diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index a17ffe9..0000000 --- a/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -# launch scripts keep LF line endings wherever the repository is cloned -*.sh text eol=lf diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 941d670..0000000 --- a/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/build*/ -*.log diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 9eb8d89..0000000 --- a/.gitmodules +++ /dev/null @@ -1,4 +0,0 @@ -[submodule "third_party/llama.cpp"] - path = third_party/llama.cpp - url = https://github.com/ggml-org/llama.cpp.git - shallow = true diff --git a/CMakeLists.txt b/CMakeLists.txt deleted file mode 100644 index 56d1ceb..0000000 --- a/CMakeLists.txt +++ /dev/null @@ -1,1444 +0,0 @@ -# Strata Engine - top-level build (P1.S1). -# -# Targets (phase-1 §P1.S1): `strata_artifact` (no CUDA dependency), `tests`. `strata_plan` and the C++ -# `strata-pack` are added when their sources exist - a target with no sources would make the build graph -# claim something the tree does not have, which is worse than an absent target. -# -# CUDA targets arrive in Phase 2. The kernels need sm_80 or newer (tf32 mma, bf16 math) and the guard -# below refuses anything older: silently building for a pre-Ampere arch would produce a binary that runs -# and is wrong about its own performance, which is the worst of both outcomes. -cmake_minimum_required(VERSION 3.24) -project(strata VERSION 0.1.39 LANGUAGES CXX) -# EXPERIMENTAL: the Intel Arc engine, the SYCL port in sycl/ (PR #423; icpx + oneMKL, docs/INTEL_ARC.md). It is its -# own project that takes the unported sources from src/; with this on, nothing below is configured. -option(STRATA_ENABLE_SYCL "EXPERIMENTAL: build the Intel Arc (SYCL) engine from sycl/ - docs/INTEL_ARC.md" OFF) -if(STRATA_ENABLE_SYCL) - if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) - message(FATAL_ERROR "STRATA_ENABLE_SYCL is a separate backend; leave STRATA_ENABLE_CUDA and STRATA_ENABLE_HIP off") - endif() - message(WARNING "STRATA_ENABLE_SYCL: the Intel Arc engine is experimental (community port, docs/INTEL_ARC.md)") - add_subdirectory(sycl) - return() -endif() -add_compile_definitions(STRATA_VERSION="${PROJECT_VERSION}") -# issue #31: release builds keep a PDB beside the exe (not shipped in it), so a minidump from a stalled engine can -# be read back to the exact source line -if(MSVC AND CMAKE_BUILD_TYPE STREQUAL "Release") - add_compile_options($<$:/Zi>) - add_link_options(/DEBUG /OPT:REF /OPT:ICF) -endif() - -# The prebuilt release (setup.py downloads it, so users need no compiler): ggml's CPU backend for any AVX2 CPU -# instead of this machine's (Strata's own AVX-512 kernels are per-file and chosen at run time either way), and -# the MSVC runtime linked in, so no Visual C++ redistributable is needed. -option(STRATA_PORTABLE "build for other PCs: AVX2 baseline, static MSVC runtime" OFF) -# EXPERIMENTAL, opt-in: an engine for CPUs without AVX2 (#394, #595, #623), compiled on that PC. ggml-cpu, which then -# computes every CPU expert row, is built for this floor instead of AVX2 or the build host: "avx" (Sandy/Ivy Bridge: -# AVX, no FMA/F16C/AVX2) or "none" (SSE4.2 + POPCNT: Nehalem/Westmere). Strata's own AVX2/AVX-512 kernels stay in the -# binary behind their CPU checks; the router lookahead gets an AVX1 kernel. Empty (the default) changes nothing. -set(STRATA_ISA_FLOOR "" CACHE STRING "experimental older-CPU build: empty (default, AVX2 floor), avx, or none (SSE4.2)") -set_property(CACHE STRATA_ISA_FLOOR PROPERTY STRINGS "" avx none) -if(NOT STRATA_ISA_FLOOR STREQUAL "" AND NOT STRATA_ISA_FLOOR STREQUAL "avx" AND NOT STRATA_ISA_FLOOR STREQUAL "none") - message(FATAL_ERROR "STRATA_ISA_FLOOR must be empty, avx or none (got '${STRATA_ISA_FLOOR}')") -endif() -if(STRATA_ISA_FLOOR AND STRATA_PORTABLE) - message(FATAL_ERROR "STRATA_ISA_FLOOR (an older-CPU build) and STRATA_PORTABLE (the AVX2 release build) exclude each other") -endif() -if(STRATA_PORTABLE AND MSVC) - set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded") -endif() - -set(CMAKE_CXX_STANDARD 20) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) -if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - set(CMAKE_BUILD_TYPE Release CACHE STRING "" FORCE) -endif() - -option(STRATA_ENABLE_CUDA "Build the CUDA targets (Phase 2+)" OFF) -# AMD gfx906 (MI50, wave64): the same .cu sources compiled as HIP through the gfx906 compat layer. The CUDA runtime and -# cuBLAS names are mapped by the headers in include/strata/platform/hip_compat/, which go first on the include path, -# and CUDA::cudart / CUDA::cublas become aliases of HIP's targets, so every CUDA target below stays as it is. This is -# separate from STRATA_ENABLE_HIP (the wave32 RDNA backend): with it on, STRATA_ENABLE_CUDA is on and -# STRATA_ENABLE_HIP stays off, so every "CUDA" branch of the tree is the one taken. -option(STRATA_HIP_GFX906 "Build the CUDA targets for AMD gfx906 through HIP (wave64 compat layer)" OFF) -if(STRATA_HIP_GFX906) - if(STRATA_ENABLE_HIP) - message(FATAL_ERROR "STRATA_HIP_GFX906 and STRATA_ENABLE_HIP are separate backends; enable only one") - endif() - set(STRATA_ENABLE_CUDA ON CACHE BOOL "" FORCE) -endif() -option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201; gfx1012/gfx1030 unvalidated)" OFF) -option(STRATA_PREFILL_MMQ "Build the optional GGML MMQ prefill path for HIP" OFF) -# CUDA: MMQ prompt kernels for Q4_K / Q5_K / Q5_1 (Unsloth's UD-Q4_K_XL experts). Off by default: the engine loads -# every kernel when it starts (CUDA_MODULE_LOADING=EAGER), so these took ~5 MB of VRAM - 1-3 expert slots - from every -# model, and the UD-Q4_K_XL prompt is SSD-bound with or without them (docs/UNSLOTH_Q4.md) -option(STRATA_MMQ_KQUANTS "Build the CUDA MMQ prompt kernels for Q4_K / Q5_K / Q5_1 experts" OFF) -option(STRATA_ORCA_Q4KS_MMQ "Build the GGML Q5_0 MMQ instance for OrcaRouter Q4_K_S" OFF) -if(STRATA_PREFILL_MMQ AND NOT STRATA_ENABLE_HIP) - message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_ENABLE_HIP=ON") -endif() -if(STRATA_ENABLE_CUDA AND STRATA_ENABLE_HIP AND NOT STRATA_HIP_GFX906) - message(FATAL_ERROR "STRATA_ENABLE_CUDA and STRATA_ENABLE_HIP are separate backends; enable only one") -endif() -if(STRATA_ENABLE_HIP) - include(cmake/hip_backend.cmake) -endif() -# The test suite and the micro benchmarks live in tests/ and bench/micro/, which the published source leaves out. -set(_strata_tests_default OFF) -if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/tests/CMakeLists.txt AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/bench/micro) - set(_strata_tests_default ON) -endif() -option(STRATA_BUILD_TESTS "Build the test suite" ${_strata_tests_default}) -option(STRATA_BUILD_CONVERSATION_TESTS "Build standalone conversation cache tests" OFF) -option(STRATA_WERROR "Treat compiler warnings as errors" OFF) - -if(STRATA_BUILD_CONVERSATION_TESTS) - enable_testing() - add_executable(conversation_cache_test src/core/conversation_cache_test.cpp) - target_include_directories(conversation_cache_test PRIVATE include) - add_test(NAME conversation_cache_test COMMAND conversation_cache_test) - add_executable(conversation_memory_test src/core/conversation_memory_test.cpp src/core/conversation_memory.cpp) - target_include_directories(conversation_memory_test PRIVATE include) - add_test(NAME conversation_memory_test COMMAND conversation_memory_test) -endif() - -if(STRATA_HIP_GFX906) - if(NOT DEFINED CMAKE_HIP_ARCHITECTURES) - set(CMAKE_HIP_ARCHITECTURES gfx906 CACHE STRING "HIP architectures" FORCE) - endif() - enable_language(HIP) - find_package(hip REQUIRED) - find_package(hipblas REQUIRED) - add_library(CUDA::cudart INTERFACE IMPORTED) - target_link_libraries(CUDA::cudart INTERFACE hip::host) - target_compile_definitions(CUDA::cudart INTERFACE STRATA_HIP_GFX906=1 __HIP_PLATFORM_AMD__=1) - target_include_directories(CUDA::cudart BEFORE INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/platform/hip_compat) - add_library(CUDA::cublas INTERFACE IMPORTED) - target_link_libraries(CUDA::cublas INTERFACE roc::hipblas CUDA::cudart) - set(CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/platform/hip_compat) - include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/platform/hip_compat) - add_compile_definitions(STRATA_HIP_GFX906=1) - message(STATUS "Strata: HIP (gfx906 compat) enabled, arch ${CMAKE_HIP_ARCHITECTURES}") - set(_strata_gpu_runtime_target CUDA::cudart) - set(_strata_gpu_blas_target CUDA::cublas) - set(_strata_gpu_include_directories ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) -elseif(STRATA_ENABLE_CUDA) - # #585: CMake links CUDA code with the STATIC runtime by default, and the targets below also link CUDA::cudart (the - # DLL's import library). MSVC with a CUDA 12.x toolkit - the experimental Pascal/Volta build - then fails with - # LNK1169 (every cudart symbol defined twice); GNU ld lets it pass. That build links the shared runtime alone. The - # ready-made engine (CUDA 13, no STRATA_EXPERIMENTAL_SM60) is unchanged; -DCMAKE_CUDA_RUNTIME_LIBRARY overrides. - if(MSVC AND STRATA_EXPERIMENTAL_SM60 AND NOT DEFINED CMAKE_CUDA_RUNTIME_LIBRARY) - set(CMAKE_CUDA_RUNTIME_LIBRARY Shared) - endif() - enable_language(CUDA) - # `enable_language(CUDA)` gives the .cu compile rules but NOT the imported targets, so `CUDA::cudart` has to - # be brought in explicitly for the host-side tests that call cudaMalloc themselves. - find_package(CUDAToolkit REQUIRED) - option(STRATA_EXPERIMENTAL_SM60 "community build for GPUs below compute capability 7.5: Pascal sm_60, Volta sm_70 (#236)" OFF) - if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES) - set(CMAKE_CUDA_ARCHITECTURES 120 CACHE STRING "CUDA architectures" FORCE) - endif() - foreach(_a IN LISTS CMAKE_CUDA_ARCHITECTURES) - string(REGEX REPLACE "-.*$" "" _base "${_a}") # 120-real / 120-virtual are still 120 - # Turing port: developed and measured on sm_120 (RTX 50); the tf32 mma in the QSA scorer has a - # portable fp32-FMA fallback, so RTX 20 (75), 30 (86), RTX 40 (89) and RTX 50 (120) build too. - # Pre-sm_75 is refused. - if(_base STREQUAL "native" OR _base STREQUAL "all" OR _base STREQUAL "all-major") - continue() - endif() - # STRATA_EXPERIMENTAL_SM60: a Pascal (sm_60, GP100-class) or Volta (sm_70, V100 / Titan V, #236) build. - # These sit below every architecture the kernels were written for, so two intrinsics are replaced below - # their arch - `__dp4a` (6.1+) and `__nanosleep` (7.0+) - in include/strata/kernels/dp4a.hpp, which is - # bit-exact for the first and merely a shorter pause for the second (sm_70 has both). Community-tested, - # not in the ready-made engine; RTX 20/30/40/50 cards must use the release engine instead. It needs a CUDA - # 12.x toolkit: CUDA 13 dropped sm_60 and sm_70 (nvcc fails CMake's compiler test with "compute_70"). - if(_base LESS 75 AND NOT STRATA_EXPERIMENTAL_SM60) - message(FATAL_ERROR - "Strata needs an NVIDIA GPU of compute capability 7.5 or newer (RTX 20 / 30 / 40 / 50 series), but " - "CMAKE_CUDA_ARCHITECTURES is '${CMAKE_CUDA_ARCHITECTURES}'. (A Pascal sm_60 or Volta sm_70 build is " - "-DSTRATA_EXPERIMENTAL_SM60=ON; upstream does not support it.)") - endif() - if(_base LESS 60) - message(FATAL_ERROR "CMAKE_CUDA_ARCHITECTURES '${CMAKE_CUDA_ARCHITECTURES}': even the experimental build " - "needs compute capability 6.0 (sm_60) or newer") - endif() - # #220 / #224: RTX 50 engines built with CUDA 12.8 crashed in the prompt path on Linux (13.0 and newer did not) - if(_base GREATER_EQUAL 120 AND CMAKE_CUDA_COMPILER_VERSION VERSION_LESS 13.0) - message(WARNING "Building for sm_${_base} (RTX 50) with CUDA ${CMAKE_CUDA_COMPILER_VERSION}: engines built with " - "CUDA 12.8 crashed on long prompts on these cards (issues #220, #224). Use CUDA 13.0 or newer.") - endif() - endforeach() - if(STRATA_EXPERIMENTAL_SM60) - # every target sees it: the Pascal / Volta code paths (the Volta prompt attention, PR #600) are compiled into this - # build only, so the ready-made engine (sm_75+) keeps exactly the code it had - add_compile_definitions(STRATA_EXPERIMENTAL_SM60=1) - endif() - message(STATUS "Strata: CUDA enabled, arch ${CMAKE_CUDA_ARCHITECTURES}") - set(_strata_gpu_runtime_target CUDA::cudart) - set(_strata_gpu_blas_target CUDA::cublas) - set(_strata_gpu_include_directories ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) -elseif(STRATA_ENABLE_HIP) - set(_strata_gpu_runtime_target strata_hip_runtime) - set(_strata_gpu_blas_target ${STRATA_HIP_BLAS_TARGETS}) - set(_strata_gpu_include_directories ${STRATA_HIP_COMPAT_INCLUDE_DIR}) -endif() - -# Warnings live on an INTERFACE target the project's own code links, NOT in add_compile_options: applied -# globally they would also hit FetchContent'd Catch2, whose -W4 warnings are not this project's to fix and -# whose /WX failures would be indistinguishable from our own. -# -# Every flag is guarded by COMPILE_LANGUAGE:CXX. Without that guard nvcc receives bare `/W4 /utf-8` and dies -# with "A single input file is required for a non-link phase" - it parses them as inputs rather than host -# flags. Host flags for CUDA must go through -Xcompiler, which is what COMPILE_LANGUAGE:CUDA does below. -add_library(strata_warnings INTERFACE) -target_compile_options(strata_warnings INTERFACE - $<$,$>:/W4> - $<$,$>:/utf-8> - $<$,$>>:-Wall> - $<$,$>>:-Wextra> - $<$,$>:-Xcompiler=/W4> - $<$:-Wall> - $<$:-Wextra>) -if(STRATA_WERROR) - target_compile_options(strata_warnings INTERFACE - $<$,$>:/WX> - $<$,$>>:-Werror> - $<$:-Werror>) -endif() - -# ---- strata_artifact ------------------------------------------------------- -# Header-only, and that is a deliberate property rather than an unfinished split: the GGUF reader and the -# scalar dequantizers hold no state worth hiding, and a header-only boundary cannot introduce a -# duplicate-symbol or missing-declaration bug into code that is already validated against the real artifact. -add_library(strata_artifact INTERFACE) -target_include_directories(strata_artifact INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) -target_link_libraries(strata_artifact INTERFACE strata_warnings) - -add_executable(strata-gguf src/artifact/gguf_reader.cpp) -target_link_libraries(strata-gguf PRIVATE strata_artifact) - -add_executable(strata-dequant src/artifact/dequant.cpp) -target_link_libraries(strata-dequant PRIVATE strata_artifact) -# this file is now nothing but the CLI entry point, and its inherited guard spells that as a "selftest" -target_compile_definitions(strata-dequant PRIVATE STRATA_DEQUANT_SELFTEST) -if(STRATA_BUILD_TESTS) - # the reader refuses a duplicate tensor name at open, naming it (a synthetic GGUF: no model, no GPU) - add_executable(gguf_reader_test src/artifact/gguf_reader_test.cpp) - target_link_libraries(gguf_reader_test PRIVATE strata_artifact) - add_test(NAME gguf_reader_test COMMAND gguf_reader_test) - # a split model's shards and their joint view: missing shard, split keys, duplicates, truncation (synthetic) - 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 ---------------------------------------------------------- -# Also header-only. A "planner" that hides state would be one whose decision is not inspectable, and the -# whole point of P1.S9 is that the decision is arithmetic you can check by hand. -add_library(strata_plan INTERFACE) -target_include_directories(strata_plan INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) -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. -if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) - add_library(strata_core STATIC src/core/device.cu src/core/pinned.cu src/platform/memory.cpp src/core/graph.cpp src/core/weights.cpp - src/core/layout.cpp) - target_include_directories(strata_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) - if(STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) - # the runtime device check (src/core/device.cu) admits the cards this build was made for (#236) - target_compile_definitions(strata_core PRIVATE STRATA_EXPERIMENTAL_SM60=1) - endif() - # The selected runtime is PUBLIC because graph.cpp is a HOST translation unit that calls cudaGraphLaunch and - # cudaEventQuery: the .cu sources get cudart through the CUDA language rules, a .cpp does not, and the - # linker error ("unresolved external symbol cudaGraphInstantiate") names the function rather than the cause. - target_link_libraries(strata_core PUBLIC strata_plan strata_warnings ${_strata_gpu_runtime_target}) - - add_executable(strata-device src/core/device_main.cpp) - target_link_libraries(strata-device PRIVATE strata_core) - - add_executable(strata-load src/core/load_main.cpp) - target_link_libraries(strata-load PRIVATE strata_core strata_kernels) - - add_executable(strata-concurrent src/core/concurrent_main.cpp) - target_include_directories(strata-concurrent PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(strata-concurrent PRIVATE strata_core strata_kernels ${_strata_gpu_runtime_target}) - - add_executable(strata-overlap src/core/overlap_main.cpp) - # a .cpp that calls cudaMemcpyAsync itself needs the toolkit headers and cudart explicitly - target_include_directories(strata-overlap PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(strata-overlap PRIVATE strata_core strata_kernels ${_strata_gpu_runtime_target}) - - # The load test needs the 34 GB artifact, so it is registered ONLY where that artifact exists. A test that - # silently skips is a test that stops running; an absent registration is visible in the configure output. - if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/pack/full/experts.bin) - add_test(NAME expert_arena_load - COMMAND strata-load --file ${CMAKE_CURRENT_SOURCE_DIR}/pack/full/experts.bin --layers 1) - set_tests_properties(expert_arena_load PROPERTIES PASS_REGULAR_EXPRESSION "per-layer checksums") - else() - message(STATUS "strata: pack/full/experts.bin absent - the expert arena load test is NOT registered") - endif() - - # ---- strata_kernels (P2.S2) ---- - # Naive first, each with a parity test against a reference that was itself validated against ggml. The - # kernels link `strata_artifact` for the scalar dequantizers, because using the VALIDATED scalar path as the - # reference is the whole point - a kernel checked against another copy of itself proves nothing. - add_library(strata_kernels STATIC src/kernels/cuda/dequant_s2.cu src/kernels/cuda/s2_gemv.cu - src/kernels/cuda/s_gemv.cu - src/kernels/cuda/s2_gemv_quads.cu - src/kernels/cuda/s2_gemv_fast.cu - src/kernels/cuda/router_top10.cu - src/kernels/cuda/quantize_act.cu - src/kernels/cuda/rope.cu - src/kernels/cuda/sampler.cu - src/kernels/cuda/s2_gemv_q8.cu - src/kernels/cuda/s2_expert_grouped.cu - src/kernels/cuda/shared_expert.cu - src/kernels/cuda/gr.cu - src/kernels/cuda/gdn.cu - src/kernels/cuda/qsa.cu - src/kernels/cuda/elementwise.cu - src/kernels/cuda/bf16_gemv.cu - src/kernels/cuda/native_mmvq.cu - src/kernels/cuda/native_bf16.cu - src/kernels/cuda/native_gr_norm.cu - src/kernels/cuda/native_moe.cu - src/kernels/cuda/native_gdn.cu - src/kernels/cuda/native_gr_postops.cu - src/kernels/cuda/native_router.cu - src/kernels/cuda/native_gdn_preprocess.cu - src/kernels/cuda/native_qsa.cu - src/kernels/cuda/native_rope.cu - src/kernels/cuda/native_ple_postops.cu - src/kernels/cuda/native_flash_attn.cu - src/kernels/cuda/native_qsa_indexer.cu - src/kernels/cuda/native_qsa_score.cu - src/kernels/cuda/ple.cu - src/kernels/cuda/kv_q8.cu - src/kernels/cuda/kv_stream.cu - src/kernels/cuda/kv_q4.cu - src/kernels/cuda/fused_gr.cu - src/kernels/cuda/cvec.cu - src/kernels/cuda/qsa_decode_attn.cu - src/kernels/cuda/qsa_prompt_attn.cu - src/kernels/cuda/fused_gdn.cu - src/kernels/cuda/dequant_bf16.cu - src/kernels/cuda/qsa_select.cu - src/kernels/cuda/verify_kernels.cu - src/kernels/cuda/iq_kernels.cu - src/kernels/ngram.cpp - src/ngram/ple_reader.cpp - src/platform/direct_file.cpp) - target_link_libraries(strata_kernels PUBLIC strata_core strata_artifact) - # perf-review D-1: the tensor-core prompt attention vs the FP32 kernel and FP64 (GPU, synthetic, no model); with - # the tests, or alone with -DSTRATA_PARITY_PROMPT_ATTN=ON. CUDA only: HIP compiles the tensor-core kernel out. - if((STRATA_BUILD_TESTS OR STRATA_PARITY_PROMPT_ATTN) AND STRATA_ENABLE_CUDA) - add_executable(qsa_prompt_attn_parity src/kernels/qsa_prompt_attn_parity.cpp) - target_include_directories(qsa_prompt_attn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) - target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels CUDA::cudart) - endif() - # #512: the top-k's active-block bound (Turing's dispatch, forced on any card by STRATA_TOPK_ACTIVE_ANY) against - # the capacity rule, selected ids bitwise - if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) - add_executable(qsa_topk_active_parity src/kernels/qsa_topk_active_parity.cpp) - target_include_directories(qsa_topk_active_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) - target_link_libraries(qsa_topk_active_parity PRIVATE strata_kernels CUDA::cudart) - add_test(NAME qsa_topk_active_parity COMMAND qsa_topk_active_parity) - set_tests_properties(qsa_topk_active_parity PROPERTIES SKIP_RETURN_CODE 77) - endif() - # the QSA selection (block scores on the warp kernel and the tensor-core one, top-k): a GPU bench with a - # scorer-vs-scorer comparison and an FP64 accuracy gate (synthetic, no model); the ctest runs a 32K context under a - # 262144-cell capacity (the top-k dispatch follows the capacity) and exits non-zero on a failed gate - if((STRATA_BUILD_TESTS OR STRATA_PARITY_PROMPT_ATTN) AND STRATA_ENABLE_HIP) - add_executable(qsa_select_bench src/kernels/qsa_select_bench.cpp) - set_source_files_properties(src/kernels/qsa_select_bench.cpp PROPERTIES LANGUAGE HIP) - target_link_libraries(qsa_select_bench PRIVATE strata_kernels strata_hip_runtime) - add_test(NAME qsa_select_bench COMMAND qsa_select_bench 32768 256 3 262144) - endif() - # plan v0.3 P6: llama.cpp's block layouts and codebook grids for the i-quant formats (MIT, third_party/ggml) - target_include_directories(strata_kernels PRIVATE third_party/ggml) - # Match the pinned llama.cpp CUDA arithmetic contract for this adapter only. - if(STRATA_ENABLE_CUDA) - set_source_files_properties(src/kernels/cuda/native_mmvq.cu src/kernels/cuda/native_bf16.cu - src/kernels/cuda/native_gr_norm.cu - src/kernels/cuda/native_moe.cu - src/kernels/cuda/native_gdn.cu - src/kernels/cuda/native_gr_postops.cu - src/kernels/cuda/native_router.cu - src/kernels/cuda/native_gdn_preprocess.cu - src/kernels/cuda/native_qsa.cu - src/kernels/cuda/native_rope.cu - src/kernels/cuda/native_ple_postops.cu - src/kernels/cuda/native_flash_attn.cu - src/kernels/cuda/native_qsa_indexer.cu - src/kernels/cuda/native_qsa_score.cu - PROPERTIES COMPILE_OPTIONS "$,,--use_fast_math>") - elseif(STRATA_ENABLE_HIP) - # Keep Q8_K's multiply and magic-bias rounding as separate FP32 operations on HIP; contraction to an - # FMA changes tie results. The embedding gather also relies on separately rounded operations. - set_source_files_properties(src/kernels/cuda/elementwise.cu src/kernels/cuda/quantize_act.cu - PROPERTIES COMPILE_OPTIONS "-ffp-contract=off") - endif() - - set(STRATA_ORACLE_SOURCE_DIR "" CACHE PATH "Pinned llama.cpp source for independent CUDA parity tests") - set(STRATA_ORACLE_BUILD_DIR "" CACHE PATH "Matching existing shared llama.cpp build") - # This oracle is a CUDA ggml build; do not pull CUDA libraries into a HIP build. - if(STRATA_ENABLE_CUDA AND STRATA_ORACLE_SOURCE_DIR AND STRATA_ORACLE_BUILD_DIR) - foreach(parity IN ITEMS native_mmvq native_bf16 native_shared native_gr_norm native_moe native_gdn native_gr_postops native_router native_gdn_preprocess native_gdn_pipeline native_qsa native_rope native_ple_postops native_flash_attn native_qsa_indexer native_qsa_score) - add_executable(${parity}_parity bench/micro/${parity}_parity.cpp) - target_include_directories(${parity}_parity PRIVATE - "${STRATA_ORACLE_SOURCE_DIR}/ggml/include" ${_strata_gpu_include_directories}) - target_compile_definitions(${parity}_parity PRIVATE GGML_SHARED GGML_BACKEND_SHARED) - target_link_libraries(${parity}_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - foreach(component IN ITEMS ggml ggml-base ggml-cpu ggml-cuda) - string(REPLACE "-" "_" variable "STRATA_ORACLE_${component}") - find_library(${variable} NAMES ${component} PATHS - "${STRATA_ORACLE_BUILD_DIR}/ggml/src" "${STRATA_ORACLE_BUILD_DIR}/ggml/src/${component}" - "${STRATA_ORACLE_BUILD_DIR}/bin" NO_DEFAULT_PATH REQUIRED) - target_link_libraries(${parity}_parity PRIVATE "${${variable}}") - endforeach() - add_test(NAME ${parity}_parity COMMAND ${parity}_parity --selftest) - if(WIN32) - set_tests_properties(${parity}_parity PROPERTIES - ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:${STRATA_ORACLE_BUILD_DIR}/bin") - endif() - endforeach() - endif() - - # ---- strata_engine (P2.S5) ----------------------------------------------------- - # The COMPOSED layer lives here and not in `strata_core`, because it calls kernels and `strata_kernels` - # already links `strata_core` - putting `gdn_layer` in core would make the two mutually dependent. A third - # library is the honest shape of the dependency graph: core knows about devices and weights, kernels know - # about arithmetic, and this one knows the ORDER the arithmetic happens in. - add_library(strata_engine STATIC src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cpp - src/core/remote_expert_opt.cu - src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp - src/core/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp src/core/peer_experts.cpp) - target_include_directories(strata_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) - target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu ${_strata_gpu_runtime_target}) - if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/file_expert_source_test.cpp") - enable_testing() - add_executable(file_expert_source_test tests/core/file_expert_source_test.cpp) - target_link_libraries(file_expert_source_test PRIVATE strata_engine) - add_test(NAME file_expert_source_test COMMAND file_expert_source_test) - set_tests_properties(file_expert_source_test PROPERTIES TIMEOUT 60) - endif() - # #477: the learned expert profile (--expert-profile-save): its order and make_profile.py's file format (CPU only) - if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/expert_profile_save_test.cpp") - enable_testing() - add_executable(expert_profile_save_test tests/core/expert_profile_save_test.cpp) - target_link_libraries(expert_profile_save_test PRIVATE strata_engine) - add_test(NAME expert_profile_save_test COMMAND expert_profile_save_test) - set_tests_properties(expert_profile_save_test PROPERTIES TIMEOUT 60) - endif() - if(STRATA_BUILD_TESTS AND STRATA_NATIVE_EXPERTS) - # native_experts.txt v2-v4 (the real packs' copies and the per-role shard column) and the arena filled from - # synthetic GGUF shards at the real expert dimensions - add_executable(expert_layout_test tests/core/expert_layout_test.cpp) - 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) - add_test(NAME native_dense_ple_key_test COMMAND native_dense_ple_key_test) - set_tests_properties(native_dense_ple_key_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) - # #369: per-layer admission on a sized (native pack) cache starts each layer in its own range - add_executable(expert_cache_per_layer_test tests/core/expert_cache_per_layer_test.cpp) - target_link_libraries(expert_cache_per_layer_test PRIVATE strata_engine) - add_test(NAME expert_cache_per_layer_test COMMAND expert_cache_per_layer_test) - set_tests_properties(expert_cache_per_layer_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) - add_executable(expert_cache_segmented_test tests/core/expert_cache_segmented_test.cpp) - 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 $ --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) - target_link_libraries(conversation_snapshot_test PRIVATE strata_engine) - add_test(NAME conversation_snapshot_test COMMAND conversation_snapshot_test) - set_tests_properties(conversation_snapshot_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) - add_executable(conversation_validation_test src/core/conversation_validation_test.cpp) - target_link_libraries(conversation_validation_test PRIVATE strata_engine) - add_test(NAME conversation_validation_test COMMAND conversation_validation_test) - set_tests_properties(conversation_validation_test PROPERTIES ENVIRONMENT "CUDA_VISIBLE_DEVICES=-1" TIMEOUT 120) - if(NOT STRATA_ENABLE_HIP AND UNIX AND NOT APPLE AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") - add_executable(conversation_transfer_test src/core/conversation_validation_test.cpp) - target_compile_definitions(conversation_transfer_test PRIVATE CONVERSATION_TEST_TRANSFERS) - target_link_options(conversation_transfer_test PRIVATE - -Wl,--wrap=cudaMemcpy -Wl,--wrap=cudaDeviceSynchronize -Wl,--wrap=cudaGetLastError) - target_link_libraries(conversation_transfer_test PRIVATE strata_engine) - add_test(NAME conversation_transfer_test COMMAND conversation_transfer_test) - set_tests_properties(conversation_transfer_test PROPERTIES ENVIRONMENT "CUDA_VISIBLE_DEVICES=-1" TIMEOUT 120) - endif() - endif() - - # `strata generate` (P2.S6). The FIRST user-facing program: everything under it is a component, and this is - # what composes them into a token. No tokenizer - the prompt arrives as ids - because Gate C1 compares logits - # against llama.cpp on the SAME ids and a tokenizer on one side of that comparison is a second variable. - # plan v0.3 P5: batched prompt processing (tensor-core GEMMs through cuBLAS). - add_library(strata_prefill STATIC src/prefill/gemm.cu src/prefill/kernels.cu src/prefill/prefill.cpp) - target_include_directories(strata_prefill PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) - target_link_libraries(strata_prefill PUBLIC strata_engine ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target}) - if(STRATA_ENABLE_HIP AND STRATA_HIPBLASLT_AVAILABLE) - target_compile_definitions(strata_prefill PRIVATE STRATA_HIPBLASLT_AVAILABLE=1) - target_link_libraries(strata_prefill PRIVATE roc::hipblaslt) - - add_executable(tune_hipblaslt tools/hip/tune_hipblaslt.cpp) - target_link_libraries(tune_hipblaslt PRIVATE hip::host roc::hipblas roc::hipblaslt) - endif() - - add_executable(strata src/program/generate.cpp) - target_include_directories(strata PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(strata PRIVATE strata_engine strata_prefill strata_spec ${_strata_gpu_runtime_target}) - - if(STRATA_ENABLE_HIP) - enable_testing() - set(_strata_hip_tests) - add_executable(hip_prefill_gemm tests/hip/prefill_gemm.cpp) - target_link_libraries(hip_prefill_gemm PRIVATE strata_prefill strata_hip_runtime) - add_test(NAME hip_prefill_gemm COMMAND hip_prefill_gemm) - list(APPEND _strata_hip_tests hip_prefill_gemm) - add_executable(hip_q2_zero tests/hip/q2_zero.cpp) - target_link_libraries(hip_q2_zero PRIVATE strata_kernels strata_hip_runtime) - add_test(NAME hip_q2_zero COMMAND hip_q2_zero) - list(APPEND _strata_hip_tests hip_q2_zero) - add_executable(hip_expert_cache_staging tests/hip/expert_cache_staging.cpp) - target_link_libraries(hip_expert_cache_staging PRIVATE strata_engine) - add_test(NAME hip_expert_cache_staging COMMAND hip_expert_cache_staging) - list(APPEND _strata_hip_tests hip_expert_cache_staging) - if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/hip/intrinsics.cpp") - add_executable(hip_intrinsics tests/hip/intrinsics.cpp) - target_link_libraries(hip_intrinsics PRIVATE strata_hip_runtime) - add_test(NAME hip_intrinsics COMMAND hip_intrinsics) - list(APPEND _strata_hip_tests hip_intrinsics) - endif() - if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/hip/handoff.cpp") - add_executable(hip_handoff tests/hip/handoff.cpp) - target_link_libraries(hip_handoff PRIVATE strata_kernels strata_hip_runtime) - add_test(NAME hip_handoff COMMAND hip_handoff) - list(APPEND _strata_hip_tests hip_handoff) - endif() - if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/hip/mapped_alias.cpp") - # #325: reports what a hipHostGetDevicePointer alias is on this stack (on Windows: the host pointer, and a - # D2D copy into it does not land - hip_handoff's timeout there). A diagnosis: exits 0 whenever it ran. - add_executable(hip_mapped_alias tests/hip/mapped_alias.cpp) - target_link_libraries(hip_mapped_alias PRIVATE strata_kernels strata_hip_runtime) - add_test(NAME hip_mapped_alias COMMAND hip_mapped_alias) - set_tests_properties(hip_mapped_alias PROPERTIES SKIP_RETURN_CODE 77) - list(APPEND _strata_hip_tests hip_mapped_alias) - endif() - if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/hip/native_qsa_score.cpp") - add_executable(hip_native_qsa_score tests/hip/native_qsa_score.cpp) - target_link_libraries(hip_native_qsa_score PRIVATE strata_kernels strata_hip_runtime) - add_test(NAME hip_native_qsa_score COMMAND hip_native_qsa_score) - list(APPEND _strata_hip_tests hip_native_qsa_score) - endif() - if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/hip/prefill_native_batch.cpp") - add_executable(hip_prefill_native_batch tests/hip/prefill_native_batch.cpp) - target_link_libraries(hip_prefill_native_batch PRIVATE strata_kernels strata_hip_runtime) - add_test(NAME hip_prefill_native_batch COMMAND hip_prefill_native_batch) - list(APPEND _strata_hip_tests hip_prefill_native_batch) - endif() - # S6: the AMD fast router against the portable kernel, bitwise - add_executable(hip_router_fast tests/hip/router_fast.cpp) - target_link_libraries(hip_router_fast PRIVATE strata_kernels strata_hip_runtime) - add_test(NAME hip_router_fast COMMAND hip_router_fast) - list(APPEND _strata_hip_tests hip_router_fast) - # S6: the RDNA4 matrix-core prompt attention (STRATA_HIP_WMMA) against the FP32 kernel and FP64; skips off gfx12 - add_executable(hip_prompt_attn_wmma src/kernels/qsa_prompt_attn_parity.cpp) - target_link_libraries(hip_prompt_attn_wmma PRIVATE strata_kernels strata_hip_runtime) - add_test(NAME hip_prompt_attn_wmma COMMAND hip_prompt_attn_wmma 32768 2048 3) - set_tests_properties(hip_prompt_attn_wmma PROPERTIES TIMEOUT 600 SKIP_RETURN_CODE 77) - list(APPEND _strata_hip_tests hip_prompt_attn_wmma) - if(STRATA_HIPBLASLT_AVAILABLE AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/hip/prefill_hipblaslt_gemm.cpp") - add_executable(hip_prefill_hipblaslt_gemm tests/hip/prefill_hipblaslt_gemm.cpp) - target_include_directories(hip_prefill_hipblaslt_gemm PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src/prefill") - target_link_libraries(hip_prefill_hipblaslt_gemm PRIVATE strata_prefill strata_hip_runtime roc::hipblaslt roc::hipblas) - add_test(NAME hip_prefill_hipblaslt_gemm COMMAND hip_prefill_hipblaslt_gemm) - set_tests_properties(hip_prefill_hipblaslt_gemm PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) - list(APPEND _strata_hip_tests hip_prefill_hipblaslt_gemm) - endif() - if(_strata_hip_tests) - set_tests_properties(${_strata_hip_tests} PROPERTIES TIMEOUT 60) - endif() - if(TARGET hip_prefill_native_batch) - set_tests_properties(hip_prefill_native_batch PROPERTIES TIMEOUT 120) - endif() - if(TARGET hip_prefill_hipblaslt_gemm) - set_tests_properties(hip_prefill_hipblaslt_gemm PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) - endif() - endif() - - add_executable(dequant_s2_parity src/kernels/dequant_s2_parity.cpp) - # The tests are HOST C++ files that call cudaMalloc/cudaMemcpy themselves, so they need the toolkit headers - # and cudart explicitly: enabling the CUDA language gives those to .cu sources automatically, but a .cpp - # target is just a C++ target and gets neither. - target_include_directories(dequant_s2_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(dequant_s2_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME dequant_s2_parity COMMAND dequant_s2_parity --selftest) - - add_executable(s2_gemv_parity src/kernels/s2_gemv_parity.cpp) - target_include_directories(s2_gemv_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(s2_gemv_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME s2_gemv_parity COMMAND s2_gemv_parity --selftest) - - add_executable(iq_parity src/kernels/iq_parity.cpp) - target_include_directories(iq_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(iq_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - # TODO 24: the i-quant fixtures are generated, not shipped. tools/iq_fixture.py needs python3 + numpy - # and the repository's vendored gguf-py (no pip installs); it writes deterministic fixtures into the - # BUILD directory (the source tree is not touched). The CTest fixture makes generation-to-test order - # explicit even under parallel execution; a fixture-generation failure fails iq_parity with it. - find_package(Python3 COMPONENTS Interpreter QUIET) - # the generator needs an interpreter WITH numpy: probe the configured one, the setup's .venv, and the - # system python3; -DIQ_FIXTURE_PYTHON=... overrides the search outright. - set(_iq_python "") - set(_iq_candidates "") - if(IQ_FIXTURE_PYTHON) - list(APPEND _iq_candidates ${IQ_FIXTURE_PYTHON}) - else() - if(Python3_Interpreter_FOUND) - list(APPEND _iq_candidates ${Python3_EXECUTABLE}) - endif() - list(APPEND _iq_candidates "${CMAKE_CURRENT_SOURCE_DIR}/.venv/bin/python" - "${CMAKE_CURRENT_SOURCE_DIR}/.venv/Scripts/python.exe" - /usr/bin/python3 - python3) - endif() - foreach(_cand IN LISTS _iq_candidates) - if(_cand STREQUAL "") - continue() - endif() - execute_process(COMMAND ${_cand} -c "import numpy" OUTPUT_QUIET ERROR_QUIET RESULT_VARIABLE _iq_probe) - if(_iq_probe EQUAL 0) - set(_iq_python "${_cand}") - break() - endif() - endforeach() - if(NOT _iq_python STREQUAL "") - add_test(NAME iq_parity_fixtures - COMMAND ${_iq_python} ${CMAKE_CURRENT_SOURCE_DIR}/tools/iq_fixture.py - --out ${CMAKE_CURRENT_BINARY_DIR}/iq_fixture) - # exit 3: numpy or the vendored gguf-py is missing (a trimmed third_party) - a skip, not a failure - set_tests_properties(iq_parity_fixtures PROPERTIES FIXTURES_SETUP iq_fixture_data SKIP_RETURN_CODE 3) - add_test(NAME iq_parity COMMAND iq_parity ${CMAKE_CURRENT_BINARY_DIR}/iq_fixture) - set_tests_properties(iq_parity PROPERTIES FIXTURES_REQUIRED iq_fixture_data SKIP_RETURN_CODE 3) - else() - message(STATUS "STRATA tests: no python3 with numpy was found (the configured interpreter and .venv " - "were probed) - the iq_parity fixtures and its test are not registered; the fixtures " - "need python3 with numpy and the repository's vendored gguf-py") - endif() - if(STRATA_ENABLE_CUDA) - # native_mmvq's multi_exact contract, bitwise: a T-column call against T single-column calls on the same Q8_1 - # bytes, with the flag off as the negative control (synthetic, GPU, no model; the control assumes 32-lane warps) - add_executable(mmvq_multi_parity src/kernels/mmvq_multi_parity.cpp) - target_include_directories(mmvq_multi_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(mmvq_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME mmvq_multi_parity COMMAND mmvq_multi_parity) - if(STRATA_HIP_GFX906) # the CUDA layout, where the negative control has power (the wave64 one is exact at every T) - add_test(NAME mmvq_multi_parity_cuda_layout COMMAND mmvq_multi_parity) - set_tests_properties(mmvq_multi_parity_cuda_layout PROPERTIES ENVIRONMENT "STRATA_MMVQ_WAVE=0") - endif() - endif() - # the IQ kernels that decode a weight part once for every column/entry, bitwise vs the per-column ones - # (GPU, synthetic, no model; --bench adds old/new timings) - add_executable(iq_multi_parity src/kernels/iq_multi_parity.cpp) - target_include_directories(iq_multi_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(iq_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME iq_multi_parity COMMAND iq_multi_parity) - # the prompt path's DeltaNet recurrence: gdn_rec_kh_kernel against gdn_rec_cols_pipe_kernel, bitwise, and the engine's - # launches against a host reference at both geometries with the negative controls (Qwen3.6 step 3; GPU, - # synthetic, no model; --bench adds timings). NVIDIA only: cp.async and the CUDA occupancy API (not on gfx906) - if(STRATA_ENABLE_CUDA AND NOT STRATA_HIP_GFX906) - add_executable(gdn_rec_parity src/prefill/gdn_rec_parity.cu) - target_link_libraries(gdn_rec_parity PRIVATE strata_prefill ${_strata_gpu_runtime_target}) - 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) - add_executable(native_grouped_parity src/kernels/native_grouped_parity.cpp) - target_include_directories(native_grouped_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(native_grouped_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME native_grouped_parity COMMAND native_grouped_parity) - add_executable(shared_expert_parity src/kernels/shared_expert_parity.cpp) - target_include_directories(shared_expert_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(shared_expert_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME shared_expert_parity COMMAND shared_expert_parity --selftest) - - add_executable(fused_gr_bench src/kernels/fused_gr_bench.cpp) - target_include_directories(fused_gr_bench PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(fused_gr_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_executable(gr_parity src/kernels/gr_parity.cpp) - target_include_directories(gr_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(gr_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME gr_parity COMMAND gr_parity --selftest) - - add_executable(gdn_parity src/kernels/gdn_parity.cpp) - 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}) - target_link_libraries(s2_gemv_q8_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME s2_gemv_q8_parity COMMAND s2_gemv_q8_parity --selftest) - - add_executable(sampler_parity src/kernels/sampler_parity.cpp) - target_include_directories(sampler_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(sampler_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME sampler_parity COMMAND sampler_parity --selftest) - set_tests_properties(sampler_parity PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=0") - # the same fixtures on the other two sampled paths: the one-block kernel and the 0.1.20 kernel - add_test(NAME sampler_parity_one_block COMMAND sampler_parity --selftest) - set_tests_properties(sampler_parity_one_block PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=1") - add_test(NAME sampler_parity_old COMMAND sampler_parity --selftest) - set_tests_properties(sampler_parity_old PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=1;STRATA_SAMPLER_ONE_BLOCK=0") - # S19: the decode QSA top-k and the greedy argmax on thread-block clusters (sm_90+) vs the one-CTA kernels, bitwise, - # captured in a graph too (GPU, synthetic, no model; skips below sm_90); --bench: per-call times - if(STRATA_ENABLE_CUDA) - add_executable(decode_cluster_parity src/kernels/decode_cluster_parity.cpp) - target_include_directories(decode_cluster_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(decode_cluster_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME decode_cluster_parity COMMAND decode_cluster_parity --selftest) - endif() - - add_executable(rope_parity src/kernels/rope_parity.cpp) - target_include_directories(rope_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(rope_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME rope_parity COMMAND rope_parity --selftest) - - add_executable(quantize_act_parity src/kernels/quantize_act_parity.cpp) - target_include_directories(quantize_act_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(quantize_act_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME quantize_act_parity COMMAND quantize_act_parity --selftest) - - # the verify window's routing in one multi-column BF16 projection + one top-k, bitwise the per-token calls - add_executable(route_window_parity src/kernels/route_window_parity.cpp) - target_include_directories(route_window_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(route_window_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME route_window_parity COMMAND route_window_parity) - - add_executable(router_top10_parity src/kernels/router_top10_parity.cpp) - target_include_directories(router_top10_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(router_top10_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME router_top10_parity COMMAND router_top10_parity --selftest) - if(STRATA_HIP_GFX906) - # the S6 router (STRATA_HIP_ROUTER_FAST=1 on gfx906) against the portable kernel, bitwise, on wave64 - add_executable(hip_router_fast tests/hip/router_fast.cpp) - target_include_directories(hip_router_fast PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(hip_router_fast PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - endif() - - add_executable(s_gemv_parity src/kernels/s_gemv_parity.cpp) - target_include_directories(s_gemv_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(s_gemv_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME s_gemv_parity COMMAND s_gemv_parity --selftest) - - add_executable(elementwise_parity src/kernels/elementwise_parity.cpp) - target_include_directories(elementwise_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(elementwise_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME elementwise_parity COMMAND elementwise_parity --selftest) - - add_executable(bf16_gemv_parity src/kernels/bf16_gemv_parity.cpp) - target_include_directories(bf16_gemv_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(bf16_gemv_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME bf16_gemv_parity COMMAND bf16_gemv_parity --selftest) - - add_executable(s_gemv_q8k_parity src/kernels/s_gemv_q8k_parity.cpp) - target_include_directories(s_gemv_q8k_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(s_gemv_q8k_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME s_gemv_q8k_parity COMMAND s_gemv_q8k_parity --selftest) - - add_executable(qsa_parity src/kernels/qsa_parity.cpp) - target_include_directories(qsa_parity PRIVATE ${_strata_gpu_include_directories}) - 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) - target_include_directories(qsa_topk_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(qsa_topk_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME qsa_topk_parity COMMAND qsa_topk_parity --selftest) - - # ---- P2.S4: the PLE n-gram hash, the IQ4_NL table read, and the PLE block ---- - # `ngram.cpp` is host-only but lives in `strata_kernels` because `ple.cu` shares its geometry constants, and - # splitting them across two libraries would only add a layer. - # - # The pack, the original GGUF and the ggml capture are all REQUIRED inputs: this test's oracles are real - # artifacts, so the working directory is pinned to the source tree and a missing input is a hard error - # INSIDE the test. A test that passes by finding nothing to compare is the failure mode this project keeps - # re-learning. - add_executable(ple_parity src/kernels/ple_parity.cpp) - target_include_directories(ple_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(ple_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - set(STRATA_PLE_FIXTURE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/bench/micro" CACHE PATH - "Directory containing required ple_in.bin and ple_out.bin parity fixtures") - add_test(NAME ple_parity COMMAND ple_parity --selftest - --in "${STRATA_PLE_FIXTURE_DIR}/ple_in.bin" --out "${STRATA_PLE_FIXTURE_DIR}/ple_out.bin" - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) - - # Plan v0.3 P7: INT8 KV storage vs a host reference and vs the FP16 path (GPU, synthetic, no model). - add_executable(kv_q8_parity src/kernels/kv_q8_parity.cpp) - target_include_directories(kv_q8_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(kv_q8_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME kv_q8_parity COMMAND kv_q8_parity) - - # KV streaming (docs/kv-streaming-design.md): streamed vs resident attention, bitwise (GPU, synthetic, no model). - add_executable(kv_stream_parity src/kernels/kv_stream_parity.cpp) - target_include_directories(kv_stream_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(kv_stream_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME kv_stream_parity COMMAND kv_stream_parity) - - # PR #120: the hybrid K8V4 KV (INT8 K + rotated Q4_0 V) vs host references (GPU, synthetic, no model). - add_executable(kv_hybrid_parity src/kernels/kv_hybrid_parity.cpp) - target_include_directories(kv_hybrid_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(kv_hybrid_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME kv_hybrid_parity COMMAND kv_hybrid_parity) - # PR #21: Q4_0 KV with Walsh-Hadamard rotation vs a host reference (GPU, synthetic, no model). - add_executable(kv_q4_parity src/kernels/kv_q4_parity.cpp) - target_include_directories(kv_q4_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(kv_q4_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME kv_q4_parity COMMAND kv_q4_parity) - add_executable(cvec_parity src/kernels/cvec_parity.cpp) - target_include_directories(cvec_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(cvec_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME cvec_parity COMMAND cvec_parity) - - # The rewritten per-hit and grouped expert kernels vs the previous ones, bitwise (GPU, synthetic, no model). - # `--bench` adds previous/new timings on engine-like shapes. - add_executable(s2_expert_grouped_parity src/kernels/s2_expert_grouped_parity.cpp) - target_include_directories(s2_expert_grouped_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(s2_expert_grouped_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME s2_expert_grouped_parity COMMAND s2_expert_grouped_parity --selftest) - - # Plan v0.3 P3: native MMVQ for 1..8 tokens (bitwise selftest + --bench timing); synthetic data, no model. - if(STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/native_mmvq_multi.cpp") - add_executable(native_mmvq_multi bench/micro/native_mmvq_multi.cpp) - target_include_directories(native_mmvq_multi PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(native_mmvq_multi PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME native_mmvq_multi COMMAND native_mmvq_multi --selftest) - endif() - - # Plan v0.3 P0.1: working-set lock of a host region (CPU only). - add_executable(platform_memory_test src/platform/memory_test.cpp) - target_link_libraries(platform_memory_test PRIVATE strata_core ${_strata_gpu_runtime_target}) - add_test(NAME platform_memory_test COMMAND platform_memory_test) - - if(CMAKE_SYSTEM_NAME STREQUAL "Linux") - add_executable(pinned_shared_test src/core/pinned_shared_test.cpp) - target_link_libraries(pinned_shared_test PRIVATE strata_core ${_strata_gpu_runtime_target}) - add_test(NAME pinned_shared_test COMMAND pinned_shared_test) - endif() - - # Plan v0.3 P2: the n-gram table read straight from the SSD. The selftest needs only the CPU and a temp file. - add_executable(ple_reader_test src/ngram/ple_reader_test.cpp) - target_include_directories(ple_reader_test PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(ple_reader_test PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME ple_reader_selftest COMMAND ple_reader_test --selftest) - - # The GPU test runs ON THE TARGET PC. `--selftest` allocates - # and writes real VRAM, so a machine without a device fails this test rather than skipping it silently - - # which is correct: an engine that targets one GPU should not report a pass for having no GPU. - if(STRATA_ENABLE_CUDA) - add_test(NAME cuda_device_selftest COMMAND strata-device --selftest) - else() - add_test(NAME hip_device_selftest COMMAND strata-device --selftest) - endif() - - # ---- P2.S5: the GraphRegistry -------------------------------------------------- - # A .cu because the test needs real kernels to capture; it links `strata_core` and not `strata_kernels`, - # because what it exercises is the capture machinery and not any kernel in it. - if(STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/graph_registry_test.cu") - add_executable(graph_registry_test bench/micro/graph_registry_test.cu) - target_include_directories(graph_registry_test PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(graph_registry_test PRIVATE strata_core ${_strata_gpu_runtime_target}) - add_test(NAME graph_registry_test COMMAND graph_registry_test) - endif() - - # ---- P2.S5's GATE: is a device<->pinned-memory handoff graph-capturable? -------------------- - # The doorbell protocol puts the D2H of `x_f` and the miss list INSIDE G[l] - that is the whole overlap. The - # phase doc says to verify this "before building on it", and this project has already lost two rounds to - # building first (a memory-only spin that DEADLOCKS on Windows, and a `cudaEventRecord` inside a capture that - # is SILENTLY DROPPED). It links only cudart: it is about the capture machinery, not about any kernel. - if(STRATA_ENABLE_CUDA AND STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/pinned_capture.cu") - add_executable(pinned_capture bench/micro/pinned_capture.cu) - target_include_directories(pinned_capture PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(pinned_capture PRIVATE ${_strata_gpu_runtime_target}) - add_test(NAME pinned_capture COMMAND pinned_capture) - endif() - - # Tells tests/CMakeLists.txt to add the CUDA-dependent Catch2 target. It cannot be declared there - # unconditionally: tests/ is added at the end of this file, but the flag has to be known before it runs. - if(STRATA_ENABLE_CUDA) - set(STRATA_CUDA_TESTS ON) - endif() -endif() - -# ---- strata_kernels_cpu (P2.S3) ---- -# -# A SEPARATE LIBRARY from `strata_kernels`, and `/arch:AVX512` is set on the SOURCE rather than on the target -# so that the flag applies only to the TU that needs it. Both parts matter: -# -# * the CPU expert kernel uses `_mm256_dpbusd_epi32` (AVX512-VNNI) and `_mm256_multishift_epi64_epi8` -# (AVX512-VBMI); without the flag MSVC reports undeclared intrinsics and never mentions AVX-512; -# * a TU compiled WITH `/arch:AVX512` may use AVX-512 in ANY of its code, so the scalar fallback and the -# test drivers must NOT be in it - otherwise the fallback is not a fallback, it is the same bet with -# worse opt-out. `cpu_require_expert_support()` therefore refuses at startup on a CPU without the -# features, and the fallback exists for tests, exactly as P2.S3 specifies. -# Plan v0.3 P6: speculation components that need no GPU. -add_library(strata_spec STATIC src/spec/suffix_drafter.cpp src/spec/controller.cpp src/spec/draft_policy.cpp) -target_include_directories(strata_spec PUBLIC include) -if(STRATA_BUILD_TESTS) - add_executable(suffix_drafter_test src/spec/suffix_drafter_test.cpp) - target_link_libraries(suffix_drafter_test PRIVATE strata_spec) - add_test(NAME suffix_drafter_test COMMAND suffix_drafter_test) - add_executable(controller_test src/spec/controller_test.cpp) - target_link_libraries(controller_test PRIVATE strata_spec) - add_test(NAME controller_test COMMAND controller_test) - add_executable(draft_policy_test src/spec/draft_policy_test.cpp) - target_link_libraries(draft_policy_test PRIVATE strata_spec) - add_test(NAME draft_policy_test COMMAND draft_policy_test) -endif() -if(STRATA_BUILD_TESTS OR STRATA_BUILD_CONVERSATION_TESTS) - # the serve loop's conversation-cache retention policy (header-only, no library to link) - add_executable(conv_cache_test src/program/conv_cache_test.cpp) - target_include_directories(conv_cache_test PRIVATE include) - add_test(NAME conv_cache_test COMMAND conv_cache_test) - # coupled draft sampling's counter and penalty-ring arithmetic (header-only, CPU) - add_executable(coupled_draft_test src/core/coupled_draft_test.cpp) - target_include_directories(coupled_draft_test PRIVATE include) - add_test(NAME coupled_draft_test COMMAND coupled_draft_test) - # the f32 -> bf16 rounding against ggml's, NaN included, over every f32 bit pattern (header-only, CPU) - add_executable(bf16_bits_test src/kernels/bf16_bits_test.cpp) - target_include_directories(bf16_bits_test PRIVATE include) - add_test(NAME bf16_bits_test COMMAND bf16_bits_test) -endif() - -add_library(strata_kernels_cpu STATIC src/kernels/cpu/expert.cpp src/kernels/cpu/pool.cpp - src/kernels/cpu/expert_layout.cpp src/kernels/cpu/q2_avx2.cpp) -target_include_directories(strata_kernels_cpu PUBLIC include) -# Plan v0.3 P6: only the kernel files get the AVX-512 / AVX2 flags; the pool and the probe run on any x86-64, -# and the engine picks the kernels at run time (cpu_avx512_ok). -if(MSVC) - set_source_files_properties(src/kernels/cpu/expert.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512") - set_source_files_properties(src/kernels/cpu/q2_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") -else() - # GCC/Clang spell it differently, and `-mavx512vnni` alone is not enough: VBMI is a separate feature bit. - set_source_files_properties(src/kernels/cpu/expert.cpp - PROPERTIES COMPILE_OPTIONS "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma") - set_source_files_properties(src/kernels/cpu/q2_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") -endif() -find_package(Threads REQUIRED) -target_link_libraries(strata_kernels_cpu PUBLIC Threads::Threads) - -# ---- plan v0.3 P6: the i-quant models' CPU experts (IQ2_XS / IQ3_XXS files) ---- -# -# The CPU computes a native expert with ggml-cpu's own dot products (`ggml_get_type_traits_cpu`), so an IQ -# weight means exactly what it means in llama.cpp. ggml is built static from a llama.cpp checkout: a local one -# with -DSTRATA_GGML_DIR=..., otherwise the pinned upstream commit (third_party/ggml/VERSION.txt). -option(STRATA_NATIVE_EXPERTS "Native (IQ) expert support through ggml-cpu" ON) -set(STRATA_GGML_DIR "" CACHE PATH "llama.cpp checkout to take ggml from (empty: fetch the pinned commit)") -if(STRATA_PREFILL_MMQ AND NOT STRATA_NATIVE_EXPERTS) - message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_NATIVE_EXPERTS=ON for GGML sources") -endif() -if(STRATA_ORCA_Q4KS_MMQ AND NOT STRATA_NATIVE_EXPERTS) - message(FATAL_ERROR "STRATA_ORCA_Q4KS_MMQ requires STRATA_NATIVE_EXPERTS=ON for GGML sources") -endif() -if(STRATA_NATIVE_EXPERTS) - enable_language(C) - set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) - set(GGML_STATIC ON CACHE BOOL "" FORCE) - set(GGML_CUDA OFF CACHE BOOL "" FORCE) - set(GGML_OPENMP OFF CACHE BOOL "" FORCE) - set(GGML_BACKEND_DL OFF CACHE BOOL "" FORCE) - set(GGML_BUILD_TESTS OFF CACHE BOOL "" FORCE) - set(GGML_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) - if(STRATA_PORTABLE) - set(GGML_NATIVE OFF CACHE BOOL "" FORCE) - foreach(_f GGML_AVX GGML_AVX2 GGML_FMA GGML_F16C GGML_BMI2) - set(${_f} ON CACHE BOOL "" FORCE) - endforeach() - elseif(STRATA_ISA_FLOOR) - # the experimental older-CPU build (STRATA_ISA_FLOOR above): one ggml-cpu for the floor, ggml's "sandybridge" - # feature set (SSE4.2 + AVX) or SSE4.2 alone - not the build host's, which may be newer than the PC it runs on. - # From the Strata_Dirigo fork (rwkeyes). ggml's defaults turn the rest on when GGML_NATIVE is off: all off here. - set(GGML_NATIVE OFF CACHE BOOL "" FORCE) - set(GGML_CPU_ALL_VARIANTS OFF CACHE BOOL "" FORCE) - set(GGML_SSE42 ON CACHE BOOL "" FORCE) - if(STRATA_ISA_FLOOR STREQUAL "avx") - set(GGML_AVX ON CACHE BOOL "" FORCE) - else() - set(GGML_AVX OFF CACHE BOOL "" FORCE) - endif() - foreach(_f GGML_AVX2 GGML_FMA GGML_F16C GGML_BMI2 GGML_AVX_VNNI GGML_AVX512 GGML_AVX512_VBMI GGML_AVX512_VNNI - GGML_AVX512_BF16 GGML_AMX_TILE GGML_AMX_INT8 GGML_AMX_BF16) - set(${_f} OFF CACHE BOOL "" FORCE) - endforeach() - else() - set(GGML_NATIVE ON CACHE BOOL "" FORCE) - endif() - # UnbiasedStrata: ggml comes from the pinned llama.cpp submodule (third_party/llama.cpp); the build fetches nothing - if(NOT STRATA_GGML_DIR) - set(STRATA_GGML_DIR ${CMAKE_CURRENT_SOURCE_DIR}/third_party/llama.cpp) - endif() - 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) - target_sources(strata_kernels_cpu PRIVATE src/kernels/cpu/native_expert.cpp src/kernels/cpu/iq_avx512.cpp - src/kernels/cpu/iq_avx2.cpp src/kernels/cpu/kq_avx2.cpp - src/kernels/cpu/kq_avx1.cpp) - target_include_directories(strata_kernels_cpu PRIVATE third_party/ggml) - if(MSVC) - set_source_files_properties(src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512") - set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") - set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") - # the router lookahead's AVX1 dot (older CPUs; called behind cpu_avx1_ok): no FMA, no 256-bit integer ops - set_source_files_properties(src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX") - else() - set_source_files_properties(src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS - "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma") - set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") - set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") - set_source_files_properties(src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "-mavx") - endif() - if(STRATA_ISA_FLOOR STREQUAL "avx") - target_compile_definitions(strata_kernels_cpu PRIVATE STRATA_ISA_FLOOR_AVX=1) - elseif(STRATA_ISA_FLOOR STREQUAL "none") - target_compile_definitions(strata_kernels_cpu PRIVATE STRATA_ISA_FLOOR_NONE=1) - endif() - target_link_libraries(strata_kernels_cpu PUBLIC ggml-cpu ggml-base) - target_compile_definitions(strata_kernels_cpu PUBLIC STRATA_NATIVE_EXPERTS=1) - # the router lookahead's dot on each rung this CPU has (AVX2, the older CPUs' AVX1) against a double reference - add_executable(router_dot_parity src/kernels/cpu/router_dot_parity.cpp) - target_link_libraries(router_dot_parity PRIVATE strata_kernels_cpu) - if(STRATA_BUILD_TESTS) - add_test(NAME router_dot_parity COMMAND router_dot_parity) - add_test(NAME router_dot_parity_avx COMMAND ${CMAKE_COMMAND} -E env STRATA_FORCE_ISA=avx $) - endif() - set(_strata_mmq_types q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0) - # #296: OrcaRouter Q4_K_S's Q5_0 experts (Q4_K and Q5_1 come with STRATA_MMQ_KQUANTS on CUDA, S5's branch) - if(STRATA_ORCA_Q4KS_MMQ) - list(APPEND _strata_mmq_types q5_0) - endif() - if(STRATA_ENABLE_CUDA) - # prompt-speed plan step 2b: llama.cpp's MMQ kernels (ggml-cuda, MIT) for the prompt path's experts, compiled - # from the same checkout as ggml above - only mmq.cuh's instances for the packs' types and the quantizer, with - # the few host symbols of ggml-cuda.cu they use in src/prefill/ggml_cuda_host.cu - if(STRATA_GGML_DIR) - set(_strata_gg ${STRATA_GGML_DIR}/ggml) - else() - set(_strata_gg ${strata_llamacpp_SOURCE_DIR}/ggml) - endif() - set(_strata_mmq ${_strata_gg}/src/ggml-cuda) - # #136: the Q2_0 pack's prompt experts on Strata's own int8 kernels (moe_fused.cu, opt-in STRATA_PF_FUSED=1; CUDA - # only: the HIP branch below keeps MMQ, and an sm_75 device or an sm_75-only build reports them unavailable) - add_library(strata_mmq STATIC src/prefill/moe_mmq.cu src/prefill/moe_fused.cu src/prefill/moe_fused_iq.cu - src/prefill/ggml_cuda_host.cu ${_strata_mmq}/quantize.cu) - # q8_0: the drafter's matrices (E-9); STRATA_ORCA_Q4KS_MMQ adds q5_0 (#296, in _strata_mmq_types), and - # STRATA_MMQ_KQUANTS q4_k q5_k q5_1, the experts of Unsloth's UD-Q4_K_XL (docs/UNSLOTH_Q4.md; the dispatch - # follows eddoursul/Strata 7706c1b), plus q6_k (Qwen3.6-35B-A3B UD-Q4_K_XL's layers 34, 38, 39) - set(_strata_mmq_cuda_types ${_strata_mmq_types}) - if(STRATA_MMQ_KQUANTS) - list(APPEND _strata_mmq_cuda_types q4_k q5_k q5_1 q6_k) - endif() - foreach(_t IN LISTS _strata_mmq_cuda_types) - target_sources(strata_mmq PRIVATE ${_strata_mmq}/template-instances/mmq-instance-${_t}.cu) - endforeach() - target_include_directories(strata_mmq PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq} - PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) - target_compile_options(strata_mmq PRIVATE $<$:--extended-lambda -use_fast_math>) - if(MSVC) - target_compile_options(strata_mmq PRIVATE $<$:-Xcompiler=/bigobj>) - endif() - target_link_libraries(strata_mmq PUBLIC ggml-base ${_strata_gpu_runtime_target}) - if(STRATA_MMQ_KQUANTS) - target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_KQUANTS=1) - endif() - if(STRATA_ORCA_Q4KS_MMQ) - target_compile_definitions(strata_mmq PRIVATE STRATA_ORCA_Q4KS_MMQ=1) - endif() - target_link_libraries(strata_prefill PUBLIC strata_mmq) - target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1 STRATA_PREFILL_FUSED=1) - if(STRATA_BUILD_TESTS) - # #136: the fused int8 experts against a double-precision reference and the MMQ path (exit 77 below sm_80) - add_executable(prefill_fused_moe_test tests/cuda/prefill_fused_moe_test.cpp) - target_link_libraries(prefill_fused_moe_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) - add_test(NAME prefill_fused_moe_test COMMAND prefill_fused_moe_test) - set_tests_properties(prefill_fused_moe_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) - # #136: the same for the native packs' formats (IQ2_XXS IQ2_XS IQ2_S IQ3_XXS IQ3_S IQ4_XS, down Q2_0 IQ4_NL) - add_executable(prefill_fused_iq_test tests/cuda/prefill_fused_iq_test.cpp) - target_link_libraries(prefill_fused_iq_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) - add_test(NAME prefill_fused_iq_test COMMAND prefill_fused_iq_test) - set_tests_properties(prefill_fused_iq_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) - endif() - if(STRATA_BUILD_TESTS AND STRATA_MMQ_KQUANTS) - # the UD-Q4_K_XL expert formats through MMQ against ggml's dequantized weights (synthetic, a few seconds) - add_executable(prefill_mmq_kquant_test tests/cuda/prefill_mmq_kquant_test.cpp) - target_link_libraries(prefill_mmq_kquant_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) - add_test(NAME prefill_mmq_kquant_test COMMAND prefill_mmq_kquant_test) - set_tests_properties(prefill_mmq_kquant_test PROPERTIES TIMEOUT 120) - endif() - elseif(STRATA_PREFILL_MMQ) - # Compile only the pinned GGML MMQ and activation-quantizer sources used by prefill. This uses - # common.cuh's native HIP path without enabling a second GGML HIP backend. - if(STRATA_GGML_DIR) - set(_strata_gg "${STRATA_GGML_DIR}/ggml") - else() - set(_strata_gg "${strata_llamacpp_SOURCE_DIR}/ggml") - endif() - set(_strata_mmq "${_strata_gg}/src/ggml-cuda") - if(NOT EXISTS "${_strata_mmq}/common.cuh" OR NOT EXISTS "${_strata_mmq}/quantize.cu") - message(FATAL_ERROR "The selected GGML source is missing the ggml-cuda MMQ sources: ${_strata_mmq}") - endif() - set(_strata_mmq_sources - src/prefill/moe_mmq.cu - src/prefill/ggml_cuda_host.cu - "${_strata_mmq}/quantize.cu") - foreach(_t IN LISTS _strata_mmq_types) - list(APPEND _strata_mmq_sources "${_strata_mmq}/template-instances/mmq-instance-${_t}.cu") - endforeach() - set_source_files_properties(${_strata_mmq_sources} PROPERTIES LANGUAGE HIP) - add_library(strata_mmq STATIC ${_strata_mmq_sources}) - target_include_directories(strata_mmq - PRIVATE "${_strata_gg}/include" "${_strata_gg}/src" "${_strata_mmq}" - PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) - target_compile_definitions(strata_mmq PRIVATE GGML_USE_HIP=1) - if(STRATA_ORCA_Q4KS_MMQ) - target_compile_definitions(strata_mmq PRIVATE STRATA_ORCA_Q4KS_MMQ=1) - endif() - target_link_libraries(strata_mmq PUBLIC ggml-base hip::host roc::hipblas) - target_link_libraries(strata_prefill PUBLIC strata_mmq) - target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1) - - # Numerical diagnostic: synthetic layouts by default, optional first-expert IQ3_XXS/IQ4_NL check with a pack. - add_executable(hip_prefill_mmq_parity tests/hip/prefill_mmq_parity.cpp) - target_include_directories(hip_prefill_mmq_parity PRIVATE "${_strata_gg}/include") - target_link_libraries(hip_prefill_mmq_parity PRIVATE strata_prefill) - add_test(NAME hip_prefill_mmq_parity COMMAND hip_prefill_mmq_parity) - set_tests_properties(hip_prefill_mmq_parity PROPERTIES TIMEOUT 120) - list(APPEND _strata_hip_tests hip_prefill_mmq_parity) - endif() - if(STRATA_ENABLE_HIP) - # Optional real-model diagnostic: pass the GGUF shard containing the native PLE key. - add_executable(hip_ple_iq4 tests/hip/ple_iq4.cpp) - target_link_libraries(hip_ple_iq4 PRIVATE strata_kernels strata_hip_runtime ggml-base) - endif() - if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) - add_executable(native_expert_parity src/kernels/native_expert_parity.cpp) - target_include_directories(native_expert_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(native_expert_parity PRIVATE strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) - add_executable(native_expert_bench src/kernels/native_expert_bench.cpp) - target_include_directories(native_expert_bench PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(native_expert_bench PRIVATE strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) - if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) - # Unsloth UD-Q4_K_XL's three expert pairs (and Q8_0 alone, its embedding) on synthetic ggml-quantized weights - # at 2560/640: GPU and CPU experts against the float reference, GPU dequantizers against to_float. - # q4_K/q5_0 and q5_0/q8_0: a plain llama-quantize "_M" tier GGUF (not Unsloth's dynamic method) commonly - # puts Q5_0 on down-projections (sometimes gate/up too) where this model's native_experts.txt had no GPU - # kernel for it before; q5_0/q5_0 (both roles Q5_0) is left out of this list since stacking the same - # lower-precision format on both roles pushes the GPU path over this test's 3% threshold (quantization - # noise, not a kernel bug -- see the PR). - foreach(_pair q4_K/q5_1 q4_K/q8_0 q5_K/q8_0 q8_0/q8_0 q4_K/q5_0 q5_0/q8_0 q6_K/q8_0) - string(REPLACE "/" "_" _name "${_pair}") - add_test(NAME native_expert_parity_${_name} COMMAND native_expert_parity --synthetic ${_pair}) - set_tests_properties(native_expert_parity_${_name} PROPERTIES TIMEOUT 120) - endforeach() - # Qwen3.6-35B-A3B's expert pairs at its 2048 x 512 (docs/qwen36-port/step3-experts.md): UD-IQ3_XXS's - # IQ2_S/IQ3_XXS (37 layers) and IQ2_S/IQ4_XS (34, 38, 39); UD-Q4_K_XL's Q4_K/Q5_K (37), Q4_K/Q6_K (34, 38) - # and Q5_K/Q6_K (39). The 256-value down types need n_ff % 256 == 0, which 512 has and 640 has not. - foreach(_pair iq2_s/iq3_xxs iq2_s/iq4_xs q4_K/q5_K q4_K/q6_K q5_K/q6_K) - string(REPLACE "/" "_" _name "${_pair}") - add_test(NAME native_expert_parity_qwen36_${_name} COMMAND native_expert_parity --geom 2048x512 --synthetic ${_pair}) - set_tests_properties(native_expert_parity_qwen36_${_name} PROPERTIES TIMEOUT 120) - endforeach() - add_test(NAME native_expert_parity_q5_1_min COMMAND native_expert_parity --q5_1-min) - # #290: the BF16 token embedding (--embd-gguf) gathered and dequantized bit for bit - add_test(NAME native_expert_parity_bf16_embd COMMAND native_expert_parity --bf16-embd) - # a 256-value down type at Flash-Next's n_ff 640 is refused by native_expert_supported, not run - add_test(NAME native_expert_parity_refuses_q6_K_down_at_640 COMMAND native_expert_parity --synthetic q4_K/q6_K) - set_tests_properties(native_expert_parity_refuses_q6_K_down_at_640 PROPERTIES WILL_FAIL TRUE) - 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 - if(STRATA_ENABLE_CUDA AND STRATA_BUILD_TESTS) - add_executable(ple_q5_parity src/kernels/ple_q5_parity.cpp) - target_link_libraries(ple_q5_parity PRIVATE strata_kernels strata_artifact ggml-base ${_strata_gpu_runtime_target}) - add_executable(q5_projection_parity src/kernels/q5_projection_parity.cpp) - target_include_directories(q5_projection_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(q5_projection_parity PRIVATE strata_kernels strata_artifact ggml-base ${_strata_gpu_runtime_target}) - # #291: the FP8 PLE table (tools/ple_fp8_pack.py) through PleTable vs the checkpoint's own values - add_executable(ple_fp8_parity src/kernels/ple_fp8_parity.cpp) - target_link_libraries(ple_fp8_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - endif() -endif() - -if(STRATA_ENABLE_CUDA AND STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/hit_cpu_order_parity.cu") - add_executable(hit_cpu_order_parity bench/micro/hit_cpu_order_parity.cu) - target_link_libraries(hit_cpu_order_parity PRIVATE strata_kernels strata_kernels_cpu ${_strata_gpu_runtime_target}) -endif() - -if(STRATA_BUILD_TESTS) - if(WIN32) - add_executable(pool_affinity_test src/kernels/cpu/pool_affinity_test.cpp) - target_link_libraries(pool_affinity_test PRIVATE strata_kernels_cpu) - add_test(NAME pool_affinity_test COMMAND pool_affinity_test) - elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") - add_executable(pool_affinity_test src/kernels/cpu/pool_affinity_linux_test.cpp) - target_link_libraries(pool_affinity_test PRIVATE strata_kernels_cpu) - add_test(NAME pool_affinity_test COMMAND pool_affinity_test) - endif() - # Plan v0.3 P6: one expert applied to several tokens, bitwise vs the single-token kernel (synthetic, CPU only). - # plan v0.3 P5: the device dequantizers vs the artifact's CPU dequantizers on the real shards (not a ctest: needs - # the 38 GB model; run it by hand or from tools/gpu_session.py) - if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) # #93: it needs the device dequantizers and a GPU runtime - add_executable(dequant_bf16_test src/kernels/dequant_bf16_test.cpp) - target_link_libraries(dequant_bf16_test PRIVATE strata_kernels strata_artifact ${_strata_gpu_runtime_target}) - endif() - - add_executable(expert_multi_test src/kernels/cpu/expert_multi_test.cpp) - target_link_libraries(expert_multi_test PRIVATE strata_kernels_cpu) - add_test(NAME expert_multi_test COMMAND expert_multi_test) - - add_executable(expert_parity src/kernels/cpu/expert_parity.cpp) - target_link_libraries(expert_parity PRIVATE strata_kernels_cpu) - # The pack is a REQUIRED input, not an optional one: this test compares against a real expert blob, and a - # missing file would otherwise be reported as a pass by a test that skipped everything. - add_test(NAME expert_parity COMMAND expert_parity --selftest - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) - - add_executable(pool_test src/kernels/cpu/pool_test.cpp) - target_link_libraries(pool_test PRIVATE strata_kernels_cpu) - add_test(NAME pool_test COMMAND pool_test --selftest WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) - # issue #29: tiny batches with sleeping workers, as on a big-VRAM card; a hang fails it - add_executable(pool_stress src/kernels/cpu/pool_stress.cpp) - target_link_libraries(pool_stress PRIVATE strata_kernels_cpu) - add_test(NAME pool_stress COMMAND pool_stress 20) - - if(UNIX AND NOT APPLE) - add_executable(direct_file_async_test tests/platform/direct_file_async.cpp src/platform/direct_file.cpp) - target_include_directories(direct_file_async_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) - target_link_libraries(direct_file_async_test PRIVATE Threads::Threads) - add_test(NAME direct_file_async_test COMMAND direct_file_async_test) - endif() -endif() - -if(STRATA_BUILD_TESTS) - enable_testing() - # Model-level checks may be absent from source distributions. - if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/CMakeLists.txt") - add_subdirectory(tests) - endif() -endif() - -# ---- HIP gfx906: every CUDA source of the tree (and the ggml-cuda MMQ sources) is compiled as HIP ---- -if(STRATA_HIP_GFX906) - file(GLOB_RECURSE _strata_cu CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/*.cu ${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/*.cu - ${CMAKE_CURRENT_SOURCE_DIR}/tools/vision/*.cu) - if(_strata_mmq) - file(GLOB _strata_mmq_cu ${_strata_mmq}/*.cu ${_strata_mmq}/template-instances/*.cu) - list(APPEND _strata_cu ${_strata_mmq_cu}) - target_compile_definitions(strata_mmq PRIVATE GGML_USE_HIP) - endif() - set_source_files_properties(${_strata_cu} PROPERTIES LANGUAGE HIP) -endif() - -# ---- UnbiasedStrata: one binary = the engine above plus a C++ front end (frontend/) ------------------------------ -# The front end takes its tokenizer, its Jinja chat-template engine and its HTTP library from the same pinned -# llama.cpp checkout that ggml comes from. ggml is already configured above, so llama.cpp's own build reuses it. -if(STRATA_ENABLE_CUDA AND STRATA_NATIVE_EXPERTS) - set(LLAMA_BUILD_MTMD ON CACHE BOOL "" FORCE) - set(LLAMA_BUILD_COMMON ON CACHE BOOL "" FORCE) - foreach(_o LLAMA_BUILD_TESTS LLAMA_BUILD_TOOLS LLAMA_BUILD_EXAMPLES LLAMA_BUILD_SERVER LLAMA_BUILD_APP - LLAMA_BUILD_UI LLAMA_USE_PREBUILT_UI LLAMA_OPENSSL LLAMA_LLGUIDANCE LLAMA_ALL_WARNINGS) - set(${_o} OFF CACHE BOOL "" FORCE) - endforeach() - add_subdirectory(${STRATA_GGML_DIR} ${CMAKE_BINARY_DIR}/llama.cpp EXCLUDE_FROM_ALL) - find_package(Threads REQUIRED) - add_executable(unbiased-strata frontend/main.cpp frontend/engine_entry.cpp) - target_include_directories(unbiased-strata PRIVATE ${_strata_gpu_include_directories} ${STRATA_GGML_DIR}/vendor) - target_link_libraries(unbiased-strata PRIVATE strata_engine strata_prefill strata_spec ${_strata_gpu_runtime_target} - llama-common llama mtmd cpp-httplib Threads::Threads) -endif() diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 6687a42..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Niko1221 and the Strata contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/Makefile b/Makefile deleted file mode 100644 index 3be25e9..0000000 --- a/Makefile +++ /dev/null @@ -1,68 +0,0 @@ -# UnbiasedStrata build. Needs CMake 3.24+, a C++20 compiler and the CUDA toolkit. Nothing is downloaded. -BUILD_DIR ?= build -# One binary for every single NVIDIA GPU from Pascal up: GTX 10 (61), Volta (70), RTX 20 / GTX 16 (75), RTX 30 (86), -# RTX 40 (89), RTX 50 (120). Pascal and Volta are the experimental build (STRATA_EXPERIMENTAL_SM60; needs a CUDA 12.x -# toolkit, 13 dropped them): any arch below 75 in the list switches it on. sm_120 needs CUDA 12.8+. An arch the -# installed nvcc cannot compile is dropped from the list with a note (CUDA 12.4 has no 120; CUDA 13 has no 61 / 70), -# so the default builds on any toolkit; `make build CUDA_ARCHS=61` keeps a single-card build short -# (docs/qwen36-port/pascal-build.md). -CUDA_ARCHS ?= 61;70;75;86;89;120 -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) - -.PHONY: build clean - -build: - @test -f third_party/llama.cpp/ggml/CMakeLists.txt || \ - { echo "third_party/llama.cpp is empty: run 'git submodule update --init' first"; exit 1; } - @git -C third_party/llama.cpp apply --check --reverse ../../patches/llama.cpp-qwen3-coder-any-argument-order.patch 2>/dev/null || \ - git -C third_party/llama.cpp apply ../../patches/llama.cpp-qwen3-coder-any-argument-order.patch - cmake -S . -B $(BUILD_DIR) -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON \ - -DSTRATA_PORTABLE=ON -DSTRATA_MMQ_KQUANTS=ON -DSTRATA_BUILD_TESTS=OFF "-DCMAKE_CUDA_ARCHITECTURES=$(CUDA_ARCHS)" $(SM60_FLAG) $(CMAKE_EXTRA) - cmake --build $(BUILD_DIR) -j $(JOBS) --target unbiased-strata - @echo "built: $(BUILD_DIR)/unbiased-strata" - -clean: - rm -rf $(BUILD_DIR) - -# Protocol and child supervision regressions; no CUDA/model required. -.PHONY: test-frontend -test-frontend: - mkdir -p $(BUILD_DIR)/frontend-tests - $(CXX) -std=c++20 -Wall -Wextra -Werror frontend/child_watch_test.cpp -o $(BUILD_DIR)/frontend-tests/child-watch-test - $(BUILD_DIR)/frontend-tests/child-watch-test - $(CXX) -std=c++20 -Wall -Wextra -Werror frontend/engine_test.cpp -o $(BUILD_DIR)/frontend-tests/engine-test - $(BUILD_DIR)/frontend-tests/engine-test - $(CXX) -std=c++20 -Wall -Wextra -Werror -pthread frontend/engine_backpressure_test.cpp -o $(BUILD_DIR)/frontend-tests/engine-backpressure-test - $(BUILD_DIR)/frontend-tests/engine-backpressure-test - -# Model-template compatibility; CPU only, after the regular build produced llama libraries. -.PHONY: test-chat-parser -test-chat-parser: - @test -n "$(MODEL)" || { echo 'set MODEL to the first GGUF shard'; exit 2; } - mkdir -p $(BUILD_DIR)/frontend-tests - $(CXX) -std=c++20 -O0 -Ifrontend -Ithird_party/llama.cpp/include -Ithird_party/llama.cpp/common \ - -Ithird_party/llama.cpp/ggml/include -Ithird_party/llama.cpp/vendor -Ithird_party/llama.cpp/tools/mtmd \ - frontend/chat_parser_test.cpp \ - -o $(BUILD_DIR)/frontend-tests/chat-parser-test $(BUILD_DIR)/llama.cpp/tools/mtmd/libmtmd.a \ - $(BUILD_DIR)/llama.cpp/vendor/hash/libvendor-hash.a $(BUILD_DIR)/llama.cpp/common/libllama-common.a \ - $(BUILD_DIR)/llama.cpp/src/libllama.a $(BUILD_DIR)/llama.cpp/vendor/cpp-httplib/libcpp-httplib.a \ - $(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) diff --git a/README.md b/README.md deleted file mode 100644 index 838eec9..0000000 --- a/README.md +++ /dev/null @@ -1,261 +0,0 @@ -# UnbiasedStrata - -[Strata](https://github.com/Niko1221/Strata)'s inference engine and llama.cpp's tokenizer, chat-template and -HTTP code, built into one binary that serves Qwen3.8-Flash-Next (one 24 GB+ card, 128 GB RAM) and -Qwen3.6-35B-A3B (any single NVIDIA card from 6 to 32 GB, Pascal or newer) over an OpenAI-style API. No -network is needed to build or run it: rsync the source, run `make build`, start the binary. No Python, no -installer. - -## Requirements - -| | Build | Run | -| --- | --- | --- | -| Network access | no | no | -| CMake 3.24+, C++20 compiler (tested: g++ 13.3) | yes | no | -| CUDA | toolkit 12.x (tested: 12.4 and 12.8; 12.8+ for RTX 50; CUDA 13 dropped Pascal and Volta) | `libcudart.so.12`, `libcublas.so.12`, `libcublasLt.so.12` and the NVIDIA driver | - -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 - -``` -rsync -a UnbiasedStrata/ host:UnbiasedStrata/ # or: git clone, then git submodule update --init -ssh host 'cd UnbiasedStrata && make build' # produces build/unbiased-strata -``` - -The tree is 6 MB plus the pinned llama.cpp submodule in `third_party/` (about 170 MB checked out). The -build fetches nothing. `make build JOBS=N` sets the job count; `CUDA_ARCHS` defaults to -`61;70;75;86;89;120`, one binary for every card from Pascal up, minus any architecture the installed -`nvcc` cannot compile (12.4 has no 120, 13 has no 61 or 70; the build says what it dropped). `make build -CUDA_ARCHS=61` builds for one card in about 3 minutes. An architecture below 75 in the list turns on -`STRATA_EXPERIMENTAL_SM60`, the Pascal/Volta build (FP32 and dp4a paths; no tensor cores). The -chat-parser patch in `patches/` is applied to the submodule at configure time. - -## 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 `--`: `--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) | -| Sampling | greedy unless `temperature` > 0 | -| Reasoning | returned as `reasoning_content`; `"reasoning_effort": "none"` turns it off | -| Tools | OpenAI format (`tools`, `tool_calls`) | -| Images | with `--mmproj`, OpenAI `image_url` parts holding a base64 `data:image/...` URL (PNG, JPEG, BMP or GIF), several per message | -| Not supported | more than one GPU, batch requests | - -Images: `--mmproj /models/mmproj-Qwen3.8-Flash-Next-BF16.gguf` loads the model's own vision encoder (from the same -Hugging Face repository as the GGUF; 0.9 GB). The encoder runs on the CPU, so the card keeps its expert cache: -about 25 s and 1,000 prompt tokens for a 1-megapixel screenshot on 8 threads, 0.2 s for a small image; a repeated -image is served from a cache. `GET /v1/models` then lists `image` under `input_modalities`. Without `--mmproj` an -image request is refused with a 400. - -The engine runs as a child process. When it exits or its stall watchdog fires, the front end exits with a failure -status, for a supervisor such as systemd (`Restart=on-failure`) to restart; `/health` and `/v1/models` answer 503 -while the engine is down. Reasoning streams as it is generated; content and tool calls are sent once the whole -message is parsed, so a partial tool-call JSON never changes arguments already sent. `make test-frontend` checks -the child handling and the protocol without a model; `make test-chat-parser MODEL=` checks the chat -template and tool-call parsing against the real GGUF. - -## 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), -directory `IQ3_XXS`, revision `ed59f920`. No other model, quantization or pruned variant is supported. The -draft (MTP) head is required. - -Everything below must be on disk before start. Nothing is fetched. - -| What | Size | SHA-256 or source | -| --- | --- | --- | -| `Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf` (weights) | 47.04 GB | `219ea929900dfa9ef091f3aa473fdba6874b65fcb36526d7d851ac9e95856d15` | -| `Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf` (n-gram table), beside shard 1 | 28.80 GB | `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113` | -| Pack: `index.txt`, `dense.bin`, `native_experts.txt`, `conversions.json`, `expert-profile.bin` | 1.5 GB | made once with upstream's tools; not published yet | -| Draft head: `experts.bin`, `dense.bin`, `dense.txt`, `draft_vocab.bin` | 0.8 GB | made once with upstream's tools; not published yet | - -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. - -| | | -| --- | --- | -| Build | from an rsynced tree with no git metadata; the binary holds no download code | -| Serving | chat, streaming, reasoning, tool calls; a coding agent (pi) wrote and ran a program through it | -| RTX 4090 (24 GB), 82 GB RAM, Debian, bare metal | serving with tool calls and images, through pi (file attachments and clipboard paste) and curl, over several days of use | -| Start from local disk | 19 s with the files in the OS file cache | -| 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. - -| | Generation, tokens/s | Prompt, tokens/s | -| --- | --- | --- | -| This fork | 107 (87 to 116) | 2,483 | -| Upstream, with `--pool-workers 15 --ple-io ram` | 78 (61 to 93) | 2,439 | -| Upstream, arguments as its installer writes them | 20 (16 to 21) | 2,368 | - -Upstream as installed started 127 CPU workers on the container's 32 vCPUs and read the n-gram table from -disk per token; the middle row removes both. The remaining gap to the fork is not explained yet: the two -builds differ in compile flags and in how the n-gram table is held in RAM, and each row is a single run. - -## Known problems - -- Text in a message that looks like a control token (``, ``) is tokenized as that control - token. Upstream's tokenizer keeps it as plain text. -- Replies are not reproducible token for token between runs or between this fork and upstream, even with - greedy sampling, so "same output" cannot be checked by comparing text. - For Qwen3.6-35B-A3B the cause is traced: an expert the card does not hold is computed by a different - kernel on the CPU, and the cache keeps changing which experts those are for the first few requests; replies - diverge only where two tokens are within about 0.3 logits, and every state holds to llama.cpp's logits. - `--adapt-every 0 --suffix-draft 0` makes a request repeat token for token. `--pcie-frac 1.0` does too - only while a layer misses fewer than 16 experts per window; past that the rest are computed on the CPU. -- Qwen3.6-35B-A3B: between user turns the prompt cache reuses the previous prompt but not the previous reply, - because the model's template re-renders an earlier reply without its reasoning. Tool loops reuse nearly - everything (1,867 of 1,948 tokens in a pi session); `chat_template_kwargs.preserve_thinking` with - `reasoning_content` sent back reuses the reply too, at the cost of keeping old reasoning in context. - A tool call arrives as one delta, not streamed. Images are checked on one screenshot only, and not - against llama.cpp; the RTX 50 and Volta builds have not - run on a card. Prompt processing is slower than llama.cpp with every expert on the card, at 6 GB, and for long - prompts on a GTX 1080 Ti. - -## Compared with upstream Strata (6f32ec0) - -| | Upstream | This fork | -| --- | --- | --- | -| Engine source (`src/`, `include/`) | 272 files | 58 files changed for the Qwen3.6 port (the model geometry read from the GGUF, the plain-residual block, dense attention, the SiLU-gated DeltaNet, the expert kernels for the UD quantizations, the VRAM planner, the drafter pack) plus retrying reads from slow stores; docs/qwen36-port/ has the per-step notes | -| Build | clones llama.cpp during CMake | pinned submodule, fetches nothing; one patch, applied at configure time: tool-call arguments in any order (see UPSTREAM.md) | -| Setup | Python installer downloads the model and builds the pack and draft head | none; files must already exist | -| Server | Python | C++, in the same binary (`frontend/`), with the image encoder from llama.cpp's `mtmd` | -| Python | 33,745 lines | 0 | -| C, C++ and CUDA | 208,254 lines (with tests and the Intel port) | 84,086 lines | -| Tracked files | 851, 27 MB | 292, 6 MB | -| Configurations | several models, NVIDIA, AMD and Intel, Linux and Windows, multi-GPU | two models, one NVIDIA card (Pascal to RTX 50), Linux | - -## Credits and licence - -MIT, as upstream. The engine is the work of Niko1221 and the Strata contributors; see [LICENSE](LICENSE) and -[UPSTREAM.md](UPSTREAM.md). llama.cpp and ggml are MIT. The model files have their own licences. diff --git a/UPSTREAM.md b/UPSTREAM.md deleted file mode 100644 index a9749eb..0000000 --- a/UPSTREAM.md +++ /dev/null @@ -1,122 +0,0 @@ -# Relationship to upstream - -## Sources - -| What | Where | Version | -| --- | --- | --- | -| Engine | https://github.com/Niko1221/Strata | commit `6f32ec070f23ced9f50e704d854d775da52591ab`, engine 0.1.39 | -| ggml (CPU backend, CUDA matrix kernels) | https://github.com/ggml-org/llama.cpp, as the submodule `third_party/llama.cpp` | commit `3cf03257f219afbe7334045ff7c6a06ac68c627d`, the one upstream Strata pins | - -The first commit of this repository is the upstream snapshot as published. One file was not imported: -`bench/results/2026-09-30-community-rtx-5090/engine.log`, which upstream's own ignore rules exclude. -`git diff HEAD -- src include CMakeLists.txt` shows every change to the engine and its build. - -## What this fork changed - -- **Build:** ggml is taken from the submodule. Upstream cloned llama.cpp during the build. -- **Removed:** the Python installer and launchers, the Python server and web app, the Python tools, the - Intel SYCL port, Docker files, benchmark results, the test suite, translations, and all docs except - `docs/upstream/DETAILS.md` and the paper. -- **Added:** `frontend/`, the C++ front end (tokenizer, chat template, output parser and HTTP API, using - llama.cpp's code from the submodule), and a build target that links it with the engine into one binary. -- **ggml / llama.cpp common (`third_party/llama.cpp`):** one change, kept as - `patches/llama.cpp-qwen3-coder-any-argument-order.patch`, applied to the submodule's working tree at CMake - configure time (and by `make build`); Qwen3.6's template routes to the same parser: - 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 - dropped silently: the client got `finish_reason=stop` and an empty answer (2026-10-08). -- **Engine source (`src/`, `include/`):** three changes, all for loading from a slow or remote store. The - engine's own program is compiled into the binary with its entry point renamed; the front end starts it - as a child process. - - `include/strata/platform/robust_read.hpp` (new): positional reads that retry an error a network store - gives for a moment, and lower the number of parallel readers while it does. - - `src/core/expert_source.cpp`: the expert loader reads through it, reports progress, and names the file, - offset and error when it fails. - - `src/kernels/ngram.cpp`: `--ple-io ram` reads the n-gram table into memory of its own with 16 readers, - where upstream locked the file mapping (which fails under a container's `ulimit -l`). - -Code paths for other models, AMD cards and Windows are still present in the engine source. They are not -built by `make build`, not tested and not supported here. - -## Prepared model files - -The pack and the draft head are produced once with upstream Strata's tools at the commit above. These are -the commands that were used, with `U` an upstream checkout, `G` this repository's -`third_party/llama.cpp/gguf-py`, and Python 3 with `numpy` and `regex`: - -``` -export STRATA_GGUF_PY=$G -# the pack, from the model's first shard (the second must be beside it) -python $U/tools/iq_pack.py --gguf Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf --out pack-iq3-xxs -cp $U/data/expert-profile.bin pack-iq3-xxs/ - -# the draft head, from the original checkpoint's 31 draft-head tensors (about 5 GB, fetched over HTTP) -python $U/tools/mtp_fetch.py fetch --out mtp-bf16 -python $U/tools/mtp_fetch.py verify --out mtp-bf16 -python $U/tools/mtp_pack.py --src mtp-bf16 --experts q2_0 --out mtp-bf16/mtp-q2_0.gguf -python $U/tools/mtp_rt.py --gguf mtp-bf16/mtp-q2_0.gguf --out mtp -cp $U/data/draft_vocab.bin mtp/ -``` - -The model shards used were revision `ed59f92082b1e93c0e96d60a8b11aab089b52f09` of -ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF, verified against their published SHA-256 checksums. The -prepared files have not been published yet. Building them twice gave the same bytes; their SHA-256: - -``` -68beec784ea64aeecace591b33debb8ba331a9ad257a3e1b68c5c701dd22b267 pack-iq3-xxs/conversions.json -d2af3d8331e5c7a1985d1d589747230f9d56719a6d33c7cddc9ee6b81cde6b13 pack-iq3-xxs/dense.bin -8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf pack-iq3-xxs/expert-profile.bin -1afe12b36cd2d13bf122b741fa0e81e1f751319cc3c451e54ba75524d825f148 pack-iq3-xxs/index.txt -ae28cf7a2a1c9063c4b55d6c8cf86d4d079dcddcf597f9e8697c9157d462c0ee pack-iq3-xxs/native_experts.txt -c724dc0b0822ada5d2977bf5bde821605feabaa64ea2e0045b67ca656329070a mtp/dense.bin -991456cf4eb266eb8a888c349e548d11bc640f5dbd9149439aa9786af0f732fd mtp/dense.txt -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`.) diff --git a/cmake/hip_backend.cmake b/cmake/hip_backend.cmake deleted file mode 100644 index d59bba9..0000000 --- a/cmake/hip_backend.cmake +++ /dev/null @@ -1,110 +0,0 @@ -# Opt-in HIP configuration. Strata's CUDA-shaped kernels target wave32 RDNA2 / RDNA3 / RDNA4 (64 KiB LDS per -# workgroup, a signed dot4 instruction). CMake/compiler discovery stays machine-independent; pass CMAKE_HIP_COMPILER when it -# is not on PATH. -if(NOT DEFINED CMAKE_HIP_ARCHITECTURES OR CMAKE_HIP_ARCHITECTURES STREQUAL "") - set(CMAKE_HIP_ARCHITECTURES gfx1100 CACHE STRING "Strata HIP target architecture(s), e.g. gfx1100 or gfx1100;gfx1201") -endif() -# Validated on real cards: gfx1100 (RX 7900 XT / XTX) and gfx1201 (RX 9070 / 9070 XT, Radeon AI PRO R9700) by the -# maintainers; gfx1101 (RX 7800 XT, #254) and gfx1200 (RX 9060 XT, #256) by their owners. gfx1102 (RX 7600) has the -# same LDS limit and dot4 instruction and passed ctest (#192), but no model run has been reported yet. RDNA2 gfx1030 (RX 6800 / 6900) has the -# same LDS limit and wave32 but an older dot4 instruction (v_dot4_i32_i8, hip_compat/intrinsics.hpp); a community -# report ran it (#311), the maintainers have not. -set(_strata_hip_validated gfx1100 gfx1201) -set(_strata_hip_community gfx1101 gfx1200) -set(_strata_hip_unvalidated gfx1012 gfx1102 gfx1030 gfx1031) -# CMake hands HIP a ';' list, but a -DCMAKE_HIP_ARCHITECTURES typed by hand (or ROCm's own Windows tooling) may use -# spaces, which foreach(IN LISTS) would otherwise treat as one element. -string(REPLACE " " ";" _strata_hip_norm "${CMAKE_HIP_ARCHITECTURES}") -set(STRATA_HIP_ARCH_LIST "") -foreach(_arch IN LISTS _strata_hip_norm) - if(_arch STREQUAL "") - continue() - endif() - string(REGEX REPLACE ":.*$" "" _base "${_arch}") # gfx1100:xnack- -> gfx1100 - if(_base IN_LIST _strata_hip_validated) - elseif(_base IN_LIST _strata_hip_community) - message(STATUS "Strata HIP: ${_base} was validated by community reports (docs/AMD_HIP.md)") - elseif(_base IN_LIST _strata_hip_unvalidated) - message(WARNING "Strata HIP: ${_base} builds, but it is not validated on a real card yet; please report results") - else() - message(FATAL_ERROR - "Strata HIP supports wave32 gfx1100, gfx1101, gfx1200 and gfx1201 (unvalidated: ${_strata_hip_unvalidated}); " - "CMAKE_HIP_ARCHITECTURES is '${CMAKE_HIP_ARCHITECTURES}'") - endif() - list(APPEND STRATA_HIP_ARCH_LIST "${_base}") -endforeach() -list(REMOVE_DUPLICATES STRATA_HIP_ARCH_LIST) -if(NOT STRATA_HIP_ARCH_LIST) - message(FATAL_ERROR "Strata HIP: CMAKE_HIP_ARCHITECTURES is empty") -endif() -# The compiled architectures reach the runtime device check (src/core/device.cu) as "gfx1100,gfx1201": a binary -# carried to a card it has no code for stops at startup with a clear message instead of "invalid device function". -string(REPLACE ";" "," STRATA_HIP_ARCHS "${STRATA_HIP_ARCH_LIST}") - -enable_language(HIP) -find_package(hip CONFIG REQUIRED) -find_package(hipblas CONFIG REQUIRED) -# Older distro hipBLAS has no workspace API. The compatibility shim uses -# rocBLAS directly for that version; newer hipBLAS keeps its existing path. -set(STRATA_HIP_BLAS_TARGETS roc::hipblas) -if(hipblas_VERSION VERSION_LESS "1.0") - find_package(rocblas CONFIG REQUIRED) - list(APPEND STRATA_HIP_BLAS_TARGETS roc::rocblas) -endif() -find_package(hipblaslt CONFIG QUIET) - -if(NOT TARGET hip::host) - message(FATAL_ERROR "The ROCm hip CMake package did not provide hip::host") -endif() -if(NOT TARGET roc::hipblas) - message(FATAL_ERROR "The ROCm hipblas CMake package did not provide roc::hipblas") -endif() -if(TARGET roc::hipblaslt) - set(STRATA_HIPBLASLT_AVAILABLE ON) -else() - set(STRATA_HIPBLASLT_AVAILABLE OFF) - message(STATUS "Strata: hipBLASLt not found; solution-table dispatch is unavailable") -endif() - -# HIP's link step produces a PIE; make Strata and ggml objects PIC for the ROCm linker. -set(CMAKE_POSITION_INDEPENDENT_CODE ON) - -set(STRATA_HIP_COMPAT_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/include/strata/hip_compat") -add_library(strata_hip_runtime INTERFACE) -target_include_directories(strata_hip_runtime BEFORE INTERFACE - "${STRATA_HIP_COMPAT_INCLUDE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include") -target_compile_definitions(strata_hip_runtime INTERFACE STRATA_USE_HIP=1 "STRATA_HIP_ARCHS=\"${STRATA_HIP_ARCHS}\"") -option(STRATA_GFX1012_PORTABLE_DOT "Use the portable signed-byte dot control on gfx1012" OFF) -if(STRATA_GFX1012_PORTABLE_DOT) - target_compile_definitions(strata_hip_runtime INTERFACE STRATA_GFX1012_PORTABLE_DOT=1) -endif() -target_link_libraries(strata_hip_runtime INTERFACE hip::host) -# The shim renames the CUDA runtime to HIP, force-included into every host and device source. On Windows the host -# compiler is ROCm's clang++ too (tools/hip/build_windows.bat: CMake refuses to mix cl.exe with Clang HIP), which takes -# -include like it does on Linux; an MSVC-style front end (cl / clang-cl) takes /FI instead. Forward slashes, so /FI -# does not read the path's backslashes as escapes. -file(TO_CMAKE_PATH "${STRATA_HIP_COMPAT_INCLUDE_DIR}/cuda_runtime.h" _strata_hip_force) -if(MSVC) - target_compile_options(strata_hip_runtime INTERFACE "$<$:/FI${_strata_hip_force}>") -else() - target_compile_options(strata_hip_runtime INTERFACE - "$<$:-include>" "$<$:${_strata_hip_force}>") -endif() -target_compile_options(strata_hip_runtime INTERFACE - "$<$:-include>" "$<$:${_strata_hip_force}>") - -# CMake does not infer HIP from Strata's existing CUDA-shaped .cu suffixes. -file(GLOB_RECURSE _strata_hip_sources CONFIGURE_DEPENDS - "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cu" - "${CMAKE_CURRENT_SOURCE_DIR}/bench/*.cu" - "${CMAKE_CURRENT_SOURCE_DIR}/tests/*.cu") -if(_strata_hip_sources) - set_source_files_properties(${_strata_hip_sources} PROPERTIES LANGUAGE HIP) -endif() -foreach(_source IN ITEMS tests/hip/intrinsics.cpp tests/hip/native_qsa_score.cpp) - if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${_source}") - set_source_files_properties("${_source}" PROPERTIES LANGUAGE HIP) - endif() -endforeach() - -message(STATUS "Strata: HIP enabled, arch ${STRATA_HIP_ARCHS}") diff --git a/cmake/qwen36_attn_fixtures.cmake b/cmake/qwen36_attn_fixtures.cmake deleted file mode 100644 index 07c6ab1..0000000 --- a/cmake/qwen36_attn_fixtures.cmake +++ /dev/null @@ -1,39 +0,0 @@ -# cmake/qwen36_attn_fixtures.cmake - the synthetic qwen35moe GGUFs at the engine's head_dim (256) and the oracle's -# dumps of their attention layer, for qsa_dense_parity (Qwen3.6 step 3, docs/qwen36-port/step3-attn.md). -# -# cmake -DPYTHON= -DSOURCE_DIR= -DOUT= -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: /.gguf and /-dump/ -# with every seam of ref/qwen36.py on 40 tokens. Writes /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}") diff --git a/cmake/qwen36_block_fixtures.cmake b/cmake/qwen36_block_fixtures.cmake deleted file mode 100644 index 94d94da..0000000 --- a/cmake/qwen36_block_fixtures.cmake +++ /dev/null @@ -1,28 +0,0 @@ -# cmake/qwen36_block_fixtures.cmake - the oracle's dumps of the synthetic qwen35moe file on a verify window's worth of -# tokens, for tests/cuda/qwen36_block_test.cpp (the plain block held to the dumps seam by seam). -# -# cmake -DPYTHON= -DSOURCE_DIR= -DSYNTH= -DOUT= -P cmake/qwen36_block_fixtures.cmake -# -# Writes /o8/.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") diff --git a/cmake/qwen36_oracle_dumps.cmake b/cmake/qwen36_oracle_dumps.cmake deleted file mode 100644 index d43a073..0000000 --- a/cmake/qwen36_oracle_dumps.cmake +++ /dev/null @@ -1,35 +0,0 @@ -# cmake/qwen36_oracle_dumps.cmake - the Qwen3.6 kernel fixture and the oracle's seam dumps for the GPU parity tests. -# -# cmake -DPYTHON= -DSOURCE_DIR= -DOUT= -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 .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}") diff --git a/cmake/qwen36_synth_fixtures.cmake b/cmake/qwen36_synth_fixtures.cmake deleted file mode 100644 index 029f3da..0000000 --- a/cmake/qwen36_synth_fixtures.cmake +++ /dev/null @@ -1,27 +0,0 @@ -# cmake/qwen36_synth_fixtures.cmake - writes the synthetic qwen35moe GGUFs the Qwen3.6 geometry tests read. -# -# cmake -DPYTHON= -DSOURCE_DIR= -DOUT= -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}") diff --git a/data/draft_vocab.bin b/data/draft_vocab.bin deleted file mode 100644 index 217f274..0000000 Binary files a/data/draft_vocab.bin and /dev/null differ diff --git a/data/draft_vocab_en.bin b/data/draft_vocab_en.bin deleted file mode 100644 index c588b56..0000000 Binary files a/data/draft_vocab_en.bin and /dev/null differ diff --git a/data/expert-profile.bin b/data/expert-profile.bin deleted file mode 100644 index a4ed7e5..0000000 Binary files a/data/expert-profile.bin and /dev/null differ diff --git a/data/qwen36-expert-profile.bin b/data/qwen36-expert-profile.bin deleted file mode 100644 index ff659f7..0000000 Binary files a/data/qwen36-expert-profile.bin and /dev/null differ diff --git a/docs/PLAN-qwen36-35b-a3b.md b/docs/PLAN-qwen36-35b-a3b.md deleted file mode 100644 index 092e53a..0000000 --- a/docs/PLAN-qwen36-35b-a3b.md +++ /dev/null @@ -1,475 +0,0 @@ -# Plan: UnbiasedStrata on Qwen3.6-35B-A3B, any single NVIDIA card from Pascal up, 256K context - -Written 2026-10-11, revised the same day three times: after reading -[Project Maya](https://github.com/mw00/project-maya); after the target widened from one card to a range; -after the llama.cpp-backend fallback was removed. Status: proposed, nothing started. - -Engine base: this repository's Strata snapshot (`6f32ec0`, engine 0.1.39). Maya is a method reference only. -llama.cpp appears in two roles only: the external speed baseline (bare `llama-server`, never inside the -binary) and the numerical oracle for parity. There is no fallback path. - -## 0. Target and what "adapt" means - -**Target:** one NVIDIA GPU, compute capability 6.1 or newer (GTX 10 series through RTX 50), **6 GB to 32 GB** -of VRAM, Linux, x86-64 with AVX2. The engine sizes itself at start: fixed weights first, then the KV cache -for the requested context, then every remaining byte of VRAM becomes expert-cache slots. The same binary -and the same model files on every card; only speed differs. Q4 is the default quant. Context 262,144 where -it fits, never below 131,072 without saying so. **Multi-GPU is out of scope**; the front end already -refuses `--gpus`, and that stays. - -The Strata engine in `src/` runs one architecture, Qwen3.8-Flash-Next (`qwen4_exp_text`). Qwen3.6-35B-A3B -(`qwen3_5_moe_text`) is the same family one generation earlier, with the extras removed. From the two -models' `config.json`: - -| | Qwen3.8-Flash-Next (what the engine runs) | Qwen3.6-35B-A3B (the target) | -| --- | --- | --- | -| Hidden / layers | 2560 / 48 | 2048 / 40 | -| Layer pattern | 3 linear attention then 1 full attention (`full_attention_interval` 4) | the same | -| Linear attention (GDN) | 16 k-heads, 48 v-heads, 128-dim, conv 4 | 16 k-heads, **32** v-heads, 128-dim, conv 4 | -| Full attention | 24 heads, 2 KV heads, head_dim 256, partial rotary 0.25, output gate, **plus a sparse indexer (QSA)** | 16 heads, 2 KV heads, head_dim 256, partial rotary 0.25, output gate, **dense** | -| MoE | 512 experts, top-10, intermediate 640, shared 640 | 256 experts, top-8, intermediate 512, shared 512 | -| Residual | hyper-connections (`hc` 4 streams) | plain residual | -| PLE / n-gram table | yes (28.8 GB shard 2) | none | -| MTP | 1 draft layer | 1 draft layer | -| Vocabulary | 248,320 | 248,320, the same tokenizer | -| Context | 262K | 262K native | - -Everything Qwen3.6 has, the engine has a kernel for; what it lacks, the engine treats as optional (PLE) or -needs a bypass for (hyper-connections, the QSA indexer). Maya's port study (`docs/GLM5-FLASH.md` in that -repo) crossed a larger *kernel* gap for GLM-5.3-Flash in about a week: study 2026-09-29, verified -streaming runner 2026-10-01, v1.0.0 on 2026-10-07. The Qwen3.6 kernel gap is smaller (no MLA, no sparse -indexer to write, no manifold hyper-connections, a SiLU-for-sigmoid change in the GDN gate). The -*plumbing* gap is not small: `docs/qwen36-port/geometry-inventory.md` (154 rows, 2026-10-11) shows the -hc = 4 gated residual and the QSA indexer assumed structurally in every block, the output head, the -verify window, the MTP drafter and prefill; prefill refusing any geometry but 2560/4/320/top-10; native -packs decoding only through the verify window; and `ModelGeometry` reading only the expert counts and -rope keys from the file. Expect Maya-scale work, with the risk in plumbing rather than kernels. - -**The deliverable:** this tree's engine running Qwen3.6-35B-A3B natively, by Maya's method, behind the -existing front end (`frontend/`: OpenAI API, tokenizer, chat template, tool-call parser, vision), which is -model-agnostic and stays. The payoff is what llama.cpp's `--n-cpu-moe` cannot do: hot experts cached in -VRAM by usage across all layers, the CPU computing the misses concurrently with the GPU, instead of whole -layers' experts on the CPU serially. On a 6 GB card that is the difference between a cache holding the -hottest 7% of experts and a layer cut holding none. - -Hypotheses: - -- **H1.** Under llama.cpp `--n-cpu-moe N` the GPU is idle most of each decode step, and the idle share - grows with N, so it is worst on the smallest cards. (The baseline sweep measures it.) -- **H2.** The idle is CPU expert matmul, not PCIe transfer. -- **H3.** 256K context fits at Q4 on every card of 11 GB or more; 128K fits on 8 GB; 6 GB at Q4 holds - the 256K fixed set only when prefill borrows cache slots, else it takes 131K or the IQ3 file, and the - engine must say which it chose. -- **H4.** Qwen3.6's routing is skewed enough that a VRAM expert cache serves well above its slot fraction - of routes at every budget from 6 GB up. The replay measures the whole curve before any CUDA. -- **H5.** The ported engine's decode scales as `1 / max(cpu, gpu)` rather than `1 / (cpu + gpu)`, and beats - the llama.cpp baseline at every VRAM budget, by the most at the small end. -- **H6.** With 12 GiB of RAM beside the 1080 Ti, Q4 reaches the disk tier and the profile-ranked VRAM - and RAM tiers keep disk reads under one expert per token on a warm conversation; IQ3 never reaches the - disk. The replay with three tiers predicts this; the engine's tier counters confirm it. - -H4 and H5 are not a go/no-go for building the engine; the port is the deliverable regardless. They decide -how the README describes the result and where the expert-cache tuning effort goes. - -**Measured on 2026-10-11 (Phase 0; details in `~/Code/regina/analysis/qwen36-35b-single-gpu-ladder/`):** - -| | Q4_K_XL at 11 GB | IQ3_XXS at 11 GB | -| --- | --- | --- | -| llama.cpp, 256K, fit edge (`--n-cpu-moe` 32 / 18), smoke test, cold cache, 400 tokens | 8.8 tok/s decode, 129 prefill, GPU busy 15% | 24.6 tok/s decode, 434 prefill, GPU busy 41% | -| llama.cpp, the sweep (warm, 1,200 tokens, `baseline-1080ti.md`) | **the number to beat: N = 30, the lowest N that fits (10,415 MiB): 13.4 tok/s decode on the regina request, 16.3 on the short one.** At N = 32: 13.5 / 12.2, 152 prefill; nvprof at N = 32: busy 13.8%, memcpy 0.6%, gaps 86%; warm nvprof at N = 30: busy 15.0%, memcpy 0.6%, 3.1 MiB of activations per token over PCIe; 14 to 21 MiB per token from disk | 33.5 tok/s decode, 907 prefill; GPU busy 56% (nvidia-smi); warm nvprof at N = 20: busy 24.8% under a 2.1x profiler slowdown, memcpy 0.8%; no disk reads | -| Sweep slope | 0.67 to 0.93 points of GPU busy and 0.5 to 0.7 tok/s per layer moved to the CPU (the N = 32 point was the first run and carried steal) | one point and 0.58 tok/s per layer | -| Route trace, top 40% of experts per layer | 76% of routes (215K routed tokens) | | -| Replay at the censused sizes, LFU with 3 spares per layer, prefill borrowing cache slots | 78 slots per layer: 83.2% hit, 36.6 RAM and 17.0 disk reads per token | 149 slots: 95.4% hit, 14.6 RAM and 0 disk reads | -| Replay, no borrowing (prompt buffer held in VRAM) | 52 slots: 72.2% hit, 35.8 disk reads | 103 slots: 89.4% hit, 0 disk reads | -| Predicted decode, overlap / serial (gpu 17 ms, CPU lane 0.15 ms per expert, disk 1.3 ms; parameters, not measurements), borrowing | 36.2 / 22.4 tok/s | 58.8 / 52.1 tok/s | - -Readings: H1 holds (the GPU idles 86% of each Q4 step by the kernel timeline, 44% at IQ3). H2 holds (memcpy is 0.6% of the window; the idle is CPU matmul and, at Q4, page-ins). H4 holds (83% hit from 35% of the -experts). With 12 GiB of RAM the Q4 arm is disk-limited (17 disk reads per token, about 22 ms, more than -the whole GPU step), so on this rung IQ3 is the quant that reaches the GPU ceiling and Q4 needs either -16 GiB of RAM or 12 GB of VRAM. Prefill borrowing cache slots is worth 11 points of hit rate at Q4. Prefill hit rates are linear in slots (a prompt touches nearly every -expert per layer per ubatch), so prompts stream experts over PCIe, as Strata already does. The overlap -column saturates at `1000 / gpu_ms`; the GPU step itself is the next thing to measure properly (nvprof, -in the sweep). - -## 1. The card ladder - -Real cards in the homelab cover the range, with Pascal at three sizes: - -| Budget | Card | Where | Arch | Role | -| --- | --- | --- | --- | --- | -| 6 GB | GTX 1060 | g7 (192.168.50.185), laptop | sm_61 | the floor; regina's `g7/README.md` has llama.cpp numbers here already | -| 8 GB | GTX 1070 Ti | host .4 (`llama-qwen36-35b-mtp.service`, live) | sm_61 | second Pascal point | -| 11 GB | GTX 1080 Ti | .57 at PCI `2a:00`, in **VM 211 `gpu-qwen36`** at 192.168.50.43 (cloned from 210 on 2026-10-11: 8 vCPU, 12 GiB, 100 GB on `local-lvm`, Debian 13, driver 550, CUDA 12.4, gcc-13) | sm_61 | the primary measurement card, and the development card until a pod is rented | -| 32 GB, rented | A6000 or similar on RunPod | on demand; this fork was already checked on a RunPod 3090 container (README) | sm_86 | only for the 32 GB rung and if the 4090 becomes busy again; the user has approved spending on this | -| 24 GB | RTX 4090 | VM 221 (192.168.50.151) on pve2: 16 vCPU, 62 GB RAM, CUDA 12.4, driver 550; root disk nearly full (build trees under `/models/work`, 174 GB free); system gcc is 14, so builds need gcc-13 as the host compiler | sm_89 | **idle since 2026-10-11 17:20, the user's call: the fast-compile development card for Phase 2 steps 3 to 5 and the 24 GB rung.** Both llama-server units there are inactive; leave them so. No RunPod needed while it stays free | -| 12, 16, 32 GB | RTX A6000 (48 GB) **capped** | VM 220 (192.168.50.8) on .57 | sm_86 | **in use by another agent**; the emulated rungs wait for it | - -The cap is Maya's `STRATA_GLM_VRAM_GB` idea: the engine limits its own total VRAM so the expert pool gets -what a card of that size would leave it. It is built in Phase 2 step 2; the 1080 Ti emulates the 6 and 8 GB -rungs with it (the real 1060 and 1070 Ti then check launch failures, FP16 paths and PCIe), and the A6000 -emulates 12, 16 and 32 GB whenever it is free. - -Consequence of the 1080 Ti being the only local card: **the Pascal build comes first, not last.** Every -parity harness and the streaming runner are brought up under `STRATA_EXPERIMENTAL_SM60=ON` on sm_61 from -the start, so Pascal surprises surface in the first week. The rented sm_86 pod runs the same harnesses in -parallel for fast iteration; a kernel passes when it passes on both. - -Constraints across the ladder: - -| | | -| --- | --- | -| CUDA | one toolkit that compiles sm_61 and sm_120 both: **CUDA 12.8** (12.x is the last with Pascal; 13 dropped it). Upstream saw RTX 50 crashes with 12.8-built engines (issues #220, #224), so RTX 50 is "built, not measured" until a card exists here. Fat binary `CUDA_ARCHS=61;70;75;86;89;120` | -| Pascal specifics | dp4a exists on sm_61 (not sm_60, which gets the shim); no tensor cores; no `__nanosleep`; FP16 math at 1/64 rate on GP102/GP104/GP106, so every kernel's *arithmetic* on these cards must be FP32 or dp4a int8 (fp16 *storage* with conversion, as in the KV pools and prefill's stores, is full rate and stays); the prompt MoE's dp4a MMQ path must be enabled on sm_61. Strata refuses sm < 75 unless `STRATA_EXPERIMENTAL_SM60=ON`; that flag becomes the default build (Phase 2, step 6). Nobody has run this engine on Pascal; Maya requires Volta or newer | -| Build verification | `cuobjdump --list-elf \| grep sm_` after every build; two past incidents here were wrong-arch binaries | -| Profilers | current Nsight Systems: Turing and newer only. Nsight Compute: no Pascal since 2019.5. On Pascal use the `nsys` bundled with CUDA 12.x (2023.x) or `nvprof`; on Turing and newer current `nsys`. Same analysis script either way | -| .57 host | Ryzen 7 1700 (Zen 1, AVX2, no AVX-512), 62 GiB usable DDR4-2133. Checked 2026-10-11: VM 220 shrunk to 36 GiB by another agent, host 18 GiB available before VM 211, about 6 GiB after. The 1080 Ti's link is **Gen3 x8** (`LnkSta: 8GT/s, Width x8`), so the June Gen1 problem is gone. VM 220 shares the memory bandwidth and the 8 physical cores (VM 220 has 12 vCPU, VM 211 has 8: oversubscribed when both are busy), so each run's metadata records VM 220's load and measurement windows prefer its idle hours | -| Stale pointer | `docs/NEW-GPU-VM.md` says "both GTX 1080 Ti"; slot 29:00 now holds the A6000 | - -## 2. Models, the memory hierarchy, and the budget table the engine must reproduce at start - -**Decision 2026-10-13 (step 5, the user):** the hierarchy is two tiers, VRAM plus host RAM, assumed to hold the -expert set; spilling to the NVMe is out of scope. Measured on the 1080 Ti at Q4_K_XL: 52 tok/s with the set -pinned in the VM's 35 GB, 12 to 15 tok/s under a 12 GiB bound (disk-bound, the replay's prediction; llama.cpp -13.4). The README states the RAM a card needs per quantization; the 12 GiB rows below are kept as the measured -cost of breaking the assumption, not as a supported rung. H6 and the disk-read instruments are therefore -informational. - -**The hierarchy on the primary rung is three tiers, by the user's decision:** 11 GB of VRAM in the 1080 Ti, -about 12 GiB of VM RAM (roughly 9 to 10 GB usable for a pinned expert tier after the OS, the process and -the KV), then the VM's NVMe disk for the rest. Strata already has the pieces: the VRAM expert cache, the -pinned RAM tier, and the low-RAM modes (`--mmap-experts` serving misses from the model file through the -page cache; `--resident-experts` copying exactly the non-VRAM experts into RAM when they fit). At Q4 they -do not all fit in 12 GiB, so the mapped mode and the disk are in play; at IQ3_XXS the whole expert set fits -VRAM plus RAM. Every per-budget number below is therefore a pair: where the experts live, and how many -reads per token reach the disk. - -| Arm | File | Size | Where it already is | -| --- | --- | --- | --- | -| **Q4, default** | `Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` (unsloth, repo commit `a483e9e`) | ~21 GB | not on hand; download once on the Mac, SHA-256 against the repo, copy over LAN | -| Q4 + MTP | `Qwen3.6-35B-A3B-UD-Q4_K_M-MTP.gguf` | 22.66 GB | `.4:/mnt/models/qwen3.6/MTP/`, Mac `~/models/qwen3.6/MTP/` | -| Q3 | `Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf` | 13.21 GB | `.4`, `.151:/models`, g7 `/home/rk/models` | - -K-quants for the default because most experts run on the CPU on most of the ladder, and K-quant dot -products are the fast AVX2 path. The engine needs the MTP block: Strata's draft protocol is built around -the model's own MTP layer. Settled on 2026-10-11: the `Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` from unsloth's MTP -repository (rev 5bc3e238) already carries the draft block as `blk.40` (753 tensors), so it is the default -file, and its `blk.40` serves as the draft pack for the IQ3 arm too (the plain IQ3 file has no draft block). - -Fixed VRAM before any expert slot. Measured and censused on 2026-10-11; the authoritative table is -`docs/QWEN36-35B-A3B.md` section 4.1, summarized: - -| Item | Q4_K_XL | IQ3_XXS | -| --- | --- | --- | -| Non-expert weights on the GPU | 2,038 MiB | 1,597 MiB | -| Draft block (dense 40 MiB + its experts + ring KV + logits) | ~520 MiB | ~520 MiB (the Q4 file's) | -| KV, q4_0, 10 attention layers, 262K | 1,440 MiB | 1,440 MiB | -| Session, CUDA context, reserve | ~0.7 to 1.2 GB | same | -| Prompt buffers | 0 when prefill borrows cache slots (a profile exists); 1,904 MiB at chunk 2048 otherwise | 0 / 1,878 MiB | -| **Decode-time fixed set at 262K** | **~4.8 GB borrowing, ~6.7 without** | **~4.3 / ~6.2** | -| Trunk experts, total / per expert (mean, max) | 18,726 MiB / 1.83 MiB, 2.20 max | 10,594 MiB / 1.04 MiB, 1.17 max | - -What each budget leaves for experts at Q4, 262K (the llama.cpp layer cut on the right is the baseline's -equivalent, for the comparison only): - -| Budget | Q4 expert slots in VRAM, prefill borrowing (of 10,240) | IQ3 slots | `--n-cpu-moe` equivalent | -| --- | --- | --- | --- | -| 6 GB | ~525 (5%); without borrowing the fixed set does not fit at 262K, so 131K or the IQ3 file | ~1,350 (13%) | 40 (all) | -| 8 GB | ~1,570 (15%) | ~3,200 (31%) | ~37 | -| 11 GB (the 1080 Ti, 11,264 MiB), 12 GiB RAM, NVMe | ~3,550 (35%) in VRAM; ~4,950 (48%) pinned in RAM; ~1,740 (17%) on disk | ~6,700 (66%) in VRAM, the rest in RAM, no disk tier | ~32 (llama.cpp's CPU experts at Q4 exceed 12 GiB, so its baseline on this rung is page-cache bound too) | -| 12 GB | ~3,650 (36%) | ~6,880 (67%) | ~31 | -| 16 GB | ~5,740 (56%) | all | ~26 | -| 24 GB | all, ~1 GB spare | all | 0 | -| 32 GB | all; the spare VRAM goes to f16 KV or a bigger prompt chunk | all | 0 | - -The sizing rule the engine implements (Phase 2, step 2): take the fixed total for the requested context; -if it does not fit, lower the context toward 131,072, then refuse with the exact numbers and the IQ3 file's -name. **KV streaming is not a lever for this model**: Strata streams by resolving the *selected* cells, and -dense attention selects every cell (study, 3.3 item 6), so the KV stays in VRAM. Never silently pick a -shorter context. Then the RAM tier: free RAM minus a headroom for the OS and the KV -stream, filled with the next experts by profile rank; whatever remains stays mapped from the GGUF on disk -and is read on a miss. The start-up log states all three counts. - -CPU-side ceiling for the misses: ~12 MiB of expert weight per CPU-computed layer-token at Q4. On the .57 -host (DDR4-2133, ~30 GB/s) that is ~60 to 70 tok/s before compute; Zen 1's 8 cores will be the lower -bound. Prior Pascal data: GTX 1060 6 GB, IQ3_XXS, N = 32: 16 tok/s at 8K depth, 11 at 32K, 355 tok/s -prefill, all llama.cpp. - -## 3. Phase 0: environment, baseline, and the replay - -Human steps (Proxmox state is the user's): - -1. (Decided: VM 220 stays up; host RAM already freed for a 12 GiB VM.) -2. (Done 2026-10-11.) VM 211 `gpu-qwen36`, a full clone of VM 210: **8 vCPU, 12 GiB RAM, balloon 0, - 100 GB on `local-lvm` (NVMe)**, `--hostpci0 0000:2a:00,pcie=1`. No `rombar=0`: that was needed only - for the boot-VGA card at 29:00 (homelab ticket 002); the 1080 Ti at 2a:00 never needed it. VM 220 - keeps running. The disk is the third tier, so `fio` its read throughput and 4K random latency once, - into `phase0-notes.md`. -3. Inside the VM: pin the kernel/driver pair, install `build-essential cmake nvtop linux-perf`, CUDA 12.8 - (the template has 12.4; 12.8 needs a 570-series driver, still a Pascal-capable branch), confirm - `nvidia-smi`, check `LnkSta`, set `perf_event_paranoid` to 1. -4. Copy the GGUFs over LAN; `sha256sum` each. - -Agent steps (fresh sonnet agent; brief = this section plus the hosts): - -5. Build bare `llama-server` at the submodule's pinned commit `3cf0325`, `-DGGML_CUDA=ON`, arches - `61;86;89`, static; verify with `cuobjdump`. Also the latest release (v0.6.0) for its MTP arm. One - build per rung, each verified for its own arch. This binary is the baseline and the oracle, nothing - else. -6. Profiler check on the 1080 Ti: CUDA 12.x `nsys status -e`, a 10-second `nsys profile -t cuda` of - `llama-bench`, `nvprof --print-gpu-trace` as fallback. Record which works. -7. Smoke test at 256K on the 1080 Ti with `llama-server`: `-ngl 99 --n-cpu-moe 32 -fa on -c 262144 - -ctk q4_0 -ctv q4_0 -b 2048 -ub 2048 --parallel 1 --cache-ram 0 -lv 4 -t 8`. Save the `-lv 4` buffer - lines; they replace the estimates in Section 2. - -**The baseline sweep (sonnet to drive, haiku to monitor).** Regina's harness (`scripts/sweep_ncpumoe.py`, -`plot_ncpumoe_sweep.py`): the N sweep with VRAM (`nvidia-smi` and `-lv 4`), host RAM (`RssFile`), prefill -and decode from `timings`, one real launch per point. One env spec per card; the A6000 budgets via -`CUDA_VISIBLE_DEVICES` plus a side process holding the surplus VRAM. Regina's hygiene: 30 s settle, drop -caches, warmup discarded, `--cache-ram 0`, `--parallel 1`. Workload per point: the Opus system prompt -(~27K tokens) + "implement Minesweeper", `n_predict 800`, plus one 3K-prefill / 1200-decode request. -Reasoning off, `temp 0`, `seed 42`. - -Instruments, logged per run (the same three serve the engine later): - -- **Level 0, always:** `nvidia-smi --query-gpu=timestamp,utilization.gpu,memory.used,power.draw - --format=csv -lms 100`. `utilization.gpu` is the GPU-busy share at 100 ms resolution. nvtop in a tmux - pane is for the human, not the record. -- **Level 1, per point:** a decode-phase kernel timeline (`nsys` or `nvprof`). A script computes busy - fraction, gap histogram, memcpy vs kernel share (the H2 test), per-token period, profiler overhead. -- **Level 2:** `perf stat` on the server PID, so gaps match CPU time in ggml matmul threads. -- **Timeline videos, prefill and decode (added 2026-10-13, the user's standing requirement).** For the - engine and for llama.cpp, on the 1080 Ti and the 4090, a real-time video of the request's timeline in the - style of `~/projects/ub-strata/strata.mp4`: lanes for CPU cores used (100 ms per-core `/proc/stat` - samples), GPU kernels, PCIe H2D / D2H bytes and GPU copy / idle, a playhead, the engine-reported tok/s - on completion, and the busy fraction stated both with and without the engine's host-wait spin kernel. - Two windows per point: the **prefill** of a long prompt (the regina request's 3.1K prompt, and a 32K - prompt where the budget allows) and the **decode** of the short request. Stacked engine-over-llama.cpp - comparisons at the fit edges. The traces come from the same nsys / nvprof captures as Level 1, so the - profiled request must cover the prefill as well as the decode. Pipeline: `scripts/decode_video_json.py`, - `scripts/decode_video_render.swift`, `scripts/render_decode_videos.sh` in regina (adapted from - `~/Code/strata-workspace/strata-investigation`); output under - `analysis/qwen36-35b-single-gpu-ladder/video/` with a README carrying the method's honesty statements. - -| # | Where | Arm | N values | ctx | Question | -| --- | --- | --- | --- | --- | --- | -| B1 | 1080 Ti | Q4 | fit edge, +2, +4, +8, 40 | 262144 | H1, H3 on the primary card; with 12 GiB of RAM the CPU experts page from disk, so `RssFile` and disk reads are recorded per point | -| B1b | 1060, 1070 Ti, 4090, A6000 at 12/16/32 | Q4 | the fit edge for that budget, and 40 | 262144, or 131072 where 262K does not fit | the baseline row of the ladder table | -| B2 | 1080 Ti | Q4 | fixed N | 262144 | depth 8K, 32K, 128K | -| B3 | 1080 Ti, 1060 | Q3 | fit edge, +4, +8, 40 | 262144 | K-quant vs i-quant CPU cost; the 6 GB default | -| B4 | 1080 Ti | Q4 + MTP | fixed N | 262144 | multi-token verify on CPU experts (llama.cpp's MTP) | - -B1, B1b and B3 are the baseline. B2 and B4 run when a card is idle. File-based drivers under `tmux`, -`DRIVER_DONE` markers. B1 takes 2 to 4 hours at 256K context. - -**E0, the route trace and cache replay (sonnet agent; any GPU host, even the Mac).** From Maya; it -answers H4 for the whole ladder before any CUDA and it produces the expert profile the engine loads: - -8. Record routes: a small patch to llama.cpp's `examples/eval-callback` writing one line per token and MoE - layer with the 8 selected expert ids (`ffn_moe_topk`). Corpus: regina's coding tasks, the Opus system - prompt, a few long chats; ~200K routed tokens. -9. Replay: adapt Maya's `tools/glm_tier_replay.py` (MIT; models LFU residents + spares + the CPU-lane - pick) to 40 layers × 256 experts **and three tiers** (VRAM slots, RAM slots, disk), and sweep the VRAM - slot count from 0 to 10,240 landing on each budget from Section 2, at Q4 and IQ3, with the RAM tier - fixed at what 12 GiB leaves. Policies: LFU, LRU, Belady ceiling. -10. Output: `phase0-replay.md` with VRAM hits, RAM hits and disk reads per token **vs slots**, the seven - budgets marked, and the predicted engine decode ceiling per budget against the baseline, using the - measured disk latency from step 2 for the disk term. The trace also seeds `expert-profile.bin`. - -Exit criteria: the baseline ladder row with the 1080 Ti's full N sweep; a working profiler on Pascal; the -hit-rate curve with the budgets marked; Section 2's estimates replaced by measured buffer sizes. - -## 4. Phase 1: images and the baseline write-up - -Under `~/Code/regina/analysis/qwen36-35b-single-gpu-ladder/`: - -1. `gpu-busy-vs-N.png`: Level-1 busy fraction and Level-0 utilization vs N on the 1080 Ti, both arms. H1. -2. `timeline-N.png`: a 200 ms strip of one decode step, kernels vs memcpys vs gaps. H2. -3. `ladder-baseline.png`: decode and prefill vs VRAM budget (6, 8, 11, 12, 16, 24, 32), llama.cpp at the - fit edge. The engine's points go on the same axes in Phase 2 step 5. The headline image. -4. `vram-vs-N.png`: VRAM vs N with the budget lines and the 262K/131K KV points. -5. `dmon-strip-N.png`: the raw 100 ms trace over prefill then decode. -6. `replay-hitrate-vs-slots.png`: hit rate vs slots per policy, budgets marked. H4. - -Analysis reads the PNGs and CSVs. The write-up answers with numbers: busy fraction and its slope in N; -memcpy vs gap; the default quant per budget; the baseline ladder row; the simulated hit rate per budget -and the predicted engine gain, largest-to-smallest card. A fresh agent reviews it, given the data but not -the conclusion. This write-up is what the engine must beat; it does not decide whether the engine is built. - -## 5. Phase 2: the engine port, Maya's recipe on a smaller gap - -The design document for this phase is `docs/QWEN36-35B-A3B.md` (2026-10-11): the model exactly from the -real GGUF's metadata, the component-by-component gap analysis with file:line citations, the memory plan -with the censused fixed set, the ladder, the envelope, the execution plan with effort weights (step 2 -15%, step 3 45%, step 4 20%, step 5 10%, step 6 5%, step 7 5%) and the risks. Where it and this plan -differed, the plan was corrected to the study on 2026-10-11 (its section 8 lists the eight points). - -Where: step 2 on VM 211 (the 1080 Ti, the Pascal build from the first step, Section 1). From step 3 on, -kernel work and parity iterate on the 4090 in VM 221 (sm_89, idle since 2026-10-11) and every kernel -also passes on the 1080 Ti before its step closes; the 4090 is also the 24 GB rung for step 5. Each step has a parity harness in Strata's negative-test discipline (every wrong reading must -differ materially before the right one is judged), as Maya's section 6 did. Steps 1 to 4 need no GPU time -beyond seconds of parity runs, so they proceed while the Phase 0 sweeps hold the cards. - -1. **Oracle and fixture (sonnet, no GPU).** Found on 2026-10-11 (`docs/qwen36-port/upstream-tooling.md`): - upstream never published its Python oracles (`ref/` holds only `load.py`; `gdn.py`, `moe.py`, - `qsa.py`, `docs/semantics.md` are cited but absent), most parity tests carry a host C++ reference - inside the test file, two embed generated `.inc` vectors, and the ggml-oracle tests link a llama.cpp - build through `STRATA_ORACLE_SOURCE_DIR`. So: `tools/` and `tests/` restored from the import commit `12a7825` - (done, commit c00942d: development tooling only, the binary still needs no Python), then write `ref/qwen36.py` new on `ref/load.py`, following the submodule's - `qwen35moe.cpp` graph with dumps named by its `cb()` calls; `tools/qwen36_synth_gguf.py` from - `test_iq_pack.py`'s `write_gguf()`; invariant tests (top-8 renormalization, GDN state shapes, the - output gate). Cross-check with the submodule's `llama-eval-callback` on the same synthetic GGUF. - One model difference already known: Flash-Next's GDN output norm gates with sigmoid(z), `qwen35moe` - with SiLU(z); `gdn.cu` and `gdn_parity` encode the sigmoid reading, so that is the first negative - test. `make_profile.py` hardcodes 48 layers and 512 experts; the MTP tools hardcode Flash-Next tensor - names; `iq_pack.py`'s `FORM` table has no `qwen35moe` entry. Dependencies: numpy, regex, gguf-py; no - torch, no GPU. - **Done 2026-10-11 on branch `qwen36-oracle`** (commits 9630539, f1ef81d, 0c850c3, 2094992, unmerged): - the oracle matches llama.cpp's own graph on 2,155 comparisons across 14 cases (max abs error 1.1e-4, - identical top-k everywhere, the nextn block included); seven rival readings each fail; 21 invariant - tests (24 after review). Independent review: no blockers; the GQA fixture (4 query heads over 2 KV - heads) added after review and matching on every seam; `ref/load.py`'s dequant bit-identical to ggml's - for Q6_K, IQ2_S, IQ3_XXS and IQ4_XS. **Tolerance policy** (`docs/qwen36-port/oracle-crosscheck.md`): - the oracle has a Q8 activation mode (`--act-quant q8`) and a per-layer protocol (`--force-topk`, - `--force-inputs`) that starts each layer from llama.cpp's inputs; against that, the per-seam relative - spread on the real file is 5e-8 (norm), 7e-7 (qkv), 8e-5 (gdn_out), 1.1e-4 (attn_out), 2.3e-3 - (moe_out), 4e-7 (logits). Those are the kernel parity tolerances. Without forcing, errors compound - 5 to 30 times and about half the top-k slots flip, so exact top-k agreement stays an F32-fixture-only - test. Branch commits after review: e452c51, 0e5344d, 44b0619. Real-file facts the engine - needs: the plain GGUF has no nextn block (only the `-MTP` files do, as block 40); nothing is fused; - the router, `ssm_alpha`, `ssm_beta` are F32; down experts are IQ3_XXS in 37 layers and IQ4_XS in - layers 34, 38, 39; the untied 2048 × 248,320 head is Q6_K. -2. **Geometry, metadata, sizing (default model).** Per the inventory: `ModelGeometry` is a set of - Flash-Next defaults; only `qwen4exp.expert_count`, `expert_used_count` and the rope keys are read, and - `check_architecture` rejects anything but `qwen4exp`. So: read every field of `ModelGeometry` from - the `qwen35moe.*` keys (hidden, layers, head counts, `ssm.*`, `n_ff`, interval); add `hc = 1` as "no - gated residual" with a plain-residual path and the `attn_norm` / `post_attention_norm` / - `output_norm` tensors the engine never references today; fix the one leak in the native expert path - (`expert_layout.cpp:284` passes compile-time 2560/640 to `native_fmt`); make `--ple-gguf` optional at - the command line (the kernels already allow no PLE); refuse llama.cpp's fused `ffn_gate_up_exps` and - `attn_qkv` forms by name (no shipped Qwen3.6 file uses them; the oracle's fused cases document the - layouts if one appears); the draft geometry follows the target; the draft vocab size comes from the - pack. The per-layer prefetch hints already exist (`FileExpertSource::warm`, `MADV_WILLNEED` on - predicted ids): verify they fire on the Qwen3.6 pack's offsets rather than porting Maya's. **The VRAM planner:** free VRAM minus the fixed set for the requested - context; KV streaming engaged when the fixed set does not fit (`--kv-resident`); the context lowered - toward 131,072 only after that; a refusal with numbers below it; the remainder becomes expert slots; - then the RAM tier from free RAM minus headroom (`--resident-experts` machinery), the rest mapped - from disk (the existing `--mmap-experts` source with its `MADV_WILLNEED` warm); `--vram-cap` and - `--ram-cap` for emulation. This step is what makes "6 GB to 32 GB" one binary, and it is where the - engine's tier counters (VRAM, RAM, disk reads per token) are exposed in the log and on `/health`. -3. **Kernels and the block (default model).** In order of risk, each with a parity harness: - - the GDN mixer: head pairing `h % h_k` already handles 32 v-heads against 16 k-heads; the gate - changes from sigmoid(z) to SiLU(z) in four kernels (`gdn.cu`, `fused_gdn.cu`, - `native_gdn_preprocess.cu`, the prefill GDN kernels), with the sigmoid reading as the negative test; - - the full-attention layer as *dense* attention: the decode kernel reads KV through an index list and - does not care how the list was built, so a "select every cell" producer replaces the indexer; the - kernels fixed at 12 query heads per KV head (Qwen3.6 has 8) and the short-context kernel fixed at - 24 heads become parameters; the prompt path is `qsa_prompt_attn.cu` (on Pascal, the batched decode - kernel), parameterized the same way; `native_flash_attn.cu` is a 256-cell diagnostic adapter, not a - fallback; - - the router at top-8 over 256 (generic already; parity at the selection boundary) and the shared - expert at 512 (its Q8_K rule needs a multiple of 256, which 512 satisfies); - - the block without hyper-connections: `layer.cpp` *and* `verify.cpp`, because native packs decode - only through the verify window, and that window requires the fused hc kernels (fixed at - 2560/4/320), top-10 and the native indexer today; - - prefill: `Prefill::init` refuses anything but 2560/4/320/10 and its GDN, split-q, route and MoE - kernels carry literals (48 v-heads, 24 heads, 1280, 640, top-10); parameterize or fork them. - Then the layer composition test: one GDN+MoE and one attention+MoE layer against the oracle's dumps. - The canonical Q2_0 CPU expert kernel bakes Flash-Next's shapes; Qwen3.6 rides the native pack path - (per-layer runtime geometry, ggml dot products, Unsloth's Q4_K/Q5_K types already included), as the - Coder with its 256 experts per layer does. -4. **Pack and runner.** `iq_pack.py` taught `qwen35moe` and its BF16-preserve list; the MTP head: the - engine's drafter reads its own Q8_0 directory with vLLM-style names, canonical Q2_0 experts at - 2560/640 and the default geometry, and Qwen3.6's single `nextn.eh_proj` over the concatenated - embedding and hidden state does not match the two separate projections it expects, so the drafter - needs a Qwen3.6 pack format and a small graph change (Maya's `mtp_gguf.py` is the model); - `make_profile.py` (hardcoded 48 × 512 today) from the E0 trace; - the streaming runner held to the oracle at every position of a short sequence; then the real Q4 file - end to end, greedy, compared with llama.cpp's output distribution (not token-for-token; the README's - known-problems entry says why). -5. **Serve and measure on the 1080 Ti at 11 GB, then capped to 8 and 6; the 12, 16, 24 and 32 rungs when a card frees up.** CPU lane and PCIe - share calibrated as Maya's `--calibrate` does, against this engine's own session; the Phase 0 - harness and instruments; the engine's points onto `ladder-baseline.png`. The H5 measurement. The - front end's `make test-chat-parser MODEL=` against Qwen3.6's template (the homelab services - use a patched `qwen3.6-enhanced.jinja`); the Qwen3-Coder any-argument-order patch checked for - misfires on this model's tool-call grammar. -6. **The other Pascal cards and the fat binary.** The sm_61 build has been the working build since step - 1; this step makes `STRATA_EXPERIMENTAL_SM60=ON` the default for the fat binary - (`CUDA_ARCHS=61;70;75;86;89;120`, CUDA 12.8) and runs the 1070 Ti and the 1060 against B1b. The - sm_75+ paths (tensor-core prompt attention, thread-block clusters) stay compiled in for the cards that - have them and are checked on the 4090 or A6000 when one is free. -7. **README/UPSTREAM.** The supported model and its checksums, the ladder table with the engine against - the baseline, the sizing rule in words, the Pascal caveats (CUDA 12.x, FP32 paths, no Nsight Compute). - -**The base is this repository's `src/` and `include/`: Strata at `6f32ec0`, engine 0.1.39.** Maya's engine -is not merged, cherry-picked or vendored: it forked from Strata around engine 0.1.27 and has rewritten the -expert tiers, the mixers and the server since, so its C++ does not apply to this tree without a port of its -own. Taken from Maya (MIT, by reference to a pinned commit): the method and the Python-side tooling; the -list of places Strata's geometry was hardcoded, each re-found and fixed here; the route-log format, -`glm_tier_replay.py` and `glm_expert_prior.py` adapted as standalone scripts; the VRAM cap and the -CPU-lane calibration as *designs*, implemented against this engine. Left out: the Python installer, the -dashboard, the Anthropic API, all multi-GPU work. One binary, no Python at run time, no network, one GPU. - -## 6. Acceptance - -Per budget, at the default quant, the engine must meet: - -| Criterion | Threshold | Basis | -| --- | --- | --- | -| A1 context | 262,144 on 11 GB and up; 131,072 on 8 GB; on 6 GB whichever the sizing rule picks, stated at start | the stated goal and floor | -| A2 decode | beats the baseline's fit-edge decode on the same rung; absolute floors ≥ 15 tok/s at 8K depth and ≥ 10 at 32K on 11 GB, ≥ 10 / 7 on 6 GB, ≥ 60 / 45 on 24 GB | the 1060 did 16/11 at IQ3 under llama.cpp; the 4090 did 100+ | -| A3 prefill | ≥ 300 tok/s on Pascal, ≥ 2,000 on Ada | the 1060 did 355 | -| A4 stability | 7 consecutive requests, no OOM, ≥ 100 MiB VRAM headroom | g7's "+78 MiB per request" | -| A5 serving | chat, streaming, reasoning, tool calls and images through the front end, pi writing and running a program through it, on the 1060, the 1080 Ti and the 4090 with no flags but the model | the README's existing status bar | - -If A2's "beats the baseline" fails on a rung after the cache tuning of step 5, the README reports the -rung's numbers against the baseline as they are. The engine still ships for that rung; the comparison is -the honest part of the result, not a gate. - -## 7. Agents: who does what, and how cheaply - -Rules: - -- `ark` is human-only. If a phase should run under ark, the plan says so and the user starts it. -- One fresh agent per phase boundary, briefed with this file, the phase section, the hosts, the run - directory, and the previous phase's write-up (not its transcript). -- Fork (same context) only to continue an in-progress phase after a wakeup. -- Nothing an agent runs changes Proxmox state. Agents do not touch the live `.4` service except by - starting a second server on another port with the production unit stopped, and restoring it. -- Unattended sweeps: a file-based driver under tmux, polled on a `/loop` or wakeup every 15 to 30 - minutes, `DRIVER_DONE` markers. - -Tiering: - -| Work | Model | Why | -| --- | --- | --- | -| `-lv 4` logs to CSV; `dmon.csv` parsing; nsys/nvprof export to busy-fraction and gap histograms; checksums; marker checks; replay runs at given slot counts; B1b single points on a card with a ready script | **haiku** | mechanical, re-runnable | -| Env specs, drivers, plots; llama.cpp builds per arch; the eval-callback route-dump patch; the replay adaptation; the oracle and synthetic fixture (Phase 2 step 1) | **sonnet** | code with a known shape and an example to copy | -| The Phase 1 write-up; geometry, the VRAM planner, kernels, pack, runner, the Pascal build (Phase 2 steps 2 to 7); diff review before the user ships | **default (Fable)** | judgment and engine code | -| Independent review of the Phase 1 write-up and of each parity harness before it is trusted | fresh **default** agent, given data but not the conclusion | an agent handed a hypothesis tends to confirm it | - -Safe parallelism: the 1080 Ti sweep, the B1b points on the other cards, E0 on the Mac, and Phase 2 steps -1 to 4 on the A6000 are independent of each other. If the user wants a multi-agent fan-out for Phase 2, -they say "use a workflow". - -## 8. Order of work and checkpoints - -1. User: VM 220 decision; the 1080 Ti VM; GGUFs copied to every rung. -2. Agent (sonnet): `llama-server` builds per arch, profiler check, smoke test → `phase0-notes.md`. - **Checkpoint: the first `-lv 4` table on the 1080 Ti; Section 2's estimates replaced.** -3. Agent (sonnet, then haiku): E0 → `phase0-replay.md` and the expert profile. **Checkpoint: the hit-rate - curve with the seven budgets marked.** In parallel, Phase 2 step 1 on the Mac. -4. Agents: B1 on the 1080 Ti; B1b on the 1060, 1070 Ti, 4090 and capped A6000; B3. **Checkpoint: the - baseline ladder row.** In parallel, Phase 2 steps 2 to 4 on the A6000. -5. Agent (default): plots and the baseline write-up; separate reviewer. **Checkpoint: the number to beat - on every rung.** -6. Agent (default): Phase 2 step 5 across the capped budgets. **Checkpoint: the engine's points on the - ladder plot against the baseline, and pi served through the front end on the 4090.** -7. Agent (default): step 6 on the three Pascal cards. **Checkpoint: `unbiased-strata --model ` - serving pi on the 1060 and the 1080 Ti with no flags but the model; A1 to A5 on every rung.** -8. Step 7, the README. B2 and B4 whenever a card is idle. - -Measurements land in `~/Code/regina/analysis/qwen36-35b-single-gpu-ladder/`, infra notes in -`~/homelab/investigations/-vm-1080ti-qwen36.md` with a LOG.md entry, the model-support outcome and -the ladder table in this repo's README, and the port study in `docs/QWEN36-35B-A3B.md`. Tickets: one -`homelab` for the VM, one `regina` for the harness, one `UnbiasedStrata`-prefixed ticket per Phase 2 -step, filed when the work starts. diff --git a/docs/QWEN36-35B-A3B.md b/docs/QWEN36-35B-A3B.md deleted file mode 100644 index 40ab94d..0000000 --- a/docs/QWEN36-35B-A3B.md +++ /dev/null @@ -1,594 +0,0 @@ -# Running Qwen3.6-35B-A3B on UnbiasedStrata - the study - -What it takes for Qwen3.6-35B-A3B (llama.cpp architecture `qwen35moe`) to run on this tree's Strata -engine, component by component, with the numbers the decision needs. Written 2026-10-11 against engine -0.1.39 (`CMakeLists.txt:11`, the `6f32ec0` snapshot; tree `8634357`). It is the Phase 2 design document -of `docs/PLAN-qwen36-35b-a3b.md` and the counterpart of Project Maya's `docs/GLM5-FLASH.md`, whose shape -it copies. Every `file:line` is this tree; "row N" is `docs/qwen36-port/geometry-inventory.md`; the model -facts come from `docs/qwen36-port/gguf-metadata.md` and `ref/qwen36.py` on branch `qwen36-oracle`; the -measurements from regina's `phase0-notes.md` and `replay/phase0-replay.md`. - -Strata is a native implementation of one architecture, Qwen3.8-Flash-Next (`qwen4exp`), with its memory -tiers and its speculation stack built around that shape. Qwen3.6-35B-A3B is the same family one generation -earlier with three things removed (the hyper-connection residual, the sparse-attention indexer, the PLE -table) and one numerical change in the GDN gate. The kernel gap is small. The plumbing gap is not: the -removed pieces are assumed structurally in every block, in the verify window that is the only decode path -for native packs, in the drafter and in prefill, and `ModelGeometry` is never populated from the model file. - ---- - -## 1. The model, exactly - -From the shipped GGUFs (`gguf-metadata.md`, dumped with `tools/gguf_reader.py`; sizes and SHA-256s in -`phase0-notes.md`): - -| | | -| --- | --- | -| Architecture | `general.architecture = qwen35moe`; `block_count` 40 (41 in the MTP files); `embedding_length` 2048; `context_length` 262,144 | -| Layer pattern | `full_attention_interval` 4: layer `il` is recurrent unless `(il+1) % 4 == 0`, so attention at 3, 7, ..., 39 (10 layers), GDN at the other 30 | -| GDN | `ssm.conv_kernel` 4, `ssm.state_size` 128, `ssm.group_count` 16 (k-heads), `ssm.time_step_rank` 32 (v-heads), `ssm.inner_size` 4096; conv channels 8192 = 2x2048 + 4096. Output gate `rms_norm(o) * ssm_norm * SiLU(z)` (`qwen35moe.cpp:267-276`) | -| Full attention | 16 heads, 2 KV heads, `key_length`/`value_length` 256, `rope.dimension_count` 64 (0.25 of 256), `rope.dimension_sections` [11, 11, 10, 0], `freq_base` 1e7, eps 1e-6; `attn_q` is 2x wide (query then gate per head, interleaved); output `* sigmoid(gate)`. **Dense**: no indexer | -| MoE | 256 experts, top-8, `expert_feed_forward_length` 512, shared expert 512 with a 1-D `ffn_gate_inp_shexp` scalar gate. Softmax over all 256, top-8 weights renormalised to sum 1 (`norm_w = true` hard-coded, `qwen35moe.cpp:506`); no `expert_weights_scale` (never loaded for this architecture) | -| Residual | plain: `attn_norm`, `post_attention_norm`, `output_norm`, all multiplicative RMS weights (no "+1") | -| MTP | `nextn_predict_layers` **absent in the plain file, 1 in the MTP files**; `blk.40` holds one attention + MoE block plus `nextn.eh_proj` [4096, 2048] over `concat(enorm(emb), hnorm(h))`, `nextn.enorm`, `nextn.hnorm`, `nextn.shared_head_norm`; no `embed_tokens`, no `shared_head_head` (the draft head is the main `output.weight`) | -| Vocabulary | 248,320 tokens, `pre = qwen35`, BOS/EOS/PAD 248044/248046/248055; the same tokenizer the engine's `--eos-ids` default already names (row 152) | -| Float tensors | the router `ffn_gate_inp`, `ssm_alpha`, `ssm_beta`, the shexp gate and every norm are **F32** in the plain file; the nextn block's router and shexp gate are BF16 | -| Mixed quantization | per layer and per role: IQ3_XXS file has IQ2_S gate/up everywhere, IQ3_XXS down on 37 layers and IQ4_XS on 3 (34, 38, 39); the nextn block in the MTP files is Q3_K/Q4_K experts with Q8_0 projections | -| Fused forms | none shipped: gate and up are separate `ffn_gate_exps`/`ffn_up_exps`, attention layers carry separate `attn_q`/`attn_k`/`attn_v`; `attn_qkv` exists only in the 30 GDN layers (the conv input) | - -The byte census of the three files on hand (gguf-py over the headers, 2026-10-11; `blk.40` separated): - -| File | Non-expert on the GPU (`output` + projections + norms) | `token_embd` | Trunk experts (40 x 256) | Per expert mean / max | `blk.40` dense / experts | -| --- | ---: | ---: | ---: | ---: | ---: | -| `UD-Q4_K_XL` (MTP repo, rev 5bc3e238, 21,784 MiB) | **2,038 MiB** (Q8_0 1,939 + F32 100) | 515 MiB Q8_0 | **18,726 MiB** (Q4_K 11,232, Q5_K 6,864, Q6_K 630) | 1.829 / 2.195 MiB (layer 39) | 40 / 464 MiB | -| `UD-IQ3_XXS` (12,589 MiB) | **1,597 MiB** (Q6_K 1,497 + F32 100) | 398 MiB Q6_K | **10,594 MiB** (IQ2_S 6,560, IQ3_XXS 3,626, IQ4_XS 408) | 1.035 / 1.172 MiB | none | -| `UD-IQ4_XS-MTP` (17,355 MiB) | 2,038 MiB | 515 MiB | 14,514 MiB | 1.417 / 1.883 MiB | 40 / 364 MiB | - -The two non-expert figures are what llama.cpp's `-lv 4` reported on the 1080 Ti once the GPU-resident -expert layers are subtracted: Q4 `CUDA0 model` 5,917 MiB minus layers 32 to 39 (3,878 MiB) = 2,039; IQ3 -7,475 minus layers 18 to 39 (5,878) = 1,597 (`phase0-notes.md`, smoke table). The token embedding stays in -host memory in both llama.cpp and this engine (`generate.cpp:2190`, "token embedding in mapped host -memory"), so it is not in the fixed set. The plan's Section 2 estimated ~3.1 GB for this item; the real -figure is 2.0 GiB. - -## 2. What the engine already is - -The implemented geometry is a struct of Flash-Next defaults (`include/strata/core/layout.hpp:27-59`): -n_embd 2560, 48 layers, full attention every 4th, GDN 16 k-heads / 48 v-heads / state 128 / conv 4 with -conv channels 10240 and value dim 6144 stored as members (row 2), QSA 24 heads / 2 KV heads / 256 with a -4-head 128-wide indexer, hyper-connections `hc` 4 with a 320-wide bottleneck, 512 experts x top-10 x 640. -`is_qsa_layer` is `layer % 4 == 3` (`layout.hpp:63`). Per layer (`src/core/layer.cpp:1170-1286`, -`1319-1342`): - - gr_read(attn) -> GDN | QSA -> gr_write(attn) -> gr_read(ffn) -> moe_route [doorbell] ... moe_finish -> gr_write(ffn) - -The unit is a captured per-layer CUDA graph replayed by a host loop (`include/strata/core/session.hpp:1-15`) -that rings a doorbell at the router so a CPU expert pool starts on the misses while the GPU continues. -Experts live in three tiers: a VRAM cache of slots filled by a profile and swapped by decayed usage -(`include/strata/core/expert_cache.hpp`), a RAM tier (pinned arena, or `--resident-experts` / -`--resident-budget-gib` keeping the complement of the VRAM cache in a compact copy, -`generate.cpp:1506-1520`, `expert_source.cpp:1331`), and the model file mapped from disk -(`--mmap-experts`, `expert_source.cpp:618-680`) with a `MADV_WILLNEED` warm hint per role on predicted -ids (`expert_source.cpp:1129-1160`, called at `1264`). Decode for a *native* pack (experts served from the -GGUF in their own ggml types, `include/strata/kernels/cpu/native_expert.hpp`) runs only through the verify -window (`expert_source.cpp:1869-1875`, row 114): windows of up to `kVerifyMaxT = 8` rows -(`verify_kernels.hpp:21`) drafted by the model's own MTP layer, a separate Q8_0 pack in VRAM -(`src/core/mtp.cpp:150-216`, `mtp.hpp:1-20`), plus a prompt-lookup drafter (`generate.cpp:522-524`). -Prompts go through a chunked prefill with the experts streamed over PCIe through a ring that borrows -cache slots (`generate.cpp:2723`, `4404-4425`; `docs/upstream/DETAILS.md`, "How it works"). The front -end (`frontend/`) is model-agnostic: OpenAI API, llama.cpp's chat parser (`frontend/chat_parser_test.cpp`), -vision through `mtmd` (`frontend/vision.hpp:4-87`), and it refuses `--gpus` (`frontend/main.cpp:558`). - -## 3. Component-by-component gap analysis - -### 3.1 Applies unchanged - -| Piece | Why | -| --- | --- | -| Layer pattern | `is_qsa_layer` (`layout.hpp:63`) gives 3, 7, ..., 39 for 40 layers; `n_qsa_layers() = 40/4 = 10` (row 55). Every per-layer loop in `session.cpp` uses `g.n_layers` (row 27). | -| GDN decode kernels | State 128, head pairing `head % h_k` (`native_gdn.cu:51`, `fused_gdn.cu:29`), grids from `h_v`, `h_v % h_k == 0` checked (`native_gdn.cu:99-101`, `fused_gdn.cu:148-153`); 32 % 16 = 0. The conv (`d_conv == 4 && state 128`, `layer.cpp:247-248`) matches. | -| Router | `router_top10` is a generic softmax top-k over runtime `n_expert <= 512`, `k <= 32` (`router_top10.hpp:21`, row 124); `moe_route` takes it whenever the pack is not 512/10 (`layer.cpp:370`). Semantics equal llama.cpp's: softmax over all, stable descending argsort, renormalise with the 2^-14 clamp (`router_top10.hpp:3-5`; `oracle-crosscheck.md`, "Router and experts"). | -| Shared expert | Shape-driven (`layer.cpp:418-451`); its Q8_K activation rule needs `n_ff % 256 == 0` (`shared_expert.cu:237-239`), which 640 failed and 512 satisfies (row 127). | -| Native expert kernels | CPU: `native_fmt` is ggml-cpu trait-driven, whole-block checks only (`native_expert.cpp:40-60`); 2048 and 512 are multiples of 256. `kNativeActBytes` 4096 / `kNativeHBytes` 1024 hold a 2048-wide Q8_K (2,336 B) and a 512-wide one (584 B) (row 111). GPU: `iq_kernels.cu:1076-1140` read `L.n_embd`/`L.n_ff` per layer; Q4_K/Q5_K gate-up and Q5_1/Q8_0 down are already present (row 120); the IQ2_S/IQ3_XXS/IQ4_XS/Q6_K of the shipped files are ggml types ggml-cpu has `vec_dot` for. | -| Expert cache and tiers | Residency `[n_layers x n_expert]`, slots, the profile header checked against `(n_layers, n_expert)` (`expert_cache.cpp:43`); the file source, the complement copy, the warm hint; all parameterised at runtime (rows 118, 109). | -| KV formats and streaming machinery | fp16 / int8 / q4_0 / K8V4 pools at `head_dim 256` (`kv_q4.cu:176`, row 103); paged pools, `--kv-resident`, the resident floor 20,480 cells (`layer.cpp:556`). The *use* of streaming changes (section 4.2). | -| RoPE | `n_rot 64`, `head_dim 256` (`native_rope.cu:121`), interleaved M-RoPE sections 11/11/10/0 with `t = h = w` for text (`mrope.hpp:3-12`); the oracle pins the same pairs `(p, p+32)` (`oracle-crosscheck.md`, "Full attention"). | -| Vocabulary, sampler, head | `n_vocab` is a kernel argument, merge handles <= 262,144 (`sampler.cu:607`); the native head takes `[n_in, n_out]` with `n_in % 256 == 0` (`native_head.cpp:21`); the drafter reads `n_vocab_ = output.weight.ne1` (`mtp.cpp:430`). | -| Speculation protocol | Verify windows, draft policy, prompt lookup; the drafter's *weights* change (3.10). | -| Front end | Tokenizer, template, tool-call parser, vision (row 154). | -| MTP drafter's attention | Already dense over every cell (`mtp.hpp:16-18`, row 76): the one dense-attention path in the tree. | - -### 3.2 GDN: head pairing, SiLU gate, four kernels (small) - -The geometry changes are runtime except two stored members, `ssm_conv_channels` and `ssm_value_dim`, -which must become 8192 and 4096 (row 2; `session.cpp:41-44` derives the state size from them). The one -numerical change: the output gate is `sigmoid(z)` in the engine and `SiLU(z)` in Qwen3.6 (row 39; -`layer.hpp:16` records the difference). Four kernels carry it: - -| Kernel | Line | Path | -| --- | --- | --- | -| `gdn_out_norm` | `src/kernels/cuda/gdn.cu:148` | legacy decode | -| `gdn_step_norm_kernel` | `src/kernels/cuda/fused_gdn.cu:69` (`1/(1+__expf(-zz))`) | the default native decode, inside the fused step | -| out-norm kernel | `src/kernels/cuda/native_gdn_preprocess.cu:110-112` | native unfused | -| `gdn_rec_kernel`, `gdn_out_norm_kernel` | `src/prefill/kernels.cu:324, 612` (`sigm(z)`) | prompt | - -The oracle's negative control shows the sigmoid reading moves the layer output by 1.07 relative L1 and the -logits by 0.92 (`oracle-crosscheck.md`, negative controls), so the trap is far above the 5% gate. -`src/kernels/gdn_parity.cpp:104` pins `h_v = 48` and its reference `sigmoid_f` (`:42`); both are re-pinned -at 32 v-heads with SiLU, the sigmoid reading becoming the negative case. The prompt GDN kernels are -specialised on `VPK = HV / HK = 3` value heads per key head (`prefill/kernels.cu:478`) and launched on the -`HV`/`HK`/`C` constants (`kernels.cu:18-19`, rows 89 to 91); they are the prefill item in 3.6. - -### 3.3 Dense attention replacing QSA (the largest kernel item, and a memory item) - -The decode kernel gathers K/V through `ids` and a page table and does not care how `ids` was built -(`qsa_decode_attn.cu:100-120`, row 102). So dense attention is a "select every cell" producer feeding the -existing kernel. What stands in the way: - -1. **The producer.** `qsa_layer` runs the indexer unconditionally: the raw key projection (`layer.cpp:945`), - the append (`:962-964`), the block scores and top-k (`:966-975`), with `indexer.{k,q}_proj.weight` and - `indexer.{k,q}_norm.weight` dereferenced as required tensors (`:891-897`, row 45). The verify window - does the same per row (`verify.cpp:757-761`, `772-870`, row 145). A dense path skips those steps and - writes `ids = 0..n_kv-1` from `st.step`; the selection width `qsa_selection_width(n_kv, s) = - min(n_kv, 2051)` (`qsa.hpp:144-147`) and the capacity `cap = qsa_selection_width(kTopkMaxCells, s)` - (`layer.cpp:876`, `verify.cpp:352`, `prefill.cpp:865`) become `n_kv` and `max_cells`. -2. **The 12-versus-8 literal.** `G = 12` query heads per KV head, refused with `exit(1)` unless - `n_head == 12 * n_head_kv` (`qsa_decode_attn.cu:17, 453, 497`; `qsa_prompt_attn.cu:22, 1447`; row 93, 94). - Qwen3.6 is 8. `G` becomes a template parameter instantiated at 8 and 12. -3. **The 24-head short-context kernel.** `native_flash_attn.cu:196-206` refuses anything but 24/2/256 and - contexts above 256; it is a diagnostic adapter (`layer.hpp:53`, "context <= 256") and is not on the - prompt path. It stays as it is. -4. **State without the indexer.** `qsa_state_bytes` carves `idx_tail`, `idx_dead`, `idx_pooled` with - `pooled_rows = max_cells/4 + 2` (`layer.cpp:559-575`, row 43): at 262,144 cells that is 65,538 x 128 x - 4 B = 32 MiB per attention layer, 320 MiB over ten, all dead. The drafter's ring already passes a state - "which has no indexer" with `pooled_rows = 2` (`layer.cpp:527-531`); the dense state takes the same. -5. **The split-K scratch scales with the context.** `qsa_decode_attn_scratch_floats(cap, s) = (cap/64) x - n_head x 258 + 64` (`qsa_decode_attn.cu:489-491`). Today `cap` is 2,051; with `cap = 262,144` and 16 - heads it is 64.5 MiB *per query row*: 516 MiB for the 8-row verify window (`verify.cpp:422`) and - `attn_batch` times that in prefill (`prefill.cpp:888`). The dense kernel needs either a larger chunk - per block or an online-softmax merge that does not keep a partial per 64-cell chunk. -6. **KV streaming no longer saves VRAM.** Streaming keeps the authoritative K/V in host memory and resolves - the *selected* blocks into VRAM slots before the read (`layer.hpp:230-236`, `qsa_kv_resolve` at - `layer.cpp:976`). With every cell selected every token, every block must be resident every token: the - mechanism degenerates to copying the whole KV (1,440 MiB at q4_0) over PCIe per token. Section 4.2 - and section 8 draw the consequence for the plan's sizing rule. - -KV formats, the Hadamard-rotated q4_0 pool, the page table and the RoPE tables carry over unchanged -(`layer.cpp:938-1010`, row 46). The prompt attention has three device paths: cp.async + mma on sm_80+, -mma on Turing, an m8n8k4 kernel on Volta, and for `cc < 70` the host returns false -(`qsa_prompt_attn.cu:1433`) so prefill falls back to the batched decode kernel -(`prefill.cpp:2222-2228`). On Pascal that fallback is the prompt attention; it needs `G = 8` and the -scratch fix above, nothing else. - -### 3.4 Router and shared expert (small; one measured-not-asserted parity) - -Both are generic already (3.1). Two form questions remain. The router kernel reads a BF16 weight -(`layer.cpp:361-366`, `project_bf16`), `fused_gdn_ab` reads BF16 `ssm_alpha`/`ssm_beta` -(`layer.cpp:285-287`), and `moe_shared` refuses a `ffn_gate_inp_shexp` that is not engine form BF16 -(`layer.cpp:427-437`). All four are F32 in the shipped file (`gguf-metadata.md`, "What was unexpected"). -The pack rounds them: exactly when the low 16 bits are zero, else only under `--compat-bf16` -(`upstream-tooling.md` section 4, the ORCA precedent). That is a numerical change against llama.cpp, which -multiplies in F32, and it lands on the one place where rounding is not a rounding error: a flipped top-8 -selection is a different expert (`layer.hpp:131-139`). The oracle's real-file smoke already shows the -F32-versus-quantized router disagreeing on 6 of 32 (token, slot) choices in layer 0 and 12 to 23 in layers -30 to 39 (`oracle-crosscheck.md`, "Not covered"), so the harness measures a flip rate at the -`logits -> top-8` boundary with the quantized-mode gates Maya calibrated (selection equal at probed layers -on an F32 fixture; a bounded rate on the real file), not bitwise equality. `router_top10_parity.cpp`'s tie -fixtures (all-equal logits, a 12-way tie, the unreachable clamp) carry over at 256/8. - -### 3.5 The block without hyper-connections: `layer.cpp` *and* `verify.cpp` (the largest plumbing item) - -`hc` sizes the residual `R` (hc, n_embd), `inject`, `gr_rs` and the GR workspace (`layer.cpp:1127-1145`), -and every block reads four `hc_attn_*` and four `hc_ffn_*` tensors with required forms -(`layer.cpp:1231-1255`, row 22). No `hc = 1` meaning exists (row 4): the GR math on one stream is not a -plain residual, and the names Qwen3.6 ships (`attn_norm`, `post_attention_norm`, `output_norm`) are -referenced nowhere in `src/` (rows 22, 23). The plain block is - - x = rms_norm(R, attn_norm) -> mixer -> R += out - x = rms_norm(R, post_attention_norm) -> MoE -> R += out head: rms_norm(R, output_norm) -> output.weight - -(`qwen35moe.cpp` layer loop; the oracle's `attn_norm-N`, `attn_residual-N`, `attn_post_norm-N`, `l_out-N`, -`result_norm` seams). The weighted RMS norm kernel exists (`native_qsa_rms_norm_weighted`, used at -`layer.cpp:879` and `mtp.cpp:488`). The places that must grow the plain path: - -| Site | What assumes hc | -| --- | --- | -| `layer.cpp:1170-1286` `block_layer_pre`, `1319-1342` `block_layer_post` | the two GR halves, the fused-GR fast path (`fused = g_fused_gr && fused_gr_supported(2560, 4, 320)`, `:1195`; `fused_gr.cu:1164-1166`), `pending_ffn` folding | -| `layer.cpp:1088-1107` `lm_head_mix` | `output_hc_{norm,down,up}` | -| `session.cpp:141-148` | first token = `hc` copies of the embedding (one copy at hc = 1, row 26) | -| `verify.cpp:331-340` | refuses unless `fused_gr_supported && ss.k == 10 && state 128 && d_conv 4` and `layer_verify_compatible` demands the fused GR and the native indexer (`layer.cpp:476-486`, row 141) | -| `verify.cpp:356-434` | `R_`, `xn_` as `T*HC*N`, `inj_`, `lo_ (T*hc_lr)`, `idx_raw_L_`, `qidx_`, `tail_snap_` | -| `verify.cpp:1123-1125` | the head mix | -| `verify_kernels.cu:256-291` | `broadcast_streams` / `add_streams_broadcast` (runtime `hc`, row 140) | -| `mtp.cpp:503-507, 564-568, 613-625`; `prefill.cpp:972-1086` | the drafter's three hc groups (3.10) | - -Because native packs decode only in verify windows (row 114) and the window refuses a layer without fused -GR and the indexer (row 141, 142), the plain block has to land in `verify.cpp` for a single token to come -out. The verify window's `ss.k == 10` refusal becomes `k == 8` from the file. `cvec` (the control-vector -apply over `hc*n_embd`, row 140) is runtime-shaped and needs no change. - -### 3.6 Prefill (the most literal-heavy subsystem) - -`Prefill::init` refuses unless `n_embd == 2560 && hc == 4 && hc_lr == 320 && k == 10` -(`prefill.cpp:737`, row 132); the file-wide constants are `N 2560, HC 4, D, LR 320, K 10, NE 512, C 10240, -ZV 6144, HV 48` (`prefill.cpp:90-91`) and `N, HC, D, LR, S, HK 16, HV 48, C 10240` in the kernels -(`prefill/kernels.cu:18-19`). The literals, each with its Qwen3.6 value: - -| Site | Literal | Qwen3.6 | -| --- | --- | --- | -| `prefill.cpp:649-650, 883-884` | `Qf` as `T * 12288` (24 x 512), `q`/`attn` as `T * ZV`; `idx_raw`, `q_idx` | 8,192 (16 x 512), 4,096; the two indexer buffers dead | -| `prefill.cpp:681-685, 704-721, 896-907` | MoE buffers `T*K*1280`, `T*K*640`, `1280 * 2560`, `2560 * 640`; `mmq::fits(gt, 1280)`, `matrix_bytes(dt, N, 640)` | `2*n_ff` 1024, `n_ff` 512, `n_embd` 2048 | -| `prefill.cpp:854-856, 1000-1026, 1375-1380` | `grs`, `gated`, `inj`, `xq`, `ident` from `HC`, `D`, `LR` | removed with hc | -| `prefill/kernels.cu:211-215, 285-304, 345-364, 387-432, 478-570, 893-924` | GDN kernels indexed on `HV`, `HK`, `C`, launched `<<>>`; `VPK = 3` (`:478`) | 32, 16, 8192; `VPK = 2` | -| `prefill/kernels.cu:616-657` | `route_kernel`: `REG 8` exists for 256 experts but the rank loop and `ids[t*10 + rank]`, `lane < 10` bake top-10 | `k` as a parameter | -| `prefill/kernels.cu:752-761` | `split_q_kernel`, `gate_attn_kernel` over `T * 24 * 256` and `h * 512` | 16 heads | -| `prefill/moe_fused_iq.cu:59` | `GU_ROWS_K = 2560, D_ROWS_K = 640` (the native-pack fused prompt MoE) | 2048, 512 | -| `prefill.cpp:1724` loop, `1303` `RP = 48` | layers from `g.n_layers` (fine, row 134); `RP` | check | - -The GDN kernels are forked per geometry (template on `HV, HK, C`) rather than made runtime, because their -shared-memory staging (`sq[2][TB][S]`, `kernels.cu:482-484`) is sized from them. `src/prefill/gdn_rec_parity.cu` -mirrors the constants (row 91) and is re-pinned with them. The chunked-versus-single-token equivalence (a -prefix through prefill then decoded must agree with token-by-token decode) is the harness that already -exists for this path (`tests/cuda/prefill_*_test.cpp`, restored in `c00942d`). - -### 3.7 The native pack path (one leak, otherwise runtime) - -The canonical Q2_0 CPU expert kernel bakes `H 2560, FF 640, NE 512, BLOB 1,382,400` -(`include/strata/kernels/cpu/expert.hpp:34-47`, row 107) and `expert_pool_dispatch` refuses any other -width (`expert_source.cpp:1863-1868`); Qwen3.6 does not go through it. It rides the native path, as the -Coder (256 of 512 experts) does. The path is runtime per layer (`NativeFmt` with `n_embd`, `n_ff`, gate/up -and down ggml types, `native_expert.hpp:22-31`) with one leak: `expert_layout_load` builds every layer's -format with the compile-time `H, FF` (`src/kernels/cpu/expert_layout.cpp:284`, `native_fmt(gt, dt, H, FF, -f, err)`) and then checks `f.bytes == blob`, so a 2048/512 pack fails the "blob is X B but its formats make -Y" check (row 108). The fix is the loader taking `n_embd`/`n_ff` from the geometry the caller resolved, -which means the call at `generate.cpp:2008-2010` (today `g0.n_layers, g0.n_expert` from a default struct, -row 10) must run after the metadata read of 3.8, not before it. - -`native_experts.txt` already carries a type per layer and per role (gate/up share one, down may differ, -`upstream-tooling.md` section 4; v3 header `(n_expert N)`, `expert_layout.cpp:271`), so the IQ3_XXS file's -37/3 down split and the Q4_K_XL's Q6_K layers need no format change. The engine reads experts as three -separate `ffn_{gate,up,down}_exps` tensors (`expert_source.cpp:2475-2500`, row 116); the shipped files are -separate, and a fused `ffn_gate_up_exps` is refused by name rather than split (section 8, item 5). - -### 3.8 Metadata and `ModelGeometry` - -`check_architecture` requires `general.architecture == "qwen4exp"` and reads six `qwen4exp.*` keys with -defaults 48/2560/24/2 (`include/strata/artifact/gguf_reader.hpp:576-597`); its callers are the native dense -loader, the native head and embedding, and the GGUF reader (`native_dense.cpp:103`, `native_head.cpp:29`, -`:113`, row 18). Every Qwen3.6 load dies there first. Beyond the guard, only `expert_count`, -`expert_used_count` and the rope keys are read, under `qwen4exp.` and only with `--native` -(`generate.cpp:2089-2096`, rows 8, 9). What `ModelGeometry` must read, all present in the file -(`gguf-metadata.md`, metadata table; row 153): - -| Field | Key | -| --- | --- | -| `n_embd`, `n_layers` | `qwen35moe.embedding_length`, `block_count` minus `nextn_predict_layers` (0 when absent) | -| `qsa_interval` | `full_attention_interval` | -| `ssm_state_size`, `ssm_k_heads`, `ssm_v_heads`, `ssm_d_conv`; conv channels and value dim derived | `ssm.state_size`, `ssm.group_count`, `ssm.time_step_rank`, `ssm.conv_kernel`, `ssm.inner_size` | -| `n_head`, `n_head_kv`, `head_dim`, `n_rot`, sections, base, eps | `attention.head_count`, `head_count_kv`, `key_length`, `rope.dimension_count`, `rope.dimension_sections`, `rope.freq_base`, `attention.layer_norm_rms_epsilon` | -| `n_expert`, `k`, `n_ff` (routed and shared) | `expert_count`, `expert_used_count`, `expert_feed_forward_length`, `expert_shared_feed_forward_length` | -| `hc` | 1 (no key; the architecture string decides) | - -The oracle's `read_hparams` (`ref/qwen36.py:125-150`) is the reference for defaults and derived values. -Other default-geometry sites: the routing trace's `layer >= 48` bounds (`generate.cpp:771, 795`, row 13), -the embedding load with `g0.n_embd` and the literal 248320 (`generate.cpp:2184-2186`, row 11), the draft -geometry (`generate.cpp:3026`, 3.10), and the standalone planner's `Geometry` and `expert_blob` -(`include/strata/plan/plan.hpp:22-52`, row 19), which is off the serving path. - -### 3.9 PLE, optional at the CLI - -The kernels already run without it: `block_layer_pre` applies the PLE only at layer 1 when `ple != nullptr -&& ple->ready()` (`layer.hpp:524-545`, row 30), prefill and verify guard on `ple_on` (rows 68, 69). The CLI -does not: `--native` refuses to start without `--ple-gguf` or a shard holding `per_layer_token_embd.weight` -(`generate.cpp:1800-1815`), and without `--native` the flag is "required" with `--no-ple` called a -"diagnostic ablation" (`:1843-1855`, rows 62, 63). The change is to make the absence of the tensor the -normal case when the architecture has no PLE. The fixed `NG_HIST x NG_HC_DIM` history buffer (about 360 KB, -`session.cpp:50-52`, row 29) and the `blk.1.ple_key` special cases (row 65) are dead but harmless. - -### 3.10 The MTP drafter - -The drafter is its own pack: `/dense.txt`, `dense.bin` (every dense weight Q8_0), `experts.bin` -written by `tools/mtp_rt.py` (`mtp.cpp:150-216`, row 70). It expects vLLM-style names -(`fc_embedding`, `fc_hidden`, `pre_fc_norm_*`, `self_attn.*`, `mlp.shared_expert.*`, `mlp.gate`, -`mlp.shared_expert_gate`, three `*hyper_connection*` groups; `mtp.cpp:210-212, 488-495, 503-507, 575`), -canonical Q2_0 experts of `n_expert x BLOB` bytes in VRAM through `moe_group_resident` / -`moe_grouped_s2` (`mtp.cpp:191, 579-583`; `s2_expert_grouped.cu:37-46` bakes 2560/640, row 121), and the -default geometry (`generate.cpp:3026`, "the canonical model's MTP head (512 experts)", row 12). - -Qwen3.6's draft block (`gguf-metadata.md`, "The nextn block"): `concat(rms_norm(emb) * enorm, rms_norm(h) -* hnorm)` (embedding first) through one `eh_proj [4096, 2048]`, then a plain attention + MoE block -(`attn_norm`, joint q+gate, q/k norm, IMRoPE, causal over its own KV, sigmoid gate, `attn_output`, -residual, `post_attention_norm`, the same top-8 MoE plus gated shared expert, residual), `shared_head_norm`, -the main `output.weight`. Pairing: token k with the trunk's output-normed hidden state of k-1 -(`oracle-crosscheck.md`, "Nextn / MTP"; verified at every nextn seam, 50 of 50). What the drafter keeps: -dense attention over its own KV ring (rows 76), the main head and the `draft_vocab.bin` subset (row 77, -the same 248,320 vocabulary, so `data/draft_vocab*.bin` carry over), `token_embd` embeds (row 78). What -changes: the two input projections become one `eh_proj` over the concatenation (`mtp.cpp:488-495`); the -three hc groups become three norms (`:503-507, 564-568, 613-625`; the prefill-side pass at -`prefill.cpp:972-1086` the same); the draft experts are 256 K-quant blobs (Q5_K/Q4_K, 464 MiB in the -Q4_K_XL file; Q3_K/Q4_K, 364 MiB in the IQ4_XS file) served by the native GPU expert kernels -(`iq_kernels.cu`, row 120) instead of the Q2_0 grouped kernel; the geometry follows the target. - -A Qwen3.6 draft pack: `dense.txt`/`dense.bin` with llama.cpp's names (`nextn.eh_proj`, `nextn.enorm`, -`nextn.hnorm`, `nextn.shared_head_norm`, `attn_norm`, `post_attention_norm`, `attn_{q,k,v,output}`, -`attn_{q,k}_norm`, `ffn_gate_inp` BF16, `ffn_gate_inp_shexp` BF16, `ffn_*_shexp`), the projections kept -Q8_0 as stored (39 MiB), and a `native_experts.txt`-style line for the one layer's three expert tensors. -Because the drafter is separate from the trunk file, the pack cut from the Q4_K_XL file's `blk.40` serves -the IQ3_XXS trunk too (the plain IQ3 file has no nextn block). Draft acceptance is an empirical question per -model; llama.cpp's own MTP arm (B4) is the external reference. - -### 3.11 Tokenizer, chat template, vision - -Same vocabulary and the same `qwen35` pre-tokenizer family (`gguf-metadata.md`; `tools/strata_tokenizer.py` -refuses schemes it has not transcribed, `upstream-tooling.md` section 2). The front end uses llama.cpp's -chat parser (`frontend/chat_parser_test.cpp`) and carries the Qwen3-Coder any-argument-order patch -(`chat_parser_test.cpp:48`); the plan's step 5 checks it against Qwen3.6's template with -`make test-chat-parser MODEL=` (`Makefile:35-41`). Vision loads an mmproj through `mtmd` -(`frontend/vision.hpp:79-87`); the `Qwen3.6-35B-A3B-MTP-GGUF-mmproj-F16.gguf` is on the VM with its SHA-256 -(`phase0-notes.md`). Nothing in the engine changes for either. - -## 4. The memory plan - -### 4.1 The fixed set, from measurements - -| Item | Q4_K_XL, 262,144 | IQ3_XXS, 262,144 | Source | -| --- | ---: | ---: | --- | -| Non-expert weights on the GPU | 2,038 MiB | 1,597 MiB | `-lv 4` minus resident expert layers (section 1); census | -| Draft block: 40 MiB dense + 256 experts in VRAM + ring KV + 8 x 248,320 logits | ~520 MiB | ~520 MiB (the Q4 draft pack) | census; `mtp.hpp:19`; `mtp.cpp:430-436` | -| KV, q4_0, 10 layers | 1,440 MiB | 1,440 MiB | `phase0-notes.md` smoke rows (both arms) | -| Session: RoPE table 64 MiB, scratch; **plus 320 MiB of indexer state unless 3.3 item 4 removes it** | ~164 MiB | ~164 MiB | `layer.cpp:559-576` | -| CUDA context | ~230 to 300 MiB | same | nvidia-smi 9,487 (peak 9,565) minus the three buffers, Q4 row | -| Reserve | 300 MiB (`kSmallReserveMib`) to 700 (default) | same | `generate.cpp:424, 3249` | -| Prompt buffers: borrowed from the cache with a profile, else chunk-sized | 0 (borrow) / 1,904 MiB at chunk 2048 | 0 / 1,878 MiB | `generate.cpp:2723`; llama.cpp `-ub 2048` compute buffer | -| **Decode-time fixed set** | **~4,760 MiB** borrowing; ~6,660 without | **~4,320** borrowing; ~6,200 without | sum | -| Trunk experts (file) | 18,726 MiB; 1.829 MiB mean, 2.195 max | 10,594 MiB; 1.035 mean, 1.172 max | census | -| Dense split-K attention scratch at `cap = 262,144` | 64.5 MiB per query row (516 for the verify window) | same | `qsa_decode_attn.cu:489-491` | - -The replay and the plan used a 5.8 GB (Q4) / 4.6 GB (IQ3) fixed set that includes the 1.9 GB prompt buffer -and excludes the drafter, and 17.4 GB / 10.5 GB of experts (`phase0-replay.md`, "Budget to slots"). The -census moves the expert total up by 7% at Q4 and the fixed set down by the prompt buffer when prefill -borrows; the two roughly cancel at the 11 GB rung (table 4.4). - -### 4.2 The VRAM planner (Phase 2 step 2) - -What exists: `--expert-cache auto` reads free VRAM, subtracts the reserve and the prompt estimate, grants -slots at `max_blob` (`generate.cpp:3232-3300`), then for a native pack with a profile re-prices the slots -per layer so the same VRAM holds the profile's hottest experts at their own blob sizes -(`generate.cpp:3307-3327`, "~30% more IQ3_XXS experts than slots of the largest blob"); the prompt path -borrows the last slots (`:4404-4425`); below `min_slots` the reserve shrinks to 300 MiB and then the start -refuses with the numbers (`:3267-3290`, "no VRAM is left for the expert cache"). What the step adds, in the -plan's order with one change: - -1. Fixed set first: weights, drafter, KV for the requested context, session. **KV streaming is not a lever - for this model** (3.3 item 6): the resident-window floor of 20,480 cells (`layer.cpp:556`) exists for a - selection of 2,051 cells, and dense attention reads every cell. So the rule's first fallback, "stream - the KV to RAM above a resident window", is replaced by: hold the KV in VRAM, and if the fixed set does - not fit, lower the context toward 131,072, then refuse with the numbers and the IQ3 file's name. Never - silently shorten. -2. Every remaining byte becomes expert slots, sized per layer from the profile as today. -3. The RAM tier: free RAM minus a headroom (`--resident-experts` uses 4 GiB, `generate.cpp:1508`; - `--resident-budget-gib N` sets it, `:1516-1520`), filled with the next experts by profile rank - (`pin_cache_complement`, `expert_source.cpp:1331`); whatever remains stays mapped from the GGUF - (`--mmap-experts`, `:618-680`) with the `MADV_WILLNEED` warm on predicted ids (`:1129-1160`). -4. Emulation: `--vram-cap MiB` clamps every `cudaMemGetInfo` free figure the planner reads (`:3297, 3313`) - to `cap - used` and, so the driver sees the same pressure the real card would, allocates a blocker of - `total - cap` at start; `--ram-cap GiB` bounds `resident_budget` and the pinned arena. The page cache - cannot be capped from inside the process; the 12 GiB VM does that physically, and on a larger host a - cgroup `memory.max` does. -5. The start-up log and `/health` state the three counts (VRAM slots, RAM copies, mapped) and per-token - counters: VRAM hits (`cache_hits`), RAM-copy hits, warm-hint count (`warm_count_`), and disk reads as - the major-fault delta from `/proc/self/stat`, since a page-cache miss is not otherwise observable. - -### 4.3 The 6-to-32 GB ladder - -Budgets in the replay's decimal convention (6 GB = 5,722 MiB) except the 1080 Ti (11,264 MiB) and a 24 GB -card (24,576 MiB). Slots at the census mean blob; "borrow" is the decode-time fixed set of 4.1, "no borrow" -adds the chunk-2048 prompt buffer. - -| Budget | Q4 replay basis (5.8 GB fixed, 1.70 MB/expert) | Q4 derived, no borrow | Q4 derived, borrow | IQ3 replay basis | IQ3 derived, borrow | -| --- | ---: | ---: | ---: | ---: | ---: | -| 6 GB | 80 (1%) | 0 (fixed set does not fit) | ~525 (5%) | 1,360 (13%) | ~1,350 (13%) | -| 8 GB | 1,280 (12%) | ~525 (5%) | ~1,570 (15%) | 3,280 (32%) | ~3,200 (31%) | -| 11 GB (decimal) | 3,040 (30%) | ~2,090 (20%) | ~3,130 (31%) | 6,240 (61%) | ~5,960 (58%) | -| 1080 Ti, 11,264 MiB | | ~2,510 (25%) | ~3,550 (35%) | | ~6,700 (66%) | -| 12 GB | 3,640 (36%) | ~2,610 (26%) | ~3,650 (36%) | 7,200 (70%) | ~6,880 (67%) | -| 16 GB | 6,000 (59%) | ~4,700 (46%) | ~5,740 (56%) | all | all | -| 24 GB (24,576 MiB) | all | ~9,790 (96%) | all, ~1,090 MiB spare | all | all | -| 32 GB | all | all | all | all | all | - -The RAM tier at the replay's 9.5 GB usable: Q4 ~4,950 experts at the census blob (the replay's 5,590 was at -1.70 MB), IQ3 ~8,760. The disk tier at Q4 on the 1080 Ti is then 10,240 - 3,550 - 4,950 = ~1,740 experts -(17%) with borrowing and ~2,780 (27%) without; the replay modelled 1,610 (16%). At IQ3 everything fits VRAM -plus RAM at every rung from 6 GB (`phase0-replay.md`, finding 5). The planner's own log at `--vram-cap` -6/8/11/12/16/24/32 is the check of this table, within one slot of the derivation. - -## 5. Expected envelope per budget - -From `phase0-replay.md` (LFU, profile seed, second half of a 214,940-token trace of the IQ3_XXS model, -decode only; the Q4 arm reuses the IQ3 routes). The parameters are parameters: `gpu_ms` 17 (an upper -estimate from the smoke rows' busy share; 12 is a flag away), `cpu_lane_ms` 0.15 per expert (llama.cpp -IQ3 N=18 implies 0.17), `disk_ms` 1.3 (fio 1 MiB random QD4; parallel faults may halve it), `pcie_ms` 0 -(promotions counted, not charged: 47.7 copies per token at Q4 11 GB, about 12 ms at 0.26 ms each, is the -largest omission; charging it takes Q4 11 GB LFU from 42.5 to 27.8 tok/s). "Overlap" is -`1000 / max(gpu, cpu, disk)`, "serial" the sum. - -| Budget | Q4 VRAM hit | Q4 disk reads/tok | Q4 tok/s overlap / serial | IQ3 VRAM hit | IQ3 disk/tok | IQ3 tok/s overlap / serial | -| --- | ---: | ---: | ---: | ---: | ---: | ---: | -| 6 GB | 0.0% | 70.7 | 7.7 / 6.8 | 59.7% | 0 | 51.7 / 27.5 | -| 8 GB | 57.9% | 51.5 | 12.6 / 10.4 | 84.4% | 0 | 58.8 / 40.9 | -| 11 GB | 82.6% | 13.2 | 42.5 / 24.7 | 96.0% | 0 | 58.8 / 52.9 | -| 12 GB | 86.8% | 7.1 | 58.8 / 31.8 | 97.7% | 0 | 58.8 / 55.2 | -| 16 GB | 95.5% | 0 | 58.8 / 52.2 | 100% | 0 | 58.8 / 58.8 | -| 24, 32 GB | 100% | 0 | 58.8 / 58.8 | 100% | 0 | 58.8 / 58.8 | - -58.8 is `1000 / gpu_ms` and the overlap column saturates there by construction. The Belady ceiling at Q4 -11 GB is 91.0% hit, 6.6 disk reads, 58.8 / 34.6. Against it, the llama.cpp smoke points on the same card: -Q4 N=32 **8.78 tok/s** decode, 128.6 prefill, GPU busy 15%; IQ3 N=18 **24.58** decode, 433.9 prefill, GPU -busy 41% (`phase0-notes.md`). The plan's floors (A2: 15/10 tok/s at 8K/32K on 11 GB, 10/7 on 6 GB, 60/45 on -24 GB; A3: 300 tok/s prefill on Pascal) sit inside these predictions except the Q4 6 GB row, which the -plan already routes to the IQ3 file. With the census tiers (4.3) the Q4 11 GB disk term is 17 to 27% of -experts rather than 16%, so its disk reads per token sit above 13.2; the replay is re-run with the census -blob sizes as part of step 2, not re-derived here. Prefill is not modelled; the engine's chunked MMQ path -amortises expert bytes across the chunk, and on Pascal the prompt MoE's fast path is a risk (section 7). - -## 6. Execution plan (Phase 2, steps 2 to 7) - -Step 1, the oracle and fixture, is done on `qwen36-oracle`: `ref/qwen36.py` agrees with the pinned -llama.cpp graph on 2,155 comparisons over 116 seam families at 1.1e-4 worst absolute error, the router's -integers identical, and all seven rival readings fail at the seam that makes them (`oracle-crosscheck.md`). -Every harness below holds the engine to those dumps by llama.cpp's `cb()` names. Each step has a parity -harness in the repo's negative-test discipline (`gdn_parity.cpp`: every wrong reading must differ by more -than 5% relative L1 before the right one is judged, `upstream-tooling.md` section 3), runs on the 1080 Ti -under `STRATA_EXPERIMENTAL_SM60=ON` (sm_61) from the first build and on a rented sm_86 card for compile -speed; a kernel passes when it passes on both. Steps 2 to 4 need seconds of GPU per run and proceed while -the Phase 0 sweeps hold the card. Effort weights sum to 100 for steps 2 to 7. - -**Step 2, geometry, metadata, sizing (15%).** Files: `gguf_reader.hpp:576-597` (accept `qwen35moe`, read -the 3.8 key set), `layout.hpp:27-59` (`hc = 1`, derived conv channels and value dim, no indexer fields), -`generate.cpp:2008-2010, 2073-2096, 2184-2186, 771, 795` (geometry from the file before the layout load; -the embedding dims from it), `expert_layout.cpp:284` (the leak), `expert_source.cpp:2475-2500` (fused -forms refused by name), `generate.cpp:1800-1815, 1843-1855` (PLE optional), the planner -(`generate.cpp:3232-3327`) with the 4.2 rule, `--vram-cap`, `--ram-cap`, the counters, `tools/make_profile.py` -(`N_LAYER = 48`). Harness: `ModelGeometry` from the synthetic GGUF (`tools/qwen36_synth_gguf.py`) and the -real file equals the oracle's `HParams` field by field; the planner's log at the seven caps reproduces -table 4.3. Negative tests: a `qwen4exp` file refused with its name; a 48 x 512 profile refused -(`expert_cache.cpp:43`); a `--fused-gate-up` fixture refused by tensor name; `--vram-cap` below the fixed -set refuses with the context it would need. No GPU beyond the planner's run. - -**Step 3, kernels and the block (45%).** In order of risk: - -- *GDN (3.2):* SiLU in the four kernels; `gdn_parity.cpp` at `h_v 32` with sigmoid as the negative, plus the - existing four traps (pairing, decay order, conv direction, l2 epsilon); `gdn_rec_parity.cu` at `VPK 2`. - Seams: `conv_output_silu-0`, `new_state-0`, `final_output-0`. -- *Dense attention (3.3):* the identity-`ids` producer; `G` templated at 8; the indexer skipped in - `qsa_layer` and the verify attention step; the state without indexer buffers; `cap = max_cells`; the - split-K scratch bounded. Harness: `qsa_parity.cpp`'s attention cases with `ids` identity against the - oracle's `kq_soft_max-3`, `kqv-3`, `attn_gated-3`, and a 300-cell case where the old width (2,051) and - the dense width differ. Negative tests: `G = 12` on 16 heads (refused, not mis-indexed), the gate skipped - (1.03 relative L1 at `attn_gated-3`), adjacent-pair RoPE (0.20 at `kqv-3`), both from the oracle's - controls. -- *Router and shared expert (3.4):* `router_top10_parity.cpp` at 256/8 with its tie fixtures; the BF16 - rounding of the F32 router measured as a flip rate on the real file's first 8 tokens with the quantized- - mode gates; `shared_expert_parity.cpp` at 512 with the 1-D F32-to-BF16 gate. Seams: `ffn_moe_topk-N`, - `ffn_moe_weights_norm-N`, `ffn_shexp_gated-N`. -- *The block without hyper-connections (3.5):* `layer.cpp` and `verify.cpp` both, `session.cpp:141-148`, - the head. Harness: the layer composition test, Maya's shape: layer 0 (GDN + MoE) and layer 3 (attention + - MoE) of the synthetic model through the engine's kernels, every seam held to the dumps; then the verify - window on an 8-token sequence against the oracle's `l_out-N` per position, with the window's row - arithmetic required to equal the single-token path (the discipline `verify.cpp:773-774` already states). - Negative tests: the GR read with identity weights (not a plain norm), the post-attention norm skipped, - `k = 10` on an 8-expert file. -- *Prefill (3.6):* the constants and the eight literal sites; the GDN kernels forked at 32/16/8192; the - route kernel at `k`; the split-q and gate kernels at 16 heads; `moe_fused_iq.cu` at 2048/512. Harness: - the restored `tests/cuda/prefill_*_test.cpp` plus chunked-prefill-then-decode against token-by-token - decode on a 40-token sequence (the oracle's `base_c7` case: chunks of 7). Negative tests: `VPK 3` on 32 - heads, top-10 routing on 8. - -**Step 4, pack, drafter, runner (20%).** `tools/iq_pack.py`: a `qwen35moe` entry in `FORM`/`ROUTERS` -(`ssm_alpha`, `ssm_beta`, `ffn_gate_inp`, `ffn_gate_inp_shexp` F32 to BF16 under `--compat-bf16` with -`compat-bf16.json`; norms, `ssm_a`, `ssm_dt.bias`, `ssm_conv1d` F32 copied; projections served natively), -`native_experts.txt` v3 per layer; `tools/test_iq_pack.py`'s `write_gguf()` fixtures at the new -architecture. The draft pack of 3.10 from the MTP file's `blk.40` (a new `tools/mtp_qwen36_pack.py` -replacing `mtp_pack.py`/`mtp_rt.py`), `mtp.cpp` and `prefill.cpp:972-1086` on the plain graph, the draft -experts through the native GPU kernels, `generate.cpp:3026` following the target. `make_profile.py` from -the E0 trace (40 x 256). Harness: the drafter's one-row forward against the oracle's `--mtp` dumps -(`mtp_eh_proj`, `mtp_attn_gated`, `mtp_ffn_out`, `result_output`; 50 nextn seams); the streaming runner -held to the oracle at every position of the 11- and 40-token cases, autoregressive and chunked -(`base_ar`, `base_c7`); then the real Q4 file, greedy, against llama.cpp's output distribution (top-1 -agreement and KL per teacher-forced position, Maya's quantized-mode gates: no monotone positional drift, -selection equal at probed layers). Negative test: a 4 KB weight corruption must move the logits by more -than 1e-2 (the mutation-sensitivity gate). - -**Step 5, serve and measure (10%).** The 1080 Ti at 11 GB, then `--vram-cap` 8 and 6; the other rungs when -a card frees up. `tools/calibrate.py` for `--pcie-frac`, `--spec-min-p`, `--pool-workers`; regina's harness -and the three instruments (`nvidia-smi` 100 ms, `nvprof` on Pascal, `perf stat`); the engine's points on -`ladder-baseline.png`; H5. `make test-chat-parser MODEL=` against the template; the any-argument-order -patch checked for misfires; images through `--mmproj`. Acceptance A1 to A5 per rung. - -**Step 6, the Pascal cards and the fat binary (5%).** `CMakeLists.txt:138-176`: `STRATA_EXPERIMENTAL_SM60` -default ON, `CMAKE_CUDA_ARCHITECTURES=61;70;75;86;89;120`, CUDA 12.8 (the sm_120-with-12.8 warning at -`:166-169` stays; RTX 50 is built, not measured). `cuobjdump --list-elf | grep sm_` after every build. The -1070 Ti and the 1060 against B1b; the sm_75+ paths checked on the 4090 or A6000 when one is free. - -**Step 7, README (5%).** The supported model and checksums, the ladder against the baseline, the sizing -rule in words, the Pascal caveats. - -The critical path runs through step 3's block-and-verify rewrite and its composition harness; the dense -attention kernel is the one new kernel, the rest is parameterisation and removal. - -## 7. Risks - -1. **Nobody has run this engine on Pascal.** The build refuses `cc < 75` without the experimental flag; - the flag is "community-tested, not in the ready-made engine" for sm_60/sm_70 (`CMakeLists.txt:150-160`), - and Maya requires Volta. The 1080 Ti is sm_61, so `__dp4a` is native and only the `__nanosleep` shim - applies (`dp4a.hpp:27-40`). -2. **FP16 on GP102/GP104/GP106 runs at 1/64 rate.** 21 kernel files touch half types. Conversions - (`__half2float`, the `hf()` stores in `prefill/kernels.cu:614, 761`, the fp16 K/V reads in - `qsa_decode_attn.cu`) are full rate; half *arithmetic* is not. The audit must separate the two in - `native_mmvq.cu`, `iq_kernels.cu`, `s_gemv.cu`, `shared_expert.cu` and the prefill kernels. The prompt - MoE is the exposed case: the MMQ (dp4a) path is gated by `mmq::built()`/`mmq::fits` - (`prefill.cpp:676-684`) and its tests exit 77 below sm_80 (`CMakeLists.txt:1076`); the fallback is the - FP16 GEMM path over dequantized fp16 weights (`prefill.cpp:907`), which is exactly the slow case. The - A3 floor of 300 tok/s prefill on Pascal depends on the dp4a MMQ running on sm_61, where llama.cpp's own - MMQ does run. -3. **Prompt attention on Pascal is the decode kernel.** `qsa_prompt_attn_batch` returns false for - `cc < 70` (`qsa_prompt_attn.cu:1433`) and prefill falls back to `qsa_decode_attn_batch` over the chunk - (`prefill.cpp:2222-2228`): correct, but a 2,048-query chunk through a decode-shaped kernel is a - throughput risk, and its split-K scratch is the 64.5 MiB-per-row item of 3.3. -4. **Memory items the plan did not count:** the draft block (~520 MiB), the dead indexer state (320 MiB - at 256K unless removed), the dense scratch, and the uniform-slot grant before the per-layer re-pricing - (`generate.cpp:3307-3327`), which is 17% of capacity at Q4 (2.195 versus 1.829 MiB) if the profile is - absent and the re-pricing does not run. -5. **KV streaming does not apply** (3.3 item 6): a 6 GB card at 256K holds the KV in VRAM or lowers the - context; there is no third option in this engine without a CPU attention path. -6. **Numerical:** BF16 rounding of the F32 router and GDN gates (3.4); the router's flip rate is measured - on the real file, and the acceptance gates are top-1 and KL, not per-logit tolerances, as Maya's - cross-check found (two flips in 512 explained by 1e-5 selection gaps). -7. **Verify-only decode.** Every token of a native pack goes through `verify.cpp` with `--spec T >= 2` - (`generate.cpp:2178`); the plain IQ3 file has no draft block, so its drafter is the Q4 file's `blk.40` - (3.10). Draft acceptance on Qwen3.6 is unmeasured; the prompt-lookup drafter alone leaves short windows. -8. **The replay's model:** `pcie_ms` 0, one IQ3 trace reused for Q4, a cache that never resets, no - prefill, `gpu_ms` an upper estimate (`phase0-replay.md`, "Limits"); the census blob sizes shift the Q4 - disk tier up (4.3). The engine's counters, not the replay, decide H4 and H6. -9. **The host.** VM 211 has 8 vCPU of a Zen 1 shared with VM 220 and AVX2 only; the native expert path then - runs ggml-cpu `vec_dot` for the i-quants and the AVX-2 kernels for the rest (`generate.cpp:2068-2072`). - The 0.15 ms CPU lane is the replay's assumption; `perf stat` measures it. -10. **Upstream tooling gaps:** no published Python oracle for the Flash-Next kernels, so the parity files' - C++ references are the only pins of the existing semantics (`upstream-tooling.md` section 1); the - `bench/micro` llama.cpp-oracle tests cannot be restored. - -## 8. Disagreements with the plan - -1. **Section 2, the sizing rule's first fallback ("stream the KV to RAM above a resident window").** Not - available for dense attention (3.3 item 6): streaming resolves the selected cells, and every cell is - selected. The rule becomes KV in VRAM, then lower the context, then refuse. H3's "6 GB needs the KV - streamed" is replaced by: 6 GB at Q4 holds the fixed set at 256K only if prefill borrows from the cache - (~525 slots, table 4.3), else it takes 131,072 or the IQ3 file. -2. **Section 2, the fixed set.** Non-expert weights are 2,038 MiB at Q4 and 1,597 at IQ3, not ~3.1 / ~1.9 - GB; the prompt buffer is 1.9 GB at chunk 2048, not 0.8; the drafter (~520 MiB) is missing from the - table. The plan says Phase 0 numbers replace the estimates; this study does so and adds the drafter. -3. **Section 2, the expert totals.** Q4 trunk experts are 18,726 MiB (19.6 GB), 1.829 MiB mean and 2.195 - max per expert, not 17.4 GB / 1.7 MiB; IQ3 agrees (10,594 MiB). The 11 GB rung's tiers at Q4 shift to - ~3,550 VRAM / ~4,950 RAM / ~1,740 disk with borrowing, and the replay's 13.2 disk reads per token is a - lower bound until it is re-run at the census sizes. -4. **Section 5 step 3, "`native_flash_attn.cu` is the fallback for prompts."** It is a diagnostic adapter - for contexts up to 256 with 24 heads hard-coded (`native_flash_attn.cu:196-206`, `layer.hpp:53`). The - prompt path is `qsa_prompt_attn.cu`, and on Pascal it is the batched decode kernel (risk 3). The dense - prompt attention comes from parameterising those two, not from `native_flash_attn.cu`. -5. **Section 5 step 2, "accept llama.cpp's fused `ffn_gate_up_exps` and `attn_qkv` forms or split them at - pack time."** No shipped Qwen3.6 file uses either (`gguf-metadata.md`). The study scopes this to a - named refusal in `check_experts_gguf` and `native_dense.cpp:31-33`; the oracle's fused cases stay as - evidence of the layouts should a file appear. -6. **Section 5 step 2, "per-layer prefetch hints as Maya's section 7 added."** This tree already has them: - `FileExpertSource::warm` issues `MADV_WILLNEED` per role (`PrefetchVirtualMemory` on Windows) for the - predicted ids (`expert_source.cpp:1129-1160`, `1264`). Nothing is ported from Maya; step 2 verifies the - hint fires on the Qwen3.6 pack's offsets and counts it. -7. **Section 2, "which file" (Q4_K_M-MTP, or Q4_K_XL plus a separately packed head).** The Q4_K_XL from the - MTP repository (rev 5bc3e238, SHA in `phase0-notes.md`) already carries `blk.40` (753 tensors). It is - the default file, and its `blk.40` is the draft pack for both arms (3.10). -8. **Section 1, "every kernel path on these cards must be FP32 or dp4a int8."** Agreed for arithmetic; - fp16 *storage* with conversion (the KV pools, the fp16 stores in prefill) is full rate on Pascal and - stays. The prompt MoE's dp4a MMQ must be enabled on sm_61 (risk 2), which the plan does not list. - -Nothing else in Sections 0, 2 and 5 is contradicted: the target, the three tiers on the primary rung, the -Q4 default with the IQ3 arm, the Pascal-first build, the step order and the acceptance thresholds stand. diff --git a/docs/qwen36-port/geometry-inventory.md b/docs/qwen36-port/geometry-inventory.md deleted file mode 100644 index 4ef0c00..0000000 --- a/docs/qwen36-port/geometry-inventory.md +++ /dev/null @@ -1,290 +0,0 @@ -# Flash-Next geometry and extras baked into the Strata engine (6f32ec0, engine 0.1.39) - -Scope: `src/` and `include/`. Target: Qwen3.6-35B-A3B (hidden 2048, 40 layers, GDN 16 k-heads / 32 v-heads, -16 attention heads / 2 KV heads of 256, dense attention, 256 experts top-8 of 512 plus a shared 512, no -hyper-connections, no PLE, MTP 1 layer, vocabulary 248,320). No fixes are proposed here. - -Derived Qwen3.6 numbers used below: GDN conv channels 8192 (2*2048 + 4096), GDN value dim 4096, attention -`q_full` width 8192 (16 * 2 * 256), attention output width 4096, GQA group 8 (16 / 2), 40 layers = 30 GDN + 10 attention. - -Classes: - -- **RT**: already a runtime parameter (`ModelGeometry`, pack metadata, tensor shape). Fine as is. -- **CT**: a compile-time constant that disagrees with Qwen3.6. Must change. -- **CT-ok**: a compile-time constant that is an upper bound or a value Qwen3.6 shares. Needs no change. -- **ST**: a structural assumption. Needs a code path, not a number. - -Line numbers are from the current tree. Where a path only runs for the canonical Q2_0 pack (not the `--native` GGUF -pack that Qwen3.6 would use), the note says "canonical only". - -## A. The central finding: `ModelGeometry` is a default, and only two fields are ever read from the model file - -| # | file:line | Assumption | Class | Note | -|---|---|---|---|---| -| 1 | include/strata/core/layout.hpp:28-30 | `n_embd = 2560`, `n_layers = 48`, `qsa_interval = 4` | CT | Struct defaults. Nothing reads `n_embd`/`n_layers` from the file. Interval 4 already matches Qwen3.6. | -| 2 | include/strata/core/layout.hpp:33-38 | `ssm_k_heads 16`, `ssm_v_heads 48`, `ssm_conv_channels 10240`, `ssm_value_dim 6144` | CT | Conv channels and value dim are stored members, not derived from heads. Changing `ssm_v_heads` alone leaves them wrong. Heads 16 and state 128 and d_conv 4 already match. | -| 3 | include/strata/core/layout.hpp:41-45 | `n_head 24`, `idx_q_heads 4`, `idx_key_dim 128` | CT | `n_head` must be 16. `n_head_kv 2` and `head_dim 256` match. Indexer fields are meaningless for Qwen3.6. | -| 4 | include/strata/core/layout.hpp:48-49 | `hc = 4`, `hc_lr = 320` | CT / ST | No "hc = 1" meaning exists. `hc` sizes `R`, `inject`, every GR buffer. See section B. | -| 5 | include/strata/core/layout.hpp:52-53 | `n_expert = 512`, `n_ff = 640` | CT | One `n_ff` serves routed and shared experts. Qwen3.6 has 512 for both, so one field still works. | -| 6 | include/strata/core/layout.hpp:55-58 | `hc_dim() = hc*n_embd`, `n_qsa_layers = n_layers/interval`, `n_gdn_layers` | RT | Derived correctly from the fields. | -| 7 | src/program/generate.cpp:2073-2074 | `ModelGeometry g;` with the comment "canonical defaults", and `K = 10` | CT | `g` and `K` start from Flash-Next defaults. | -| 8 | src/program/generate.cpp:2089-2092 | Only `qwen4exp.expert_count` -> `g.n_expert` and `qwen4exp.expert_used_count` -> `K` are read, and only when `--native` is given | RT (partial) | The only model-file overrides of geometry. `block_count`, `embedding_length`, head counts, `ssm.*`, `expert_feed_forward_length` are never read. | -| 9 | src/program/generate.cpp:2093-2096 | Rope keys read under the `qwen4exp.` prefix | CT | Key prefix must become `qwen35moe.`. Values (base 1e7) happen to match. | -| 10 | src/program/generate.cpp:2008-2010 | `const ModelGeometry g0;` passed to `expert_layout_load(o.pack, g0.n_layers, g0.n_expert)` | CT | Runs before the line-2091 override, so it sees 48 layers and 512 experts. The `native_experts.txt` header can still correct `n_expert` (expert_layout.cpp:271). | -| 11 | src/program/generate.cpp:2184-2186 | `NativeEmbed::load(..., g0.n_embd, 248320, ...)` | CT | Default `n_embd` 2560 would reject a 2048-wide `token_embd.weight`. The 248320 literal equals Qwen3.6's vocabulary. | -| 12 | src/program/generate.cpp:3026 | `static const ModelGeometry draft_geometry{}` handed to `mtp.load` | CT | The comment says the draft layer is "the canonical model's MTP head (512 experts)". Draft geometry does not follow the target. | -| 13 | src/program/generate.cpp:771, 795 | Routing trace rejects `layer >= 48` | CT | Literal 48 in two bounds checks. | -| 14 | src/program/generate.cpp:5769 | `kImagePad = 248056` (comment: `qwen4exp.ple.image_token_id`) | CT-ok | Only feeds the PLE hash for image cells. Dead without PLE. | -| 15 | include/strata/core/session.hpp:48 | `SessionState::k = 10` | CT | Experts per token default. Overwritten from `K` at session init. | -| 16 | include/strata/core/expert_source.hpp:194 | `int k_ = 10` | CT-ok | Default only; set per layer at runtime. | -| 17 | include/strata/artifact/gguf_reader.hpp:576-578 | `Qwen4ExpGuard{block_count 48, hidden 2560, head_count 24, head_count_kv 2}` | CT | Struct defaults for the architecture guard. | -| 18 | include/strata/artifact/gguf_reader.hpp:581-597 | `check_architecture` requires `general.architecture == "qwen4exp"` and reads `qwen4exp.block_count`, `.embedding_length`, `.expert_count`, `.expert_used_count`, `.attention.head_count`, `.attention.head_count_kv` | CT / ST | Callers: native_dense.cpp:103, native_head.cpp:29 and :113, gguf_reader.cpp:57. Every Qwen3.6 load is refused here first. | -| 19 | include/strata/plan/plan.hpp:22-42, 49-52, 83, 133 | Standalone planner `Geometry` (48 layers, 12 QSA, 48 v-heads, 10240 channels, indexer cache term), `Costs::expert_blob = 1382400`, `vram_pool_bytes() = 5,943,000,000`, "slots of 1,382,400 B" | CT | Used only by src/plan/plan_main.cpp and src/core/device_main.cpp. Not on the serving path. Has no streaming-KV or RAM-tier model. | -| 20 | src/core/graph.cpp (whole file) | None | RT | No geometry. Graphs are keyed by `(LayerType, n_tokens)`. | - -## B. Layer composition: `layer.hpp`, `layer.cpp`, `session.cpp` - -| # | file:line | Assumption | Class | Note | -|---|---|---|---|---| -| 21 | src/core/layer.cpp:1170-1286 (`block_layer_pre`), 1319-1342 (`block_layer_post`) | Every layer is `gr_read(attn) -> mixer -> gr_write(attn) -> gr_read(ffn) -> router ... moe_finish -> gr_write(ffn)` | ST | The gated-residual read/write wraps both mixer and FFN on every layer. No plain "rms_norm -> mixer -> residual add" branch exists. | -| 22 | src/core/layer.cpp:1231-1255 | Four GR tensors per half, prefixes `hc_attn_` and `hc_ffn_` (`norm`, `down`, `up`, `inject`), required engine forms (norm F32, other three BF16) | ST | Qwen3.6 has `attn_norm` and `post_attention_norm` (plain RMS norms) instead. Neither name is referenced anywhere in src/. | -| 23 | src/core/layer.cpp:1088-1107 (`lm_head_mix`) | Final mix is `gr_read` with `output_hc_norm/down/up` | ST | Qwen3.6 needs `output_norm.weight` (plain RMS norm). That name is not referenced anywhere in src/. Same in verify.cpp:1123-1125. | -| 24 | src/core/layer.cpp:1127-1145 (`block_buffers_bytes/init`) | `R` is `(hc, n_embd)`; `inject`, `inject2`, `gr_rs`, `gr_workspace_bytes(GrShapes{n_embd, hc, hc_lr})` | RT | Sized from `g.hc`. Works for hc = 1 in size, but the GR math is meaningless there. | -| 25 | src/core/layer.cpp:1146-1158 (`dump_stride_floats`) | C1-oracle dump layout is `2*n_embd + 2*hc + n_head*head_dim + ...` | RT | Debug only. | -| 26 | src/core/session.cpp:141-148 | The first token's residual is `hc` copies of the embedding | RT / ST | Loops `g.hc` times. With hc = 1 it is one copy. | -| 27 | src/core/session.cpp:1, 228, 331, 424 etc. | Comments say "48 layers", but loops use `g.n_layers` | RT | Verified: loops at 55, 77, 194-205, 283, 301, 331, 391, 424, 662, 788, 856, 921 all use `g.n_layers`. | -| 28 | src/core/session.cpp:41-44 | `gdn_state_floats = S*v_heads*S + conv_channels*(d_conv-1)` | RT | From `ModelGeometry`. Correct once row 2 is fixed. | -| 29 | src/core/session.cpp:50-52, 71, 124-126, 159-162 | `ple_hist_bytes() = NG_HIST * NG_HC_DIM * 4` (9 x 10240 floats) is always carved and zeroed | CT-ok | Fixed ~360 KB per session, allocated even with no PLE. Harmless but dead. | -| 30 | include/strata/core/layer.hpp:524-587 and src/core/layer.cpp:1192-1229 | PLE runs only at `layer == 1`, and only when `ple != nullptr && ple->ready()` | RT | PLE is optional in the block. See rows 62 to 66 for what forces it on. | -| 31 | src/core/layer.cpp:355 | `moe_route` requires `1 <= k <= 64`; `moe_finish`/`moe_combine_parts` the same (456, 472) | RT | K = 8 is fine. | -| 32 | src/core/layer.cpp:370 | Native fused router only when `n_expert == 512 && k == 10`, else generic `router_top10` | RT | Guarded at runtime. 256/8 takes the generic kernel (row 87). | -| 33 | src/core/layer.cpp:396 | `moe_route_window` batched path excluded when native router active at 512/10 | RT | Same guard. | -| 34 | src/core/layer.cpp:335-354 | `moe_buffers_*` sized from `n_expert`, `k`, `n_ff` | RT | | -| 35 | src/core/layer.cpp:418-451 (`moe_shared`) | Shared expert has a sigmoid scalar gate `ffn_gate_inp_shexp` that must be engine form BF16 (`Bf16InF32`); the three projections need S-forms | ST | Qwen3.6 has the same scalar gate. Its GGUF dtype (F32 or BF16) has to match what the loader produces; see the tensor tables below. | -| 36 | src/core/layer.cpp:223-333 (`gdn_layer`) | Sizes from `g.ssm_*`; recurrence head pairing is `head % h_k` | RT | Matches ggml `repeat` tiling. Needs `h_v % h_k == 0` (32 % 16 = 0). | -| 37 | src/core/layer.cpp:247-248 | Fused conv path requires `d_conv == 4 && state_size == 128`; fused step requires `state_size == 128` (306) | CT-ok | Qwen3.6 matches. | -| 38 | src/core/layer.cpp:276 | `scale_inplace(b.h, qk, 1/sqrt(S))` on the legacy (non-native) path | RT | | -| 39 | src/core/layer.cpp:288-318 and kernels (rows 76-79) | GDN output gate is `rms_norm(o) * ssm_norm * sigmoid(z)` | **ST / CT** | **Qwen3.6 uses SiLU(z), not sigmoid(z).** llama.cpp qwen35moe.cpp:273 `ggml_silu(gate)`, qwen4exp.cpp:481 says "the one numerical difference from Qwen3.5's GDN". The layer.hpp:16 comment records it. This is the only numerical (not geometric) GDN difference. | -| 40 | src/core/layer.cpp:505 (`qsa_shapes`) | Starts from `qsa_real_shapes()` then overrides `n_head`, `n_head_kv`, `head_dim`, `idx_*` from `ModelGeometry` | RT / CT | `n_rot = 64`, `idx_block = 4`, `idx_top_k = 2048`, `page_size = 4` stay compile-time (rows 41 to 44). `n_rot 64` matches Qwen3.6 (0.25 * 256). | -| 41 | include/strata/kernels/qsa.hpp:98-113 (`qsa_real_shapes`) | `n_head 24`, `idx_n_head 4`, `idx_dim 128`, `idx_block 4`, `idx_top_k 2048`, `page_size 4` | CT | Used by layer.cpp:505, mtp.cpp:71, verify.cpp:~100, prefill.cpp:862 etc. | -| 42 | include/strata/kernels/qsa.hpp:144-147, 282 | `qsa_selection_width = min(n_kv, idx_top_k + idx_block - 1)`; `kTopkMaxCells = 32768` | ST | Attention reads only the selected cells, via `ids`. With the indexer absent there is no selection, so every cell must attend. | -| 43 | src/core/layer.cpp:559-575, 761-790 | `qsa_state_bytes` / `qsa_buffers_bytes` include `idx_pooled`, `idx_tail`, `idx_dead`, `pooled_rows = max_cells/idx_block + 2`, indexer scratch, `cell_scores` | ST | The KV state always carries indexer state (about `max_cells/4 * 128 * 4` B per layer). The drafter already passes `ring_cells > 0` for a state "which has no indexer" (layer.cpp:527-531, `pooled_rows = 2`). | -| 44 | src/core/layer.cpp:876-1019 (`qsa_layer`) | Always runs: `indexer.k_proj` BF16 projection (962), indexer key append (945-948), `indexer.q_proj` + norm + rope (962-964), block scores + top-k (966-975), KV resolve, gather/attend over the selected `ids` | ST | The indexer is not optional in this function. It requires `indexer.{k,q}_proj.weight` BF16 and `indexer.{k,q}_norm.weight` (line 891 and the `Req` list). A dense path would skip steps 3, 5-indexer, 7, 8-score/select and attend over `0..n_kv`. | -| 45 | src/core/layer.cpp:891-897 | `w_idxk = v.get("indexer.k_proj.weight")` and `w_idxq` are dereferenced, with a BF16 form check | ST | Null here is an error, not a skip. | -| 46 | src/core/layer.cpp:938-1010 | KV in 4 formats (fp16 / int8 / q4_0 / k8v4), hybrid rotations (`fwht256`), paged pools | RT | `head_dim 256` only (kv_q4.cu:176). Same for Qwen3.6. | -| 47 | src/core/layer.cpp:556 | `qsa_kv_resident_min() = 20480` cells | CT-ok | Streaming floor. Independent of geometry. | - -## C. Loader, layout, metadata - -| # | file:line | Assumption | Class | Note | -|---|---|---|---|---| -| 48 | src/core/layout.cpp:50-80 | `check_one` requires per layer: `hc_attn_{down,up,inject}`, `hc_ffn_{down,up,inject}` with `hc_dim x hc_lr` shapes | ST | `blk.N.hc_*` do not exist in a Qwen3.6 GGUF. | -| 49 | src/core/layout.cpp:60-63 | `ffn_gate_inp [n_embd, n_expert]`, `ffn_{gate,up}_shexp [n_embd, n_ff]`, `ffn_down_shexp [n_ff, n_embd]` | RT | Use `ModelGeometry`. | -| 50 | src/core/layout.cpp:65-70 | GDN: `attn_qkv [n_embd, conv_channels]`, `attn_gate [n_embd, value_dim]`, `ssm_out [value_dim, n_embd]`, `ssm_conv1d [d_conv, channels]`, `ssm_alpha/beta [n_embd, v_heads]` | RT | Same orientation as llama.cpp qwen35moe. | -| 51 | src/core/layout.cpp:72-79 | Attention: `attn_q [n_embd, 2*n_head*head_dim]`, `attn_k/v [n_embd, n_kv*head_dim]`, `attn_output`, and `indexer.q_proj`, `indexer.k_proj` | RT / ST | Attention shapes RT. The two indexer tensors are ST (required). | -| 52 | src/core/layout.cpp:97-106 | 1-D set: `hc_attn_norm`, `hc_ffn_norm` (`hc_dim`, F32), `ffn_gate_inp_shexp` (BF16), `ssm_a`, `ssm_dt.bias`, `ssm_norm`, `attn_q_norm`, `attn_k_norm`, `indexer.q_norm`, `indexer.k_norm` | ST | Same split as rows 48 and 51. | -| 53 | src/core/layout.cpp:162-169 | `check_all` counts `g.n_qsa_layers()` / `g.n_gdn_layers()` | RT | | -| 54 | src/core/layout.cpp:141, 149; layout.hpp:91 | `check_layer` / `check_all` have no call site in src/ | n/a | Grep finds none. The shape assertions are not enforced at load in this tree. Parity tools outside src/ may call them. | -| 55 | include/strata/core/layout.hpp:63 | `is_qsa_layer = layer % interval == interval - 1` | RT | Layers 3, 7, ..., 39 for Qwen3.6. | -| 56 | src/core/weights.cpp:91, 123, 146-191 | Loads whatever `/index.txt` lists (19 fields per row), into an arena | RT | Name-driven and shape-driven. The model-specific part is the pack builder (`tools/pack_index.py`, `tools/iq_pack.py`, not in this tree). | -| 57 | src/core/native_dense.cpp:31-33 | Native dense GGUF suffixes: `.attn_qkv`, `.attn_gate`, `.ssm_out`, `.attn_q`, `.attn_k`, `.attn_v`, `.attn_output`, `.ffn_{gate,up,down}_shexp` (all `.weight`) | RT | The names match llama.cpp. A fused attention-layer `attn_qkv` (a llama.cpp option) would not match the engine's separate q/k/v. | -| 58 | src/core/native_dense.cpp:102-104, 169-172 | Needs `general.architecture` passing `check_architecture`; each native tensor must already be in the canonical table with a matching 2-D shape | ST | See row 18. Also requires a pack index entry per tensor. | -| 59 | src/core/native_head.cpp:29, 32-39 | `output.weight` must be `[n_in, n_out]`; `n_in % 256 == 0` | RT | 2048 % 256 = 0. `n_out` comes from the pack. | -| 60 | src/core/native_head.cpp:108-128 | `token_embd.weight` must be `[n_embd, n_vocab]` | RT | Caller passes the literals from row 11. | -| 61 | src/core/layer.cpp:1033-1087 (`embed_row`) | `w->ne0 != g.n_embd` is an error | RT | Follows `g.n_embd`. | - -## D. PLE and the n-gram table - -| # | file:line | Assumption | Class | Note | -|---|---|---|---|---| -| 62 | src/program/generate.cpp:1800-1815 | `--native` requires `--ple-gguf` (or a shard holding `per_layer_token_embd.weight`); `--native` plus `--no-ple` is refused | ST | Qwen3.6 has no such tensor, so every native launch is refused. | -| 63 | src/program/generate.cpp:1843-1855 | Without `--native`, `--ple-gguf` is "required"; `--no-ple` is called a "diagnostic ablation" | ST | PLE is mandatory at the CLI, optional in the kernels. | -| 64 | src/program/generate.cpp:2395-2500 | When a PLE table is opened, the pack must contain `blk.1.ple_{key,value,norm_key,norm_query,norm_conv,conv1d}.weight` or the launch fails ("a DIFFERENT MODEL") | ST | Skipped when `--no-ple`. | -| 65 | src/core/native_dense.cpp:29-30, 65-73, 156; generate.cpp:2207-2209, 1956 | Special-casing of `blk.1.ple_key.weight` | ST | Dead without PLE. | -| 66 | include/strata/kernels/ngram.hpp:31-49 | `NG_N_EMBD 2560`, `PLE_HEAD_DIM 160`, `NGRAM_SIZE 3`, `HEADS_PER_NGRAM 8`, `PLE_N_HEADS 16`, `NG_HC 4`, `NG_HC_DIM 10240`, `NG_HIST 9`, `PLE_TABLE_ROWS 320001536`, `PLE_EOS_TOKEN_ID 248044` | CT-ok | All PLE-only. Dead if PLE is skipped. `NG_HIST` x `NG_HC_DIM` still sizes a session buffer (row 29). | -| 67 | src/kernels/cuda/ple.cu:238; native_ple_postops.cu:35, 98; include/strata/kernels/native_ple_postops.hpp:6 | `static_assert(NG_N_EMBD == 2560 ...)`; `N = 2560, H = 4, HISTORY = 9` | CT-ok | Compiles regardless; never launched without PLE. | -| 68 | src/prefill/prefill.cpp:543-549, 806-814, 924-925, 1401, 1590-1599, 1683-1714, 1920 | Prefill allocates `ple_emb`, `ple_norm`, pinned PLE staging; runs the PLE at layer 1 when `ss.ple.ready()` | RT | Guarded by `ple_on`. Buffers are still allocated (about `T * 2560 * 4`, `NG_HC_DIM * 4`). | -| 69 | src/core/verify.cpp:370, 408, 559, 636-675, 1311, 1405 | Verify window stages and runs the PLE at layer 1 when `ss.ple.ready() && ple_stage()` | RT | Guarded. | - -## E. MTP drafter (`mtp.cpp`, `mtp.hpp`) - -| # | file:line | Assumption | Class | Note | -|---|---|---|---|---| -| 70 | src/core/mtp.cpp:150-216 | Loads `/dense.txt`, `dense.bin`, `experts.bin` produced by `tools/mtp_rt.py` (not in this tree), all dense weights as Q8_0 | ST | The drafter does not read the GGUF. | -| 71 | src/core/mtp.cpp:210-212 | Required tensors: `fc_embedding.weight`, `fc_hidden.weight`, `self_attn.{q,k,v,o}_proj.weight`, `mlp.shared_expert.{gate,up,down}_proj.weight` | ST | vLLM-style names. Qwen3.6's MTP has one `nextn.eh_proj [2*n_embd, n_embd]` over `[enorm(emb), hnorm(h)]`, not two separate projections. | -| 72 | src/core/mtp.cpp:488-495 | `pre_fc_norm_embedding` -> `fc_embedding`; `pre_fc_norm_hidden` over `hc*n_embd` -> `fc_hidden` per stream -> `R = h + e` broadcast over `hc` streams | ST | Qwen3.6: `eh_proj(concat(enorm(emb), hnorm(h)))`, one stream. | -| 73 | src/core/mtp.cpp:503-507, 564-568, 613-625 | Three hyper-connection groups: `attn_hyper_connection.*`, `mlp_hyper_connection.*`, `hyper_connection_mixer.*` | ST | Same gated-residual structure as rows 21-23. | -| 74 | src/core/mtp.cpp:191, 200, 306-308, 579 | Drafter experts are `n_expert * cpu::BLOB` bytes in VRAM, canonical Q2_0 at 2560/640, run through `moe_group_resident` | CT | `BLOB = 1,382,400`. Qwen3.6 Q2_0 blob would be `3 * 2048 * 512 * 18/64` = 884,736 B. Message text says "the 512 experts do not fit". | -| 75 | src/core/mtp.cpp:575, 598 | Draft router `mlp.gate.weight` BF16 `[n_embd, n_expert]`; `mlp.shared_expert_gate.weight` BF16 | RT | Shape-driven. | -| 76 | src/core/mtp.cpp:71-78, 218-249 | Draft KV is dense attention (no indexer state read), shapes from `ModelGeometry` | RT | The header says it is "identical to the model's sparse selection below 2,051 cells". The only existing dense-attention path. | -| 77 | src/core/mtp.cpp:428-454 | Head is the main `output.weight`; `n_vocab_ = wo->ne1`; optional `draft_vocab.bin` subset | RT | Vocabulary size is a runtime value. Subset files (`data/draft_vocab_*.bin`) are token ids into the same 248,320 vocabulary. | -| 78 | src/core/mtp.cpp:477, 488 | Draft embeds from `token_embd.weight` | RT | | -| 79 | src/core/mtp.cpp:251-268 | Buffers from `g.hc`, `g.hc_lr`, `g.n_head` | RT | | -| 80 | src/prefill/prefill.cpp:972-1086 | MTP prefill reads `attn_hyper_connection.hc_norm.weight`, uses `LR`, `HC`, `fc_hidden` per stream | ST / CT | Same vLLM-style structure as row 72. | - -## F. GDN kernels - -| # | file:line | Assumption | Class | Note | -|---|---|---|---|---| -| 81 | src/kernels/cuda/native_gdn.cu:37, 100-102, 117 | `S = 128`; grid `h_v` x `S/4`; requires `h_v % h_k == 0`, `h_v <= 65535` | RT | Heads from `GdnShapes`. State layout `(S, h_v, S)`. | -| 82 | src/kernels/cuda/native_gdn.cu:51 | `q_head = head % h_k` | RT | Modulo pairing. | -| 83 | src/kernels/cuda/fused_gdn.cu:12-14, 22-24, 127-129, 148-153 | `S = 128`, `RG = 4`; grid `h_v`; `qk_heads` blocks for conv+L2; `h_v % h_k == 0` | RT | | -| 84 | src/kernels/cuda/gdn.cu:46-59, 156 | `MAX_H = 8` heads per block, `S <= 128` | RT | Legacy path; only a performance shape. | -| 85 | src/kernels/cuda/gdn.cu:148 | `y = o * rms * ssm_norm * sigmoid_f(z)` | **CT** | **SiLU for Qwen3.6.** See row 39. | -| 86 | src/kernels/cuda/fused_gdn.cu:69 | `... * (1/(1+exp(-zz)))` in `gdn_step_norm_kernel` | **CT** | **SiLU for Qwen3.6.** The default decode path for native packs. | -| 87 | src/kernels/cuda/native_gdn_preprocess.cu:110-112 | `weighted * sigmoid(z)` in the out-norm kernel | **CT** | **SiLU for Qwen3.6.** The same file's `conv_silu` (53-67) and `beta_sigmoid` (86-88) are correct for both models. | -| 88 | src/prefill/kernels.cu:324, 612 | `sigm(z)` in `gdn_rec_kernel` and `gdn_out_norm_kernel` | **CT** | **SiLU for Qwen3.6.** Prompt path. | -| 89 | src/prefill/kernels.cu:18-19 | `N = 2560, HC = 4, D = N*HC, LR = 320`; `S = 128, HK = 16, HV = 48, C = 10240` | CT | Constants for every prompt-path GDN, GR and gate kernel. | -| 90 | src/prefill/kernels.cu:211-215, 285-304, 345-364, 387-432, 478-570, 893-924 | GDN prompt kernels index with `HV`, `HK`, `C`; launched `<<>>`, `<<>>`, `<<>>` | CT | Includes `VPK = HV/HK = 3` value heads per key head (478): 2 for Qwen3.6. `gdn_rec_kh_kernel` is specialised on it. | -| 91 | src/prefill/gdn_rec_parity.cu | Parity harness for the above | CT | Mirrors the same constants. | -| 92 | include/strata/kernels/gdn.hpp:11, 64; layer.hpp:10, 21, 23, 546 | Comments cite 10240 / 48 / 2560 | n/a | Comments only. | - -## G. Attention kernels (the QSA path) - -| # | file:line | Assumption | Class | Note | -|---|---|---|---|---| -| 93 | src/kernels/cuda/qsa_decode_attn.cu:16-17, 110, 272, 453, 497 | `HD = 256`, `G = 12` (query heads per KV head); refuses with `exit(1)` unless `n_head == 12 * n_head_kv` | CT | The main decode kernel. Qwen3.6 has G = 8. | -| 94 | src/kernels/cuda/qsa_prompt_attn.cu:21-22, 115-116, 1442-1447 | `HD = 256`, `G = 12`; refuses unless `n_head == 12 * n_head_kv` | CT | The prompt attention kernels (tensor-core). | -| 95 | src/kernels/cuda/native_flash_attn.cu:55, 196-197, 206 | `kv = head / 12`; refuses unless `n_head == 24 && n_head_kv == 2 && head_dim == 256`; grid 24; context 1..256 | CT | Short-context adapter only. | -| 96 | src/kernels/cuda/qsa.cu:96 | Generic `qsa_attend`/`kv_append`/`kv_gather`; requires `n_head % n_head_kv == 0` | RT | Reference-quality path. | -| 97 | src/kernels/cuda/native_rope.cu:121 | `head_dim in {128, 256}`, `n_rot == 64` | CT-ok | Matches Qwen3.6 (partial rotary 0.25 of 256). | -| 98 | include/strata/kernels/mrope.hpp:3-12 | Interleaved M-RoPE sections 11/11/10/0; text has `t = h = w` | CT-ok | Qwen3.6 uses the same sections. | -| 99 | src/kernels/cuda/native_qsa_score.cu:31, 194 | Indexer: `D = 128, HEADS = 4, R = 4`, `idx_top_k == 2048` | ST | Indexer-only. Not reachable without the indexer. | -| 100 | src/kernels/cuda/native_qsa_indexer.cu:35, 231, 259 | `D = 128, R = 4, ROT = 64` | ST | Indexer-only. | -| 101 | src/kernels/cuda/qsa_select.cu:17-19, 161-165, 467-475, 1081, 1115, 1220 | `IDX_DIM 128`, `IDX_HEADS 4`, `R 4`; requires `cap >= qsa_selection_width(kTopkMaxCells, s)` | ST | Indexer-only. With the indexer absent nothing here runs, and nothing else produces the `ids` that `qsa_decode_attn` consumes. | -| 102 | src/kernels/cuda/qsa_decode_attn.cu | The kernel gathers K/V through `ids` and `pools.page_table`, so it is selection-agnostic | RT | An identity `ids` would attend over every cell. No other dense decode kernel exists. | -| 103 | src/kernels/cuda/kv_q4.cu:176, kv_q8.cu | `head_dim == 256` | CT-ok | Matches Qwen3.6. | -| 104 | src/kernels/cuda/kv_stream.cu:23 | `RT = 1024` resolve block | CT-ok | Streaming resolve granularity. Reads `ids`. | -| 105 | src/prefill/kernels.cu:752-761, 1016, 1020 | `split_q_kernel`, `gate_attn_kernel`: `T * 24 * 256`, `24 * 512` | CT | Prompt-path q/gate split and gate. 16 heads for Qwen3.6. | -| 106 | src/prefill/prefill.cpp:649-650, 883-884 | `T * 12288` (= 24 * 512) for `Qf`; `T * 512` for `Kc/Vc` (2*256, unchanged); `T * ZV` for `q` and attn; `T * 128`, `T * 512` for `idx_raw`, `q_idx` | CT | `12288` and `ZV = 6144` must change. `512` for K/V stays. The two indexer buffers are dead without the indexer. | - -## H. Experts, router, shared expert - -| # | file:line | Assumption | Class | Note | -|---|---|---|---|---| -| 107 | include/strata/kernels/cpu/expert.hpp:34-36, 40-47 | `H = 2560`, `FF = 640`, `NE = 512`, `BLOB = 1,382,400`, `ROW_GU`, `SC_GU` | CT | Canonical Q2_0 blob geometry. Canonical only. Used by the rows below. | -| 108 | src/kernels/cpu/expert_layout.cpp:284 | `native_fmt(gt, dt, H, FF, f, err)` | **CT** | **The one compile-time leak in the native-pack path.** The layout loader builds each layer's `NativeFmt` with 2560/640 and then checks `f.bytes == blob`. A 2048/512 pack fails the "blob is X B but its formats make Y" check. | -| 109 | src/kernels/cpu/expert_layout.cpp:233-244, 271 | `native_experts.txt` header "(n_expert N)" overrides `n_expert`; absent file means canonical pack, total = `n_layers*n_expert*BLOB` | RT | | -| 110 | include/strata/kernels/cpu/expert_layout.hpp:20, 32, 35-37 | `n_expert = NE` default, `max_blob = BLOB` default | CT-ok | Overwritten for native packs. | -| 111 | include/strata/kernels/cpu/native_expert.hpp:17-19; src/kernels/cpu/native_expert.cpp:64 | `kNativeActBytes = 4096`, `kNativeHBytes = 1024` upper bounds, checked at layout time | CT-ok | 2048-wide Q8_K is 2336 B; 512-wide Q8_K is 584 B. Both fit. | -| 112 | src/kernels/cpu/native_expert.cpp:40-60 | `native_fmt(gu_type, d_type, n_embd, n_ff)` is runtime; requires whole ggml blocks | RT | 2048 and 512 are multiples of 256 and 32. K-quants and Q8_K activations work for n_ff = 512 (unlike 640). | -| 113 | src/core/expert_source.cpp:1863-1868 (`expert_pool_dispatch`) | Refuses `n_embd != H` ("compiled for a 2560-wide activation") | CT | Canonical single-token path only. | -| 114 | src/core/expert_source.cpp:1869-1875 | `expert_pool_dispatch` refuses a native pack outright ("single-token expert path does not take a native pack") | **ST** | **Native-pack experts run only in verify windows.** generate.cpp:~2180 also requires `--spec T >= 2` and `--prefill`. Every decoded token therefore goes through verify.cpp. | -| 115 | src/core/expert_source.cpp:367-376, 2328; include/strata/core/expert_source.hpp:241 | Canonical size checks with `BLOB`; `ExpertDispatch::n_expert = cpu::NE`; hit path uses `cpu::H` | CT | Canonical only. `n_expert` is overwritten at generate.cpp:3683. | -| 116 | src/core/expert_source.cpp:2475-2500 (`check_experts_gguf`) | Native experts are read from `blk.N.ffn_{gate,up,down}_exps.weight` as three separate tensors, each `[cols, rows, n_expert]` | ST | llama.cpp may fuse gate and up into `ffn_gate_up_exps` (`create_tensor_gate_up_exps`, llama-model.cpp:3253). The engine accepts only the separate form. | -| 117 | src/core/expert_source.cpp:1979-1980 | `MAXT * 10 <= kMaxWindowEntries (128)` | CT-ok | 8 * 10 = 80; with k = 8 it is 64. | -| 118 | src/core/expert_cache.cpp, include/strata/core/expert_cache.hpp | Slots, residency `[n_layers * n_expert]`, profile file `(n_layers, n_expert)` header, `n_layers/n_expert <= 65535` | RT | All sizes passed in. The profile header is checked against `(n_layers, n_expert)` (cache.cpp:43). | -| 119 | src/kernels/cuda/iq_kernels.cu:1076-1140, 2543 | Native GPU expert kernels read `L.n_embd` and `L.n_ff` per layer; the fast sub-warp paths apply only when `n_ff == 640` (else 8-row fallback) | RT | Runtime guard. | -| 120 | src/kernels/cuda/iq_kernels.cu:309-350, 512-518 | Unsloth UD-Q4_K_XL expert types already supported: Q4_K / Q5_K gate-up, Q5_1 / Q8_0 down | RT | Native GPU expert dequant kernels exist for the Qwen3.6 UD quant family. | -| 121 | src/kernels/cuda/s2_expert_grouped.cu:37-46, 139-195, 301-346 | `H = 2560`, `FF = 640`, `ROW_GU`, `SC_GU`, blob offsets | CT | Canonical Q2_0 VRAM-hit kernels. Used for the MTP drafter's experts (row 74), not for native packs. | -| 122 | src/core/remote_experts.cpp:16-18, 246; src/core/peer_experts.cpp:25-26, 115, 130; src/core/remote_expert_opt.cu:13-14 | `H`, `FF` from `cpu::`, `CAP = MAXT * 10`, `k != 10` refused | CT | Multi-GPU expert tiers. Out of scope for a single card. | -| 123 | src/program/generate.cpp:3721 | `moe_hit_grouped_scratch_bytes(K, g.n_embd, cpu::FF)` | CT-ok | Over-allocates by 640 vs 512. | -| 124 | src/kernels/cuda/router_top10.cu:65-215; include/strata/kernels/router_top10.hpp:21 | Generic top-k softmax router: `n_expert <= 512`, `k <= 32`, runtime `n_expert` and `k` | RT | Handles 256 / 8. | -| 125 | src/kernels/cuda/native_router.cu:49, 54, 73, 97, 111-122 | Fused pinned router: `512` logits, `10` outputs, `REG 16`, hard-coded in the kernel and the validity checks | CT | Used only when `n_expert == 512 && k == 10` (row 32). Otherwise bypassed. | -| 126 | src/kernels/cuda/native_moe.cu:62-63, 79-80 | `native_moe_combine` requires `1 <= k <= 15` | RT | | -| 127 | src/kernels/cuda/shared_expert.cu:191, 237-239, 325-328 | `n_tok 1..8`; Q8_K activation needs `n_ff % 256 == 0` | RT | 640 failed this; 512 passes. Header comments in s_gemv.hpp:122-124 and layer.cpp:419-437 ("Q8_K is structurally impossible") describe Flash-Next only. | -| 128 | src/prefill/kernels.cu:616-657, 928-936 | Prompt `route_kernel`: `REG 16` for 512, `REG 8` for 256; rank loop `< 10`, writes `ids[t*10 + rank]`, `lane < 10` | CT | A 256 variant exists, but top-10 is baked into the kernel. | -| 129 | src/prefill/kernels.cu:660-692, 947, 951; moe_fused.cu:46-53, 199-203, 343; moe_mmq.cu:60-75, 249 | Canonical Q2_0 blob dequant and fused kernels: `1280 * 640`, `2560 * 160`, `n * 640`, `10 * AB` | CT | Canonical only. | -| 130 | src/prefill/moe_fused_iq.cu:59 | `GU_ROWS_K = 2560, D_ROWS_K = 640` | CT | Native-pack fused prompt MoE. Used as K of gate/up and of down. | -| 131 | src/prefill/prefill.cpp:90-91 | `N = 2560, HC = 4, D = N*HC, LR = 320, K = 10, NE = 512; C = 10240, ZV = 6144, HV = 48` | CT | File-wide constants. | -| 132 | src/prefill/prefill.cpp:737 | `Prefill::init` refuses unless `g.n_embd == N && g.hc == HC && g.hc_lr == LR && ss.k == K` | CT / ST | Hard refusal; every chunked-prefill launch fails on Qwen3.6. | -| 133 | src/prefill/prefill.cpp:681-685, 704-721, 896-907, 1294-1322, 1391 | Prompt MoE buffers: `T*K*1280`, `T*K*640`, `q8_bytes(.., 640)`, `1280 * 2560`, `2560 * 640`, `RP = 48` (1303) | CT | `1280 = 2*n_ff`, `640 = n_ff`, `2560 = n_embd`. | -| 134 | src/prefill/prefill.cpp:1724 and loops | Iterates `g.n_layers` and `is_qsa_layer` | RT | | -| 135 | src/prefill/prefill.cpp:854-856, 1000-1026, 1375-1380 | `grs`, `gated`, `inj`, `xq`, `ident` sized from `HC`, `D`, `LR` | CT | Hyper-connection buffers in prefill. | -| 136 | include/strata/prefill/kernels.hpp:15-16, 40, 52, 54, 58, 79 | Declarations documented as `2560 / 4 / 320`, `48 v heads`, `512, top-10`, `[1280, 2560]`, `640`, `[T, 24, 512]` | CT | Comments describing the constants above. | - -## I. Hyper-connection (gated residual) kernels - -| # | file:line | Assumption | Class | Note | -|---|---|---|---|---| -| 137 | src/kernels/cuda/fused_gr.cu:20-28, 253-254, 320-321, 1164-1166 | `N = 2560, HC = 4, LR = 320, D = 10240`; `DOWN_BLOCKS = LR/8`, `UP_BLOCKS = N/32`, `UPM_BLOCKS = N/16`; `fused_gr_supported()` returns `n_embd == N && hc == HC && hc_lr == LR` | CT | Default decode and verify GR kernels. | -| 138 | src/core/layer.cpp:1195, 1319-1342, verify.cpp:336 | `fused = g_fused_gr && ... fused_gr_supported(...)`; verify refuses without it | CT / ST | Row 142. | -| 139 | src/kernels/cuda/gr.cu, native_gr_norm.cu, native_gr_postops.cu | Generic `GrShapes{n_embd, hc, hc_lr}` unfused path | RT | The generic GR is runtime-shaped, but its semantics (down/up/inject mixing) are the hyper-connection. | -| 140 | src/kernels/cuda/cvec.cu:11-17; verify_kernels.cu:256-291 (`broadcast_streams`, `add_streams_broadcast`) | Control-vector apply on `hc*n_embd`; stream broadcast | RT | `MAXK = 16` supports `n_embd <= 4096`. | - -## J. Verify window (`verify.cpp`) and the speculation protocol - -| # | file:line | Assumption | Class | Note | -|---|---|---|---|---| -| 141 | src/core/verify.cpp:331-334 and layer.cpp:476-486 (`layer_verify_compatible`) | The verify window needs native BF16 projections, fused GR, fused native GDN, split-K decode attention, block top-k selection, **native QSA indexer** | ST | Verify is the only decode path for native packs (row 114). It cannot be built on a layer that has no fused GR and no indexer. | -| 142 | src/core/verify.cpp:336-340 | Refuses unless `fused_gr_supported && ss.k == 10 && ssm_state_size == 128 && ssm_d_conv == 4` ("geometry differs from the artifact's") | CT / ST | | -| 143 | src/core/verify.cpp:356-434 | Buffers `R_ (T*HC*N)`, `inj_`, `lo_ (T*hc_lr)`, `xn_ (T*HC*N)`, `idx_raw_L_`, `qidx_`, `tail_snap_` | RT / ST | Sized from `g.hc`, `g.hc_lr`, `idx_*`. | -| 144 | src/core/verify.cpp:550-559 | `IQ = idx_q_heads`, `ID = idx_key_dim`, `NE = n_expert`, `TS = (idx_block-1)*ID` | RT | | -| 145 | src/core/verify.cpp:757-761, 772-870, 1271-1311 | Attention step: `need(v, "indexer.k_proj.weight")`, `indexer.q_proj`, `indexer.q_norm`, `indexer.k_norm`; indexer append, block scores, top-k per window row; commit restores the indexer tail | ST | Same as row 44, for the multi-token path. | -| 146 | src/core/verify.cpp:916 | Batched native router only when `NE == 512 && K == 10` | RT | Guarded. | -| 147 | src/core/verify.cpp:1123-1125 | Head mix needs `output_hc_{norm,down,up}.weight` | ST | Row 23. | -| 148 | src/core/verify.cpp:347-349 | `n_vocab_ = output.weight.ne1` | RT | | -| 149 | include/strata/kernels/verify_kernels.hpp:21 | `kVerifyMaxT = 8` | CT-ok | Draft window cap. | -| 150 | src/kernels/cuda/verify_kernels.cu:366, 397-401, 506 | Grid `48 * 8`; `kVerifyMaxT * 10 <= kResidentPlanMax` | CT-ok | The 48 is a block count, not a layer count. | - -## K. Vocabulary, sampler, metadata keys - -| # | file:line | Assumption | Class | Note | -|---|---|---|---|---| -| 151 | src/kernels/cuda/sampler.cu:102-700 | `n_vocab` is a kernel argument everywhere; the split top-k merge handles `n_vocab <= 262,144` (607) | RT | 248,320 fits. | -| 152 | src/program/generate.cpp:479-481 | Default EOS ids `{248044, 248046}` | CT-ok | Same tokenizer; override with `--eos-ids`. | -| 153 | include/strata/artifact/gguf_reader.hpp:581-597 | All keys read use the `qwen4exp.` prefix | CT | Row 18. The Qwen3.6 GGUF uses `qwen35moe.*`. Also needed and not read anywhere: `qwen35moe.ssm.{conv_kernel,inner_size,state_size,time_step_rank,group_count}`, `.expert_feed_forward_length`, `.expert_shared_feed_forward_length`, `.full_attention_interval`, `.rope.dimension_sections`, `.nextn_predict_layers`. | -| 154 | frontend/ | Tokenizer, template, tool-call parser, vision | n/a | Model-agnostic per the plan. Not part of this inventory. | - -## Tensor names the loader expects (engine side) against llama.cpp qwen35moe - -Engine names come from layout.cpp:50-106, layer.cpp, native_dense.cpp:31-33 and expert_source.cpp:2491. -llama.cpp names come from `third_party/llama.cpp/src/models/qwen35moe.cpp:43-138` and `src/llama-arch.cpp:435-587` -(pinned commit 3cf0325). - -**One GDN layer, `blk.N.`** - -| Engine expects | Shape / form | llama.cpp qwen35moe | Match | -|---|---|---|---| -| `hc_attn_norm.weight`, `hc_attn_down.weight`, `hc_attn_up.weight`, `hc_attn_inject.weight` | `[hc_dim]` F32; BF16 | none | **Engine-only (hyper-connection)** | -| `hc_ffn_norm.weight`, `hc_ffn_down.weight`, `hc_ffn_up.weight`, `hc_ffn_inject.weight` | same | none | **Engine-only** | -| (none) | | `attn_norm.weight` `[n_embd]` | **llama.cpp-only** | -| (none) | | `post_attention_norm.weight` `[n_embd]` (pre-FFN norm; there is no `ffn_norm`) | **llama.cpp-only** | -| `attn_qkv.weight` | `[n_embd, conv_channels]` | `attn_qkv.weight` `[n_embd, 2*key_dim + value_dim]` | yes | -| `attn_gate.weight` | `[n_embd, value_dim]` | `attn_gate.weight` | yes | -| `ssm_conv1d.weight` | `[d_conv, conv_channels]` F32 | `ssm_conv1d.weight` | yes | -| `ssm_alpha.weight`, `ssm_beta.weight` | `[n_embd, v_heads]` BF16 | same names, `{n_embd, n_v_heads}` | yes, dtype to confirm | -| `ssm_a` | `[v_heads]` F32 | `ssm_a` (no `.weight`) | yes | -| `ssm_dt.bias` | `[v_heads]` F32 | `ssm_dt.bias` | yes | -| `ssm_norm.weight` | `[128]` F32 | `ssm_norm.weight` `{head_v_dim}` | yes | -| `ssm_out.weight` | `[value_dim, n_embd]` | `ssm_out.weight` | yes | -| `ffn_gate_inp.weight` | `[n_embd, n_expert]` BF16 | same | yes, dtype to confirm | -| `ffn_gate_exps.weight`, `ffn_up_exps.weight`, `ffn_down_exps.weight` | `[n_embd, n_ff, n_expert]` x2, `[n_ff, n_embd, n_expert]` | same, or fused `ffn_gate_up_exps.weight` `[n_embd, 2*n_ff, n_expert]` | yes if unfused | -| `ffn_gate_shexp.weight`, `ffn_up_shexp.weight`, `ffn_down_shexp.weight` | `[n_embd, n_ff]`, `[n_ff, n_embd]` | same | yes | -| `ffn_gate_inp_shexp.weight` | `[n_embd]` engine form BF16 | `ffn_gate_inp_shexp.weight` `{n_embd}` | yes, dtype to confirm | - -**One attention layer, `blk.N.` (layers 3, 7, ..., 39)** - -| Engine expects | Shape / form | llama.cpp qwen35moe | Match | -|---|---|---|---| -| the six `hc_*` tensors and two `hc_*_norm` as above | | none | **Engine-only** | -| (none) | | `attn_norm.weight`, `post_attention_norm.weight` | **llama.cpp-only** | -| `attn_q.weight` | `[n_embd, 2*n_head*head_dim]` (q then gate per head, interleaved) | `attn_q.weight` `{n_embd, head_dim*n_head*2}` | yes | -| `attn_k.weight`, `attn_v.weight` | `[n_embd, n_kv*head_dim]` | same | yes, unless the GGUF fuses them into `attn_qkv.weight` (`create_tensor_qkv`) | -| `attn_output.weight` | `[n_head*head_dim, n_embd]` | `attn_output.weight` | yes | -| `attn_q_norm.weight`, `attn_k_norm.weight` | `[head_dim]` F32 | same | yes | -| `indexer.q_proj.weight`, `indexer.k_proj.weight`, `indexer.q_norm.weight`, `indexer.k_norm.weight` | BF16 / F32 | none | **Engine-only (QSA indexer)** | -| the same five MoE tensors, three shexp tensors, `ffn_gate_inp_shexp` as a GDN layer | | same | as above | - -**Global tensors** - -| Engine expects | llama.cpp qwen35moe | -|---|---| -| `token_embd.weight` `[n_embd, n_vocab]` | same | -| `output.weight` `[n_embd, n_vocab]` (native head; mtp.cpp:428 and verify.cpp:347 read `ne1`) | `output.weight` (optional; falls back to `token_embd.weight`) | -| `output_hc_norm.weight`, `output_hc_down.weight`, `output_hc_up.weight` | `output_norm.weight` `{n_embd}` | -| `blk.1.ple_{key,value,norm_key,norm_query,norm_conv,conv1d}.weight` and `per_layer_token_embd.weight` | none | -| MTP: `/dense.txt` names `fc_embedding`, `fc_hidden`, `pre_fc_norm_embedding`, `pre_fc_norm_hidden`, `self_attn.*`, `mlp.*`, three `*hyper_connection*` groups | `blk.40.nextn.eh_proj.weight` `{2*n_embd, n_embd}`, `blk.40.nextn.enorm.weight`, `blk.40.nextn.hnorm.weight`, optional `blk.40.nextn.{embed_tokens,shared_head_head,shared_head_norm}.weight`, plus a full attention + MoE block under `blk.40.` (attn_norm, post_attention_norm, attn_q/k/v/output, attn_q_norm, attn_k_norm, ffn_gate_inp, ffn_*_exps, ffn_*_shexp, ffn_gate_inp_shexp) | - -## Summary of which subsystems are runtime-parameterized - -1. **Already parameterized:** the GDN decode kernels (state 128, head counts and head pairing by `h % h_k`, grids from `h_v`), the generic router, the shared expert (and 512 now satisfies its Q8_K rule), the native CPU and GPU expert kernels (`NativeFmt` and `L.n_embd`/`L.n_ff` per layer, UD-Q4_K_XL types already present), the expert cache, the weight loader, the sampler, `output.weight` and vocabulary size, and the drafter's dense-attention KV. -2. **The geometry struct is never populated from the model.** Only `expert_count` and `expert_used_count` (and rope keys) are read, under a `qwen4exp.` prefix, and only with `--native`. `n_embd`, `n_layers`, head counts, `ssm.*` and `n_ff` stay at Flash-Next defaults. `check_architecture` refuses any other architecture string. -3. **The gated residual is structural.** Every block, the output head, the verify window, the drafter and prefill assume `hc` streams with down/up/inject mixing. The fused kernels are hard-coded to 2560/4/320, and `hc = 1` has no plain-norm meaning. The plain `attn_norm`, `post_attention_norm` and `output_norm` tensors are never referenced. -4. **Dense attention is structural.** `qsa_layer`, `verify.cpp`, the KV state size and the selection width all assume the indexer. The decode and prompt attention kernels are compile-time for group 12 (Qwen3.6 is 8) and the short-context kernel is compile-time for 24 heads. The attention kernel reads through `ids`, so it is selection-agnostic, but no producer of dense `ids` exists. -5. **GDN output gate differs numerically:** Qwen3.6 applies SiLU(z) where the engine applies sigmoid(z) in four kernels (gdn.cu, fused_gdn.cu, native_gdn_preprocess.cu, prefill/kernels.cu). This is a semantic change, not a size change. -6. **Native-pack decode is verify-window only.** The single-token expert dispatch refuses native packs, and the verify window demands fused GR, K = 10, and the native indexer. Any hc = 1 or dense-attention work has to land in verify.cpp as well as layer.cpp. -7. **Prefill is the most compile-time-heavy subsystem.** `Prefill::init` refuses non-2560/4/320/10, and GDN, gate, split-q, route and MoE buffers all use literal constants (HV 48, 24 heads, 1280, 640, top-10). -8. **One leak inside otherwise-runtime expert code:** `expert_layout.cpp:284` passes compile-time `H, FF` to `native_fmt`, so a 2048/512 pack fails the blob-size check. -9. **PLE is optional in kernels but mandatory in the CLI.** `--native` refuses to start without `--ple-gguf`, and a table implies `blk.1.ple_*` tensors. Qwen3.6 has neither. A small session buffer (about 360 KB) is allocated regardless. -10. **MTP drafter is separate from the GGUF** (Q8_0 `rt_dir` from `tools/mtp_rt.py`, canonical Q2_0 experts at 2560/640, three hyper-connection groups, two fc projections). It gets the canonical default geometry, not the target's. The `tools/` packers are not in this tree, so the pack and MTP tensor names are defined by scripts that were not inspected. diff --git a/docs/qwen36-port/gguf-metadata.md b/docs/qwen36-port/gguf-metadata.md deleted file mode 100644 index 70db9eb..0000000 --- a/docs/qwen36-port/gguf-metadata.md +++ /dev/null @@ -1,102 +0,0 @@ -# Qwen3.6-35B-A3B GGUF: metadata and tensors as shipped - -Dumped 2026-10-11 with `tools/gguf_reader.py` (no gguf-py) from two files: - -- **Plain**: `/Users/robertkarl/models/qwen3.6/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf` (Unsloth `UD-IQ3_XXS`, 733 tensors, `general.file_type` 23, 13.2 GB). The file the port is built against. -- **MTP**: `/Users/robertkarl/models/qwen3.6/MTP/Qwen3.6-35B-A3B-UD-IQ4_XS-MTP.gguf` (753 tensors, 41 blocks). Same architecture plus the nextn block. Shown only where it differs. - -GGUF dims below are **ne order** (fastest first). The numpy / `ref/load.py` shape is the reverse, `(out, in[, experts])`. -"llama.cpp reads it" cites the pinned submodule (`third_party/llama.cpp`, commit 3cf0325). - -## Metadata - -| key | value | llama.cpp reads it | -| --- | --- | --- | -| `general.architecture` | `qwen35moe` | `llama-arch.cpp:42` | -| `qwen35moe.block_count` | 40 (MTP file: 41) | `llama-model.cpp:1259`; trunk layers = block_count - nextn | -| `qwen35moe.nextn_predict_layers` | **absent** in the plain file; 1 in the MTP file | `llama-model.cpp:1261`, optional, default 0 | -| `qwen35moe.context_length` | 262144 | `llama-model.cpp:1254` | -| `qwen35moe.embedding_length` | 2048 | `:1255` | -| `qwen35moe.attention.head_count` / `head_count_kv` | 16 / 2 | `:1328`, `:1336` | -| `qwen35moe.attention.key_length` / `value_length` | 256 / 256 | `:1372`, `:1375` | -| `qwen35moe.attention.layer_norm_rms_epsilon` | 1e-6 (stored as f32 9.99999997e-07) | `qwen35moe.cpp:7`, required | -| `qwen35moe.rope.dimension_count` | 64 (= 0.25 * 256) | `:1380` | -| `qwen35moe.rope.dimension_sections` | `[11, 11, 10, 0]` (sum 32 = 64 / 2) | `qwen35moe.cpp:9`, required, 4 entries | -| `qwen35moe.rope.freq_base` | 1e7 | `:1347` | -| `qwen35moe.expert_count` / `expert_used_count` | 256 / 8 | `:1263`, `:1265` | -| `qwen35moe.expert_feed_forward_length` | 512 | `qwen35moe.cpp:5` | -| `qwen35moe.expert_shared_feed_forward_length` | 512 | `qwen35moe.cpp:6` | -| `qwen35moe.ssm.conv_kernel` | 4 | `qwen35moe.cpp:12` | -| `qwen35moe.ssm.state_size` | 128 (head dim of k and v) | `:14` | -| `qwen35moe.ssm.group_count` | 16 (k heads) | `:16` | -| `qwen35moe.ssm.time_step_rank` | 32 (v heads) | `:15` | -| `qwen35moe.ssm.inner_size` | 4096 (= 32 * 128, the value dim) | `:13` | -| `qwen35moe.full_attention_interval` | 4 | `:22`; layer `il` is recurrent when `(il+1) % 4 != 0` | -| `tokenizer.ggml.model` / `pre` | `gpt2` / `qwen35` | vocab, 248320 tokens, 247587 merges | -| `tokenizer.ggml.{bos,eos,padding}_token_id` | 248044 / 248046 / 248055 | `add_bos_token` false | -| `tokenizer.chat_template` | 8424 characters | frontend, not llama.cpp's graph | -| `general.*`, `quantize.imatrix.*` | name, license, Unsloth provenance, imatrix file | not used by the graph | - -Keys that are **not** in the file and **not** read by the `qwen35moe` loader: `expert_weights_norm`, `expert_weights_scale`, -`attention.recurrent_layers` (read if present, `qwen35moe.cpp:20`), `feed_forward_length`, `expert_group_count`, rope scaling. -`HParams` defaults then apply: `expert_weights_scale` stays 0.0 (`llama-hparams.h:124`, the key is never loaded for this architecture), -so no scaling; `norm_w` is hard-coded `true` at the call site (`qwen35moe.cpp:506`), so the top-8 weights always renormalize to sum 1. -A GGUF cannot change either; a stray `qwen35moe.expert_weights_scale` key is ignored (checked with `--expert-weights-scale` on the fixture). - -## Tensors (plain file, 733) - -| name | ne | dtype in the IQ3_XXS file | count | -| --- | --- | --- | --- | -| `token_embd.weight` | 2048, 248320 | Q6_K | 1 | -| `output.weight` | 2048, 248320 | Q6_K (not tied) | 1 | -| `output_norm.weight` | 2048 | F32 | 1 | -| `blk.N.attn_norm.weight` | 2048 | F32 | 40 | -| `blk.N.post_attention_norm.weight` | 2048 | F32 | 40 | -| `blk.N.ffn_gate_inp.weight` (router) | 2048, 256 | F32 | 40 | -| `blk.N.ffn_gate_exps.weight` | 2048, 512, 256 | IQ2_S | 40 | -| `blk.N.ffn_up_exps.weight` | 2048, 512, 256 | IQ2_S | 40 | -| `blk.N.ffn_down_exps.weight` | 512, 2048, 256 | IQ3_XXS (37), IQ4_XS (3: layers 34, 38, 39) | 40 | -| `blk.N.ffn_gate_inp_shexp.weight` | **2048** (1-D) | F32 | 40 | -| `blk.N.ffn_{gate,up}_shexp.weight` | 2048, 512 | Q6_K | 80 | -| `blk.N.ffn_down_shexp.weight` | 512, 2048 | Q6_K | 40 | -| GDN layers (30: 0-2, 4-6, ..., 36-38): | | | | -| `blk.N.attn_qkv.weight` | 2048, 8192 (= 2*2048 + 4096) | Q6_K | 30 | -| `blk.N.attn_gate.weight` (z) | 2048, 4096 | Q6_K | 30 | -| `blk.N.ssm_conv1d.weight` | 4, 8192 | F32 | 30 | -| `blk.N.ssm_alpha.weight`, `ssm_beta.weight` | 2048, 32 | F32 | 60 | -| `blk.N.ssm_a` (no `.weight` suffix) | 32 | F32 | 30 | -| `blk.N.ssm_dt.bias` | 32 | F32 | 30 | -| `blk.N.ssm_norm.weight` | 128 | F32 | 30 | -| `blk.N.ssm_out.weight` | 4096, 2048 | Q6_K | 30 | -| Attention layers (10: 3, 7, ..., 39): | | | | -| `blk.N.attn_q.weight` (query and gate, interleaved per head) | 2048, 8192 (= 16 * 2 * 256) | Q6_K | 10 | -| `blk.N.attn_k.weight`, `attn_v.weight` | 2048, 512 (= 2 * 256) | Q6_K | 20 | -| `blk.N.attn_output.weight` | 4096, 2048 | Q6_K | 10 | -| `blk.N.attn_q_norm.weight`, `attn_k_norm.weight` | 256 | F32 | 20 | - -Values worth knowing (layer 0 and 3): `ssm_a` is **negative**, -72.3 to -0.019 (it is `-exp(A_log)`, so `gate = softplus(alpha + dt_bias) * ssm_a` is already a log decay); -`ssm_dt.bias` -5.3 to 15.6; every RMS-norm weight is stored multiplicatively (`attn_norm` mean 1.03, `output_norm` mean 2.63), so no "+1" is applied anywhere; -`ssm_conv1d` is within +-0.41; `ffn_gate_inp_shexp` is a 2048-vector with mean 0. - -## The nextn block (MTP file only) - -`blk.40` is the draft block, 20 tensors: the same ones an attention layer plus MoE carries (`attn_norm`, `post_attention_norm`, `attn_q/k/v/output`, -`attn_q_norm/k_norm`, `ffn_gate_inp`, `ffn_{gate,up,down}_exps`, `ffn_gate_inp_shexp`, `ffn_{gate,up,down}_shexp`) plus -`nextn.eh_proj.weight` (4096, 2048: one projection over `[enorm(token embedding), hnorm(hidden)]` concatenated, embedding first), -`nextn.enorm.weight`, `nextn.hnorm.weight`, `nextn.shared_head_norm.weight` (each 2048, F32). -There is **no** `nextn.embed_tokens` and **no** `nextn.shared_head_head`: the block embeds with `token_embd.weight` and the draft head is the main `output.weight` -(`qwen35moe.cpp:583`, `:733`); the head norm is `shared_head_norm` when present, else `output_norm`. -In that file the nextn router `blk.40.ffn_gate_inp.weight` and `ffn_gate_inp_shexp.weight` are **BF16** while the trunk's are F32; the -experts are Q3_K gate/up and Q4_K down (trunk: IQ3_S / IQ4_XS). - -## What was unexpected - -- **The plain GGUF has no nextn block at all.** `nextn_predict_layers` is absent and `block_count` is 40. The MTP head exists only in the separate `-MTP.gguf` builds, which carry 41 blocks. -- **Gate and up are not fused** (`ffn_gate_exps` + `ffn_up_exps`), and attention layers are **not** fused (`attn_q`, `attn_k`, `attn_v`). `attn_qkv` exists, but only in the 30 GDN layers where it feeds the conv, next to a separate `attn_gate` (z). llama.cpp accepts the fused forms (`llama-model.cpp:3253-3300`, `ffn_gate_up_exps` with gate rows first, `attn_qkv` with Q|K|V rows), and the fixture and oracle support both, but no shipped file uses them. -- **`expert_weights_norm` and `expert_weights_scale` are not in the file and cannot matter**: the architecture hard-codes renormalization and never loads a scale (see above). -- **The router and the GDN `ssm_alpha` / `ssm_beta` are F32**, not BF16. `ref/load.py`'s `FORM` table in `iq_pack.py` must not assume the Flash-Next BF16 forms for them. -- **`attn_q` is 2x wide**: per head 256 query values then 256 gate values, interleaved, which is how `attn_output_gate` is stored. There is no separate gate tensor. -- **`ssm_a` carries no `.weight` suffix** and `ssm_dt` is named `ssm_dt.bias`. -- **`ffn_gate_inp_shexp` is 1-D** (a vector, producing one scalar per token), not a 2048x1 matrix. -- **Per-layer quantization is mixed** (down experts: IQ3_XXS in 37 layers and IQ4_XS in 3; the MTP block uses a different family altogether), so any pack format must carry a type per layer and per role, as `native_experts.txt` already does. -- `ref/load.py` did not know IQ2_S, IQ3_XXS, IQ3_S (gate/up/down of this file); it is extended in the same commit that adds the oracle. diff --git a/docs/qwen36-port/oracle-crosscheck.md b/docs/qwen36-port/oracle-crosscheck.md deleted file mode 100644 index 6afaba2..0000000 --- a/docs/qwen36-port/oracle-crosscheck.md +++ /dev/null @@ -1,313 +0,0 @@ -# Qwen3.6 oracle cross-check against the pinned llama.cpp graph - -Run 2026-10-11 on this branch (`qwen36-oracle`), CPU only, F32 synthetic fixtures, against `third_party/llama.cpp` at 3cf0325. -`ref/qwen36.py` (the numpy oracle) and the submodule's own graph agree on **every named tensor of every case**: 2,155 comparisons over 116 seam -families, worst absolute error **1.1e-4** (on a tensor whose values reach 3.8), the router's integer outputs identical. The printed stats of -`llama-eval-callback` agree on all 209 named nodes it prints. A reading that is wrong in any of the 8 places a port could plausibly get wrong -fails the comparison at the layer that makes it. Dequantization of the real file's types is bit-identical to ggml's (below). - -## Reproduce - -One command builds the submodule's `libllama` and `llama-eval-callback` (CPU, outside the repo), builds the dumper, writes the fixtures, runs -every case and exits 1 on any failed seam. About 4 seconds once built; the first build takes a few minutes. - -``` -export STRATA_GGUF_PY=$PWD/third_party/llama.cpp/gguf-py # optional: tools/_paths.py finds it there anyway -tools/qwen36_crosscheck.sh /path/to/scratch [REAL-MTP.gguf] # 2nd argument: a real qwen35moe file, for the --like-real case -python3 -I tools/test_qwen36_oracle.py # 21 invariant tests, no llama.cpp build needed -``` - -The same steps by hand, for one case (`$B` is the build directory, `$W` a scratch directory): - -``` -cmake -S third_party/llama.cpp -B $B -DCMAKE_BUILD_TYPE=Release -DGGML_METAL=OFF -DGGML_BLAS=OFF \ - -DLLAMA_CURL=OFF -DLLAMA_BUILD_TESTS=OFF -DLLAMA_BUILD_SERVER=OFF -cmake --build $B --target llama-eval-callback -j8 -c++ -std=c++17 -O1 tools/qwen36_dump_llama.cpp -o $B/qwen36-dump -Ithird_party/llama.cpp/include \ - -Ithird_party/llama.cpp/ggml/include -L$B/bin -lllama -lggml -lggml-base -Wl,-rpath,$B/bin - -python3 tools/qwen36_synth_gguf.py $W/base.gguf # add --like-real REAL.gguf / --fused-gate-up / --fused-qkv / --no-nextn -T=104,101,108,108,111,32,119,111,114,108,100 # "hello world": the fixture's vocabulary is the 128 ASCII bytes -python3 ref/qwen36.py $W/base.gguf --tokens $T --dump $W/o --mtp # oracle dumps (+ $W/o_mtp) -$B/qwen36-dump $W/base.gguf $W/d $T 0 mtp # llama.cpp's graph, every named tensor in full (+ $W/d_mtp) -python3 tools/qwen36_compare_dumps.py $W/o $W/d # per-seam max |difference|; exit 1 on a failure - -$B/bin/llama-eval-callback -m $W/base.gguf -p "hello world" -ctk f32 -ctv f32 -fa off -c 64 -t 1 -ngl 0 > $W/eval.txt 2>&1 -python3 tools/qwen36_check_eval_callback.py $W/o $W/eval.txt --require-tail -``` - -`-ctk f32 -ctv f32 -fa off` matter: the default F16 KV cache would put half-precision rounding into attention, and `qwen36-dump` sets the same. -Both tools use one thread, so the only differences left are float32 summation order. - -## Cases (all in `tools/qwen36_crosscheck.sh`) - -| case | fixture | tokens | what it adds | -| --- | --- | --- | --- | -| `base_11` | default, seed 0 | 11 ("hello world") | the baseline; also the nextn block | -| `base_40` | default | 40 | longer GDN history, attention over 40 keys | -| `base_ar` | default | 40, one token per decode call | llama.cpp's autoregressive GDN path: state and KV carried through 40 calls; only the last call is dumped | -| `base_c7` | default | 40, chunks of 7 | state carried across 5 calls of 7, then 5 | -| `seed7` | seed 7 | 11 | different weights, so a coincidence in seed 0 cannot hide a bug; nextn | -| `fused_gu` | `--fused-gate-up --seed 3` | 11 | `ffn_gate_up_exps` (gate rows then up rows) for trunk and nextn; nextn | -| `fused_qkv` | `--fused-qkv --no-nextn --seed 4` | 11 | `attn_qkv` in the attention layer (Q, K, V rows in that order) | -| `gqa4_2` | `--heads 4,2 --seed 11` | 40 | **non-degenerate GQA**: 4 query heads over 2 KV heads, so `kv = h // (n_head/n_head_kv)` is tested (every other fixture has one KV head, where any mapping passes); nextn | -| `stray_scl` | `--expert-weights-scale 2.5 --seed 5` | 11 | the key is in the file; llama.cpp ignores it, so must the oracle; nextn | -| `like_real` | `--like-real ` | 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-` 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-.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`). diff --git a/docs/qwen36-port/pascal-build.md b/docs/qwen36-port/pascal-build.md deleted file mode 100644 index 60ec898..0000000 --- a/docs/qwen36-port/pascal-build.md +++ /dev/null @@ -1,198 +0,0 @@ -# The Pascal (sm_61) build of the engine on the GTX 1080 Ti - -Phase 2 step 2, the one item that needed the GPU (2026-10-11, branch `qwen36-step2`, VM 211: GTX 1080 Ti sm_61, -8 vCPU of a Ryzen 7 1700, 12 GiB, CUDA 12.4, Debian's gcc 14.2 as the default compiler and gcc-13 / g++-13 as the -host compiler for nvcc). The configure line is the one in `step2-notes.md` section 4. - -## 1. Where the tree uses what Pascal lacks (read before the build) - -Pascal GP102 is compute capability 6.1: `__dp4a` is native; no tensor cores (`mma.sync`, `ldmatrix`, tf32), no -`cp.async` (sm_80), no `__nanosleep` (sm_70), no thread-block clusters (sm_90), no `__match_any_sync` (sm_70), -no `__reduce_*_sync` (sm_80), fp16 arithmetic at 1/64 rate. The tree was searched for every one of those before -the build (`grep -rl` over `src/` and `include/`, `.cu` / `.cuh` / `.hpp` / `.cpp`): - -| Feature | Files | Guard already in the file | -| --- | --- | --- | -| `mma.sync` f16 (m16n8k16 sm_80, m16n8k8 sm_75), `cp.async` | `src/kernels/cuda/qsa_prompt_attn.cu` | `STRATA_PA_SM80` (`__CUDA_ARCH__ >= 800`); `mma16816` is `__trap()` below sm_75 and `qsa_prompt_attn_batch` refuses `cc < 70` at run time, prefill takes `qsa_decode_attn_batch` instead. The Volta m8n8k4 kernel is under `STRATA_EXPERIMENTAL_SM60 && 700 <= arch < 750`, so it is not compiled for sm_61 | -| `mma.sync` tf32, `ldmatrix` | `src/kernels/cuda/native_qsa_score.cu` | `__CUDA_ARCH__ >= 800` around `load_a` / `load_b` / `mma`; `score_kernel` has an FP32-FMA path under `__CUDA_ARCH__ < 800` | -| `cvt.rna.tf32`, `mma.sync` tf32, `cp.async` | `src/kernels/cuda/qsa_select.cu` | `STRATA_SEL_SM80`; `qsa_block_scores_tc` refuses the device, the warp kernel runs | -| thread-block clusters (`cudaLaunchKernelEx`, cluster barriers) | `src/kernels/cuda/qsa_select.cu`, `src/kernels/cuda/sampler.cu` | `STRATA_SEL_CLUSTER` / `STRATA_AM_CLUSTER` (`__CUDA_ARCH__ >= 900`): a trap that `qsa_block_topk_cluster` / `sample_greedy_cluster` never launch below sm_90 | -| `__match_any_sync` | `src/kernels/cuda/qsa_select.cu` | inside the sm_80 region above (checked at the build) | -| `cp.async` | `src/kernels/cuda/fused_gr.cu` | `__CUDA_ARCH__ >= 800 && !__HIPCC__` | -| `cp.async` in the GDN recurrence | `src/prefill/kernels.cu`, `src/prefill/gdn_rec_parity.cu` | `STRATA_GDN_CP_ASYNC` (`__CUDA_ARCH__ < 800`: plain copies, and `gdn_keyhead_ok` never launches the key-head kernel there) | -| `mma.sync` / `ldmatrix` / `cp.async` in the fused prompt MoE | `src/prefill/moe_fused.cu`, `src/prefill/moe_fused_iq.cu` | `__CUDA_ARCH__ >= 800` at the two sites of each; their tests exit 77 below sm_80 | -| `__nanosleep` | `include/strata/kernels/dp4a.hpp` (`strata_spin_pause`), `src/prefill/gdn_rec_parity.cu` (`nap`) | `__CUDA_ARCH__ < 700`: the loop spins | -| `__dp4a` | `include/strata/kernels/dp4a.hpp` | `STRATA_DP4A`: the byte-loop fallback only below 6.1; sm_61 uses the instruction | -| half arithmetic (`__hfma2` and kin) | none found outside `qsa_prompt_attn.cu`'s mma path | conversions only elsewhere (the 1/64-rate risk of the design doc's section 7 item 2 is a throughput item, not a build item) | -| bf16 intrinsics (`__nv_bfloat16`, `__float2bfloat16`), fp16 atomics, `__reduce_*_sync` | none | | -| `STRATA_EXPERIMENTAL_SM60` itself | `src/core/device.cu` (the cc check), `src/kernels/cuda/qsa_decode_attn.cu` (the sm_60 decode kernel), `src/kernels/cuda/qsa_prompt_attn.cu` (the Volta kernel), `src/prefill/gemm.cu` (the FP32 GEMM default) | the flag the configure line passes | - -So upstream's experimental build already guards every sm_75+ site this tree has; the question the build answers is -whether any site was missed for sm_61 specifically (the guards were written for sm_60 and sm_70, and nobody has run -the build at 61). - -## 2. The build - -Nothing needed a guard. The tree as it stood at `8b7525e` configured and built for sm_61 unchanged: - -| Phase | Command | Result | Time (8 Zen 1 vCPU) | -| --- | --- | --- | --- | -| configure | the `cmake -S . -B build ...` line of `step2-notes.md` section 4 | `Strata: CUDA enabled, arch 61`; `NVIDIA 12.4.131 with host compiler GNU 13.3.0` | 4 s | -| `unbiased-strata` | `cmake --build build -j 8 --target unbiased-strata` | 38,221,376 B; `cuobjdump --list-elf` shows `sm_61` only | 173 s | -| every other target | `cmake --build build -j 8 -- -k` | 93 targets built, 0 errors (`logs/all.log`) | 43 s on top of the engine's libraries | - -No compile error for sm_61 at all, so the table of section 1 stands: every `mma.sync` / `ldmatrix` / tf32 / -`cp.async` / cluster / `__nanosleep` / `__match_any_sync` site is behind a `__CUDA_ARCH__` guard with a fallback or -a trap that its host code never launches below the architecture. The 102 warnings of the engine build are the same -on every target: 46 `-Wdeprecated-enum-enum-conversion` from ggml's `ggml_scale_mode | ggml_scale_flag`, nvcc's -`#611-D` partially overridden `ExpertSource::prefetch` (twice each for `FileExpertSource` and `ArenaExpertSource`), -`#177-D` the unused `MAGIC` of `strata::prefill::fused`, a handful of unused variables (`w`, `width`, `n_bid`) and -unused functions in the vendored jinja. None is architecture-specific. - -The VM has no `gguf` module for its system Python, but `tools/qwen36_synth_gguf.py` and `tools/iq_pack.py` run -there with the vendored `third_party/llama.cpp/gguf-py` on `PYTHONPATH` (numpy 2.2.4 is installed). - -## 3. The parity tests and ctest on the 1080 Ti - -`ctest --output-on-failure --timeout 900` in `build/`: 75 tests, 52 s. First run: 7 failed, 2 skipped. Two of the -failures were the branch's own tests that had never been run (both CUDA-gated in CMake, so the Mac had no binary), -fixed on the branch; the final run (`logs/ctest-final.log`) is **69 passed, 4 failed, 2 skipped**. - -| Test | 1080 Ti | First line of the failure | Pascal-specific? | -| --- | --- | --- | --- | -| `qwen36_synth_fixtures` then `model_geometry_test` | failed, then Not Run; **pass after the fix** | `CMake Error at cmake/qwen36_synth_fixtures.cmake:11 (list): list index: 1 out of range (-1, 0)` | no: cmake 3.31 drops the empty element of `"toy.gguf;"` with CMP0007 unset (cmake 4 on the Mac does not). Fix: `cmake_policy(SET CMP0007 NEW)` in the script (commit `cd2a73c`). `model_geometry_test --real` also passes on the VM against both real files | -| `expert_layout_test` | 3 checks failed; **all pass after the fix** | `qwen36-q4_k_xl.txt: per-layer formats and blobs (... total 19636158464 B) FAIL` and twice `at Flash-Next's 2560 x 640 refused by its numbers: native experts: expert geometry is not whole blocks FAIL` | no: the test's Q4 total constant was 524,288 B above the pack's own header (19,635,634,176 B), and n_ff 640 is not whole 256-value blocks for Q4_K / IQ2_S rows, so `native_fmt` refuses before the blob message the test looked for (commit `5798a46`) | -| `kv_hybrid_parity` | **FAIL** at `[5/5]` (steps 1 to 4 pass, max error 7.8e-08 / 4.4e-03 vs true fp32) | `[5/5] qsa_prompt_attn mode 3: FAIL (refused the hybrid pools)` | **yes**: `qsa_prompt_attn_batch` returns false for `cc < 70` (`qsa_prompt_attn.cu:1433`), by design (the prompt path takes the decode kernel on Pascal, design doc section 7 item 3). The test counts a refusal as PASS on HIP and FAIL on CUDA; it needs the same "refused below sm_70: the old kernel runs" branch. Step 3 item, with the dense attention work | -| `platform_memory_test` | FAIL | `lock_resident: ok=0 locked=0 MiB (mlock failed (raise ulimit -l))` | no: the VM's `ulimit -l` hard limit is 8,192 KiB; every `file_cache_keeps` case before it passes | -| `ple_parity` | FAIL | `ple_parity: required PLE table is missing or incompatible: ../../Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf (cannot open ...)` | no: the test hardcodes a Flash-Next shard path relative to the build directory; the VM has no Flash-Next file | -| `expert_multi_test` | FAIL | `strata: this CPU cannot run the expert kernel: missing AVX512F AVX512BW AVX512VL AVX512-VNNI AVX512-VBMI.` | no: the canonical Q2_0 CPU expert kernel needs AVX-512; the Ryzen 7 1700 has AVX2 only (`STRATA_PORTABLE=ON`). Qwen3.6 rides the native pack path, which does not use this kernel | -| `prefill_fused_moe_test`, `prefill_fused_iq_test` | Skipped (exit 77) | | expected: the fused prompt MoE needs sm_80 (`CMakeLists.txt`, SKIP_RETURN_CODE 77) | - -**`expert_multi_test` and AVX-512, on both VMs.** VM 211's Ryzen 7 1700 (Zen 1) and VM 221's i9-9900K (Coffee Lake) -both lack AVX-512, so `expert_multi_test` refuses on both with `this CPU cannot run the expert kernel`. The kernel it -tests is the canonical Q2_0 pack's CPU expert kernel (`src/kernels/cpu/expert.cpp`, `s2_expert_vnni_q`: AVX-512 VNNI -and VBMI, with a scalar fallback for tests only), which bakes Flash-Next's 2560 x 640. The engine calls -`cpu_require_expert_support()` only when the pack is NOT native (`generate.cpp`, "the canonical Q2_0 pack's CPU -kernels are AVX-512 only; a native pack runs on AVX2 CPUs as well"); for a native pack it logs instead that the -expert kernels run on AVX-2 (or ggml-cpu `vec_dot` without AVX2 / with `STRATA_NO_IQ256`). What that means for -step 5's RAM tier: the RAM tier (`FileExpertSource`'s pinned "cache complement", filled by profile rank) is read in -two ways, both from the same bytes. The CPU lane computes experts from it: `ExpertPool`'s native modes 5 and 6 -(`src/kernels/cpu/pool.cpp`, `native_gu_rows` / `native_down_rows`, the AVX-2 i-quant kernels or ggml-cpu's -`vec_dot`) take the blob pointer the source hands them, which is the complement's copy when the expert is held there -and the mapped GGUF otherwise. And the VRAM staging path copies from it: `FileExpertSource::copy_blob` memcpys the -complement's blob into the stage buffer bound for a VRAM slot (`prefetch` skips experts the complement holds; the -`RAM-copy reads` counter of STATS). So the RAM tier is both a compute tier (the CPU lane, on AVX-2 for Qwen3.6 -on these hosts) and the source of VRAM refills; neither path touches the AVX-512 kernel, and the engine's own -start-up refusal on these CPUs applies to the canonical pack only. - -Everything else passed, including every kernel parity on the card: `iq_parity`, `iq_multi_parity`, `mmvq_multi_parity`, -`s2_gemv_*`, `s_gemv_*`, `dequant_s2_parity`, `gdn_parity`, `gdn_rec_parity`, `gr_parity`, `qsa_parity`, -`qsa_topk_parity`, `qsa_topk_active_parity`, `decode_cluster_parity`, `sampler_parity` (all three), `rope_parity`, -`quantize_act_parity`, `route_window_parity`, `router_top10_parity`, `router_dot_parity` (and `_avx`), -`elementwise_parity`, `bf16_gemv_parity`, `gemm_bf16_parity`, `kv_q4_parity`, `kv_q8_parity`, `kv_stream_parity`, -`cvec_parity`, `native_grouped_parity`, `shared_expert_parity`, `s2_expert_grouped_parity`, the nine -`native_expert_parity_*` cases (including `refuses_q6_K`), `cuda_device_selftest`, `ple_reader_selftest`, the -expert cache / source / profile tests, `vram_plan_test`, `gguf_*`. So on the 1080 Ti the numerics of every kernel -that has a parity test agree with their references; the one Pascal-specific result is a refusal, not a wrong number. - -## 4. The pack and the gate - -The pack is the layout half (`tools/iq_pack.py --layout-only`): one `native_experts.txt`, made on the Mac in 0.35 s -and copied to `/home/rk/packs/qwen36-iq3/` (2,669 B). The Q4_K_XL layout was made on the VM itself -(`PYTHONPATH=third_party/llama.cpp/gguf-py`, 0.6 s, 2,727 B, `/home/rk/packs/qwen36-q4/`), byte-identical in its -layer lines to `tests/data/native_experts/qwen36-q4_k_xl.txt`. - -**The first run did not reach the gate.** With the tree at `8b7525e` both files printed the geometry block and then -exit 1 in 0.13 s from the expert format whitelist that `generate.cpp` ran right after the layout load: - - strata generate: layer 0's experts are IQ2_S/IQ3_XXS (ggml types 22/18), which this engine has no GPU kernels for - -(`Q4_K/Q5_K (ggml types 12/13)` for the Q4 file). `native_expert_supported()`'s *down* types (`STRATA_D_FMTS` in -`src/kernels/cuda/iq_kernels.cu`) are IQ4_NL, IQ4_XS, Q5_0, Q5_1, Q8_0 and type 42; Q4_K / Q5_K / IQ2_S / IQ3_XXS -are gate/up types only and Q6_K is in neither (`native_expert_parity_refuses_q6_K` pins that). The IQ3_XXS file's -down projections are IQ3_XXS on 37 layers (IQ4_XS on 34/38/39, which the kernels have); the Q4_K_XL's are Q5_K on -37 and Q6_K on 34/38/39. The study's section 3.7 checked the layout against these types, not the kernels. The down -kernels are step 3's `qwen36-step3-experts` branch; commit `30e3add` moved the gate ahead of the whitelist, so a -Qwen3.6 file now prints the plan and the missing pairs. The whitelist still runs, unchanged, for every other file. - -**The gate as it stands** (`30e3add` and after, `logs/gate-IQ3_XXS-cap0.log`): exit 2 after 0.36 s, the IQ3_XXS -file with its layout pack, the notes' command: - - strata generate: model geometry (/home/rk/models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf, from the file's metadata): - arch qwen35moe - n_embd 2048 - n_layers 40 - nextn_layers 0 - qsa_interval 4 - n_qsa_layers 10 - n_gdn_layers 30 - ssm_state_size 128 - ssm_k_heads 16 - ssm_v_heads 32 - ssm_d_conv 4 - ssm_conv_channels 8192 - ssm_value_dim 4096 - n_head 16 - n_head_kv 2 - head_dim 256 - n_rot 64 - rope_sections 11,11,10,0 - rope_base 10000000.000000 - rms_eps 0.000001 - idx_q_heads 0 - idx_key_dim 0 - hc 1 - hc_lr 0 - n_expert 256 - n_expert_used 8 - n_ff 512 - n_ff_shexp 512 - has_ple no - has_indexer no - strata generate: VRAM plan for /home/rk/models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf on this card (kv q4_0, prefill borrows cache slots): - VRAM budget 11001 MiB - fixed set at 262144 tokens: 4019 MiB = weights 1596 + drafter 520 + KV 1440 + session 162 + CUDA context 0 + reserve 300 (prefill borrows cache slots) - expert slots in VRAM: 6748 of 10240 (65%) at 6981 MiB, 1084825 B mean blob - expert copies in RAM: 3492 (3612 MiB of 9409 MiB available minus 4096 headroom) - experts mapped from the model file: 0 - strata generate: step 3 also needs GPU expert kernels for gate-up/down IQ2_S/IQ3_XXS (37 layers: 0, 1, 2, 3, 4, 5, 6, 7, ... (37 layers)) - strata generate: this is a Qwen3.6-35B-A3B file (qwen35moe, 40 layers, 2048 wide, 256 experts x top-8): Phase 2 step 2 (geometry, metadata, the VRAM plan above) is done, but the engine cannot run it yet. Not done: step 3 (kernels and the block: the GDN gate SiLU(z) instead of sigmoid(z), dense attention at 16 heads with no indexer, the block and the verify window without hyper-connections, prefill at this geometry), step 4 (the native pack and the MTP drafter from blk.40, the expert profile at 40 x 256). See docs/PLAN-qwen36-35b-a3b.md section 5 and docs/qwen36-port/step2-notes.md - -The Q4_K_XL file (`logs/gate-Q4_K_XL-cap0.log`, exit 2): the same geometry block with `nextn_layers 1`, then - - strata generate: VRAM plan for /home/rk/models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf on this card (kv q4_0, prefill borrows cache slots): - VRAM budget 11001 MiB - fixed set at 262144 tokens: 4461 MiB = weights 2038 + drafter 520 + KV 1440 + session 162 + CUDA context 0 + reserve 300 (prefill borrows cache slots) - expert slots in VRAM: 3575 of 10240 (34%) at 6539 MiB, 1917542 B mean blob - expert copies in RAM: 2929 (5356 MiB of 9453 MiB available minus 4096 headroom) - experts mapped from the model file: 3736 (read from disk on a miss) - strata generate: step 3 also needs GPU expert kernels for gate-up/down Q4_K/Q5_K (37 layers: 0, 1, 2, 3, 4, 5, 6, 7, ... (37 layers)) - strata generate: step 3 also needs GPU expert kernels for gate-up/down Q4_K/Q6_K (2 layers: 34, 38) - strata generate: step 3 also needs GPU expert kernels for gate-up/down Q5_K/Q6_K (1 layers: 39) - strata generate: this is a Qwen3.6-35B-A3B file (qwen35moe, ...): [the same gate message] - -(CUDA reports the card as 11,165 MiB total with 11,001 free at start, 164 MiB in use by the display and the -driver; `nvidia-smi`'s 11,264 is the marketing figure.) - -**`--vram-cap` on the 1080 Ti** (`logs/gate-*-cap*.log`, after commit `2b4fcf1`): the cap line and the plan at -the study's caps that fit on an 11 GB card. "Free to this engine" is cap minus the 164 MiB in use before the -start, within the driver's 1 MiB rounding of the blocker, at every cap; the start would refuse if it were more than -64 MiB off. - -| `--vram-cap` (MiB) | held back | free to this engine | expected (cap - 164) | -| ---: | ---: | ---: | ---: | -| 5722 (6 GB) | 5443 | 5557 | 5557 | -| 7629 (8 GB) | 3536 | 7463 | 7464 | -| 8192 | 2973 | 8027 | 8027 | -| 10490 (11 GB decimal) | 675 | 10325 | 10325 | -| 12288 | "is not below this card's 11165 MiB: no cap" | 11001 | | - -The plan's tiers at each cap are in `step2-notes.md` section 5, next to the study's table 4.3. -## 5. The Makefile's Pascal switch - -`make build CUDA_ARCHS=61 BUILD_DIR=build-make` on the VM, with no compiler override at all (`logs/make-plain.log`): -the llama.cpp patch applied (`git apply` works outside a repository, so the rsynced tree without `.git` is fine and -the patch now sits in the VM copy of the submodule), CMake chose Debian's g++ 14.2 for the host code and nvcc 12.4 -took g++-13 as its host compiler by itself (`NVIDIA 12.4.131 with host compiler GNU 13.3.0`), `Strata: CUDA enabled, -arch 61` with `STRATA_EXPERIMENTAL_SM60=ON` from the Makefile's switch, 0 errors, `built: build-make/unbiased-strata` -(38,627,048 B) in 181 s from configure to link; `cuobjdump --list-elf build-make/unbiased-strata` shows `sm_61` only. diff --git a/docs/qwen36-port/step2-notes.md b/docs/qwen36-port/step2-notes.md deleted file mode 100644 index c3a0e31..0000000 --- a/docs/qwen36-port/step2-notes.md +++ /dev/null @@ -1,166 +0,0 @@ -# Qwen3.6 port, Phase 2 step 2: geometry, metadata, the VRAM planner - -Working notes, kept as the step was done (2026-10-11, branch `qwen36-step2`, branched from `qwen36-oracle`). -The design is `docs/QWEN36-35B-A3B.md` sections 3.7 to 3.9 and 4.2; the plan is `docs/PLAN-qwen36-35b-a3b.md` -section 5 step 2. Every item below says what was decided, where it lives, and how it is checked. - -## 1. What the engine does with a Qwen3.6 file at the end of this step - -Started with `--native Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf --pack ` 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 --out --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. diff --git a/docs/qwen36-port/step3-attn.md b/docs/qwen36-port/step3-attn.md deleted file mode 100644 index 379641c..0000000 --- a/docs/qwen36-port/step3-attn.md +++ /dev/null @@ -1,214 +0,0 @@ -# Qwen3.6 port, Phase 2 step 3: dense attention replacing QSA - -Working notes of the `attn` area (branch `qwen36-step3-attn`, from `qwen36-step2` at 8b7525e, 2026-10-11). The -design is `docs/QWEN36-35B-A3B.md` section 3.3 (six items) and section 6 step 3, second bullet. Every item says -what was decided, where it lives, how it is checked, and the numbers from both cards. - -## 1. What changed, item by item - -| 3.3 item | Decision | Where | -| --- | --- | --- | -| 1, the producer | A **null `ids` is the identity selection**: the decode and prompt kernels read cell `j = j` for `j < step[kStepWidth]`. The engine's dense paths pass `nullptr` and carve no ids buffer (prefill at 2,048 queries x 262,144 cells would carry 2 GiB of ids). The explicit form `qsa_identity_ids(ids, steps, n_q, cap, stream)` exists for a caller that must hand a buffer on (a dump, the streaming resolver) and for the test, which holds the two forms bit for bit equal | `src/kernels/cuda/qsa_decode_attn.cu`, `qsa_prompt_attn.cu`; `qsa_layer` and the verify window's attention step pass null | -| 1, the indexer skipped | `g.has_indexer()` (step 2: false for `qwen35moe`) gates the raw key projection, the append, the indexer query, the block scores and the top-k in `qsa_layer` and in `Verifier`'s attention step; the four `indexer.*` tensors are required only with an indexer | `src/core/layer.cpp` (c4793cd), `src/core/verify.cpp` (bc2fb91), each one commit | -| 2, G = 12 | `G` is a template parameter of every attention kernel, instantiated at **2, 8, 12**; `qsa_attn_group(s, why, n)` picks it from the geometry and returns 0 with a message naming the heads for any other ratio; `qsa_attn_group_check(s, G, why, n)` refuses a G that does not divide the geometry (G = 12 on 16 / 2 is a message, never a mis-indexed run); `qsa_prompt_attn_batch` returns false for an unknown ratio and the decode kernel then refuses by name | `qsa_decode_attn.cu`, `qsa_prompt_attn.cu`, `include/strata/kernels/qsa_decode_attn.hpp` | -| 3, the selection width and the capacity | **One builder**, `strata::core::qsa_shapes(g)` (`include/strata/core/qsa_shapes.hpp`, header-only), used by `layer.cpp`, `verify.cpp`, `mtp.cpp`, `session.cpp` and `prefill.cpp` (the last two as `[shared]` commits): for a geometry without an indexer it zeroes `idx_n_head`, `idx_dim` **and** `idx_top_k`. The dense signal is `qsa_dense(s)` = the three zero together; `qsa_shapes_valid(s, why, n)` (what every kernel's guard checks, non-exiting for the test) refuses a half-set shape - two zeros with the 2,048 budget kept, which the first hand-written builders in verify and mtp made and the kernels' guard then exited on at the first append. `qsa_selection_width(n_kv, s)` returns `n_kv` when dense, so `qsa_step_fill` writes `width = n_kv`; **`qsa_selection_cap(max_cells, s)`** is the capacity every buffer is sized by: `max_cells` when dense, `qsa_selection_width(kTopkMaxCells, s)` = 2,051 otherwise. The indexer entry points refuse a dense shape by name (`validate_indexer`). Not converted: `generate.cpp:7469` (a snapshot-hash shape that sets only `n_head_kv`/`head_dim`/`idx_dim`; not edited on this branch) | `qsa_shapes.hpp`, `qsa.hpp`, `qsa.cu`, `layer.cpp`, `verify.cpp`, `mtp.cpp`, `session.cpp`, `prefill.cpp` | -| 4, the state without the indexer | `kv_plan` gives a dense state `pooled_rows = 2` (the drafter's ring) and `idx_dim` is 0, so the three indexer regions are 0 bytes (section 3). The buffers carve no `cell_scores`, `ids`, `k_scratch`, `v_scratch` for the dense model: at 262,144 cells those are 1 + 1 + 512 + 512 MiB (the gather scratch was `cap x n_head_kv x 256 x 2 B` each) | `layer.cpp`: `kv_plan`, `qsa_state_bytes/init`, `qsa_buffers_bytes/init` | -| 5, the split-K scratch | The grid is capped at **128 blocks per KV head**; a block walks its span of the selection in 64-cell sub-chunks with the running (m, l, acc) rescale. The span is computed **on the device from the token's width**, not from the capacity, so a selection up to 8,192 cells still spreads one block per 64 cells (decode at a short depth keeps its parallelism). **The bound applies to dense shapes only**: a sparse (Flash-Next) shape keeps `ceil(cap / 64)` blocks at any capacity, because the MTP drafter's ring runs this kernel at its `--mtp-window` (32,768 by default: 512 blocks, `mtp.cpp:249`) and keeps its previous grid, scratch (12 MiB at 24 heads) and summation order. On sm_75+ one looped kernel serves every capacity (the 4090 measures it equal to the old one at 2,051 cells). Below sm_75 (`STRATA_EXPERIMENTAL_SM60`, PR #540's kernel) the looped form costs 16-28 registers on sm_61 (80-92 at G 12 against 63-64; a register cap spilled and cost more), so every sparse shape, and a dense capacity under 8,192 cells, runs `attn_chunk_kernel_pre75_single`, PR #540's body as it was: every Flash-Next state (the QSA layers at cap 2,051, the drafter's ring at its window) is the old kernel to the instruction, and the looped `attn_chunk_kernel_pre75` runs only for the dense model's long-context states. `qsa_decode_attn_scratch_floats(cap, s) = min(ceil(cap / 64), 128) x n_head x 258 + 64`: **528,448 floats = 2.02 MiB per query row at 16 heads** for any cap >= 8,192 (was 64.5 MiB at 262,144); 16 MiB for the 8-row verify window, 64 MiB for prefill at `attn_batch` 32 | `qsa_decode_attn.cu` (`kMaxChunks`, `chunks_for`, both chunk kernels, `attn_merge_kernel`) | -| 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. diff --git a/docs/qwen36-port/step3-block.md b/docs/qwen36-port/step3-block.md deleted file mode 100644 index 46d91f9..0000000 --- a/docs/qwen36-port/step3-block.md +++ /dev/null @@ -1,202 +0,0 @@ -# Qwen3.6 port, Phase 2 step 3: the block without hyper-connections - -Working notes, kept as the step was done (2026-10-11, branch `qwen36-step3-block`, from `qwen36-step2` at 8b7525e). -The design is `docs/QWEN36-35B-A3B.md` section 3.5 and section 6 (step 3, fourth bullet); the plan is -`docs/PLAN-qwen36-35b-a3b.md` section 5 step 3. Every item says what was decided, where it lives, how it is -checked, and the numbers from both cards. - -## 1. What changed, in one paragraph - -`ModelGeometry::hc == 1` (set by the `qwen35moe` architecture string in step 2) now selects a second block path: -llama.cpp's plain pre-norm residual block, in the single-token functions (`block_layer_pre`, `block_layer_post`, -`lm_head_mix`) and in the verify window (`Verifier::record_window`'s `pre`, `post` and head), through two row-count -helpers that the single-token path calls with one row and the window with its T rows. The hyper-connection kernels -are never entered for this model: the GR read on one stream is not a plain norm (its bottleneck gates the normed -stream with a sigmoid and its norm weight is stored as `1 + w`), which the harness shows as a negative case. The -Flash-Next path (`hc = 4`) is untouched: every `hc == 1` test is a branch in front of the existing code, no GR -call site moved, and the no-geometry `layer_verify_compatible` keeps its Flash-Next meaning. - - x = rms_norm(R) * attn_norm -> mixer (GDN | attention) -> R += out - x = rms_norm(R) * post_attention_norm -> MoE (routed top-k, normalised, + shared expert) -> R += out - head: rms_norm(R) * output_norm -> output.weight - -## 2. Decisions - -| Decision | Where | Why | -| --- | --- | --- | -| Two helpers, `plain_norm_rows(R, w, mixed, n_embd, eps, n_tok, stream)` and `plain_residual_rows(R, block_out, n_embd, n_tok, stream)`, take a ROW COUNT | `include/strata/core/layer.hpp` ("the plain block"), `src/core/layer.cpp` | the single-token path (1 row) and the verify window (T rows) call the same kernels, so the window's row arithmetic equals the single-token path by construction; the harness asserts it bitwise | -| The norm is `native_qsa_rms_norm_weighted` (one block per row, fixed reduction order, `rsqrtf`, `(scale * x) * gamma`); the add is `add_inplace` | `layer.cpp` | the engine's pinned-arithmetic norm kernel, already used on q/k and in the drafter; ggml's `rms_norm` then `mul` in that order | -| No pending write at hc = 1: `R += out` is applied where the reference adds it (stage 2 and `post`), never folded into the next read | `layer.cpp` (`plain_block_pre` / `plain_block_post`), `verify.cpp` | the fold exists to fuse the GR write into the GR read; with no GR there is nothing to fuse, and an in-place add keeps `R` materialised for the control vector, the hand-off and the head | -| The stages and the `half` / `stage_prefix` selection are the GR path's (0 read, 1 mixer, 2 write, 3 read, 4 route) | `plain_block_pre` | `session_replay_stages`, the per-stage timing and the measurement splits apply unchanged; the harness drives stage 0 and half 2 separately | -| The norm weights are read as `const float*` after a form check (F32, `n_embd` elements) | `plain_norm_weight` in `layer.cpp`, `plain_w` in `verify.cpp`, `lm_head_mix` | Qwen3.6's norms are F32 in the file and the pack keeps them F32; a BF16 row read as f32 walks 2x the tensor inside the arena and yields a finite wrong norm (the `layout.cpp` failure) | -| `check_one` skips the `hc_*` rows at hc = 1 and requires `attn_norm` / `post_attention_norm` (F32, `n_embd`) instead; at hc > 1 the two plain names are skipped | `src/core/layout.cpp` | row 22 of the inventory; the indexer rows are the attention branch's | -| `layer_verify_compatible(const ModelGeometry&, std::string&)`: at hc = 1 the fused GR read is not required; without an indexer the block selection and the native indexer are not required | `layer.cpp`, `layer.hpp` | the window's compatibility check named kernels this model has no use for; the no-argument form stays Flash-Next's | -| `verify_geometry_supported(g, k, why)` replaces the window's `ss.k == 10` refusal: `k == g.n_expert_used` (8 from the file), the fused GR shape only at hc > 1, state 128 / conv 4 | `include/strata/core/verify.hpp`, `verify.cpp` | row 142; a free function so the negative case (top-10 on an 8-expert file) is a unit test and the message names both numbers | -| The window's head at hc = 1: `output_norm` over the T rows in one launch when the native head is loaded; the canonical head goes through `lm_head`, which branches the same way | `verify.cpp` (`record_window`, the head block) | the per-row arithmetic is the single-token `lm_head_mix`'s | -| A PLE run with hc = 1 is refused (`block_layer_pre`, `record_window`) | `layer.cpp`, `verify.cpp` | the model has no PLE (`has_ple = false`); a wired one would be a different model | -| `session_zero`'s first token needs no change | `src/core/session.cpp:141-148` | the loop is over `g.hc` (row 26): one copy at hc = 1 | -| `broadcast_streams` / `add_streams_broadcast` need no change | `src/kernels/cuda/verify_kernels.cu:256-291` | runtime `hc` (row 140): the identity copy at hc = 1 | - -## 3. The harness: `tests/cuda/qwen36_block_test.cpp` - -Maya's layer composition shape on the synthetic fixture (`tools/qwen36_synth_gguf.py`: hidden 64, layers 0-2 GDN, -layer 3 attention, 8 experts top-2, F32 everywhere) against the oracle's dumps of 8 tokens -(`cmake/qwen36_block_fixtures.cmake` runs `ref/qwen36.py --dump`; the fixture test `qwen36_block_fixtures` depends on -step 2's `qwen36_synth_fixtures`). CTest: `qwen36_block_test` (exit 77: no CUDA device or no numpy). - -**Through the engine's own functions.** The test writes a pack (index.txt + dense.bin) holding, per layer, the two -norms (F32, index kind 2), the router `ffn_gate_inp` (BF16, kind 4, the engine's contract) and the shared expert's -scalar gate, plus `output_norm`; `WeightTable::load` reads it like any pack. Then, per layer and token, with the -mixer's output and the experts' outputs TEACHER-FORCED from the dumps: - -| seam | engine call | tolerance (relative L2) | -| --- | --- | --- | -| `attn_norm-N` | `block_layer_pre(..., stage_prefix = 1)` on `R = l_out-(N-1)` (`model.input_embed` at N = 0) | 1e-6 | -| `attn_residual-N` | `plain_residual_rows` with `block_out = linear_attn_out-N` (GDN) or `attn_output-N` (attention) | 1e-6 | -| `attn_post_norm-N` | `block_layer_pre(..., half = 2)` on `R = attn_residual-N` (shared expert off: its weights are not in the pack) | 1e-6 | -| `ffn_moe_topk-N`, `ffn_moe_weights_norm-N` | the same call's router (`moe_route`: BF16 weight, F32 activations, `router_top10` at 8 / 2) | picks identical; weights 1e-2 reported | -| `ffn_out-N`, `l_out-N` | `block_layer_post` with `parts = ffn_moe_down-N`, `weights = ffn_moe_weights_norm-N`, `shared = ffn_shexp_gated-N` | 1e-6 | -| `result_norm` | `lm_head_mix` on `R = l_out-3[last]` | 1e-6 | -| `result_output` | the engine's `result_norm` through a host F32 projection of `output.weight` | 1e-5 | - -**The window.** `plain_norm_rows` and `plain_residual_rows` over the 8 rows against the one-row calls per row -(bitwise, `memcmp`), `native_moe_combine_multi` against `native_moe_combine` per row (bitwise), and the 8-token -sequence carried through the four layers from the embeddings (`R` is never reloaded from the dumps) against -`attn_norm-N`, `attn_residual-N`, `attn_post_norm-N`, `ffn_out-N`, `l_out-N` at every position, then `h_nextn` -(every row) and `result_norm` (row 7), all at 1e-6. - -**Negative cases** (each must differ from the oracle by more than 5 % relative L1): the GR read at hc = 1 with -identity bottleneck weights (`GrShapes{64, 1, 64}`, `w_down = w_up = I`, `w_norm = attn_norm`) against -`attn_norm-0`; the post-attention norm skipped (`attn_residual-0` as the MoE input) and unweighted; top-10 on the -8-expert file refused by `verify_geometry_supported` with both numbers in the message; a layer whose `attn_norm` -is not in the pack refused by name; `layer_verify_compatible` at hc = 1 passing without the fused GR read while -the Flash-Next geometry still demands it. - -**The mixers are reported, not asserted.** The fixture's projections are F32 and the engine has no F32 projection -kernel (the mixers take quantized planes or native GGUF types), so `block_layer_pre(..., stage_prefix = 2)` is -attempted and its own error printed (`blk.N.attn_qkv.weight is missing`; the attention layer's RoPE table of 0 rows). -The mixer seams (`conv_output_silu-N`, `new_state-N`, `final_output-N`, `linear_attn_out-N`; `kq_soft_max-3`, -`kqv-3`, `attn_gated-3`, `attn_output-3`) wait on the GDN and attention branches and on step 4's pack, which is -where the engine first runs a Qwen3.6 mixer end to end. - -**Why 1e-6 and not the policy's 5e-8.** `oracle-crosscheck.md`'s norm figure is numpy F32 against numpy F32 on a -forced input; the CUDA norm uses `rsqrtf` (2 ulp, 2.4e-7) under `--use_fast_math`, so one CUDA ulp is above that -figure. The measured numbers are below. - -## 4. Build and test commands - -On VM 221 (the 4090, sm_89; the working copy is synced with the worktree's empty `third_party/llama.cpp` excluded -and the pinned submodule copied from the step-2 tree): - - rsync -a --delete --exclude .git --exclude '/build/' --exclude '/build-mac/' --exclude '/logs/' \ - --exclude '/third_party/llama.cpp/' ~/Code/UnbiasedStrata-step3-block/ rk@192.168.50.151:/models/work/qwen36-step3-block/ - /models/work/build-step3-block.sh configure # the common file's configure line, logged - /models/work/build-step3-block.sh target qwen36_block_test - /models/work/build-step3-block.sh ctest 'qwen36' - /models/work/build-step3-block.sh all # everything else still builds (the gate binary links the engine) - -On VM 211 (the 1080 Ti, sm_61) under the `/home/rk/VM-BUSY` lock, the same with `-DSTRATA_EXPERIMENTAL_SM60=ON --DCMAKE_CUDA_ARCHITECTURES=61` and the working copy in `/home/rk/qwen36-step3-block/`. - -## 5. Results - -### VM 221, the RTX 4090 (sm_89), 2026-10-11 - -`./build/qwen36_block_test build/qwen36_synth build/qwen36_block/o8` (the fixtures written by hand, below), all 30 -checks pass: - -| seam (single-token path through the engine) | measured, worst over 4 layers x 8 tokens | tolerance | -| --- | ---: | ---: | -| `attn_norm-N` (`block_layer_pre` stage 0) | 1.13e-7 | 1e-6 | -| `attn_residual-N` | 0.0 | 1e-6 | -| `attn_post_norm-N` (`block_layer_pre` half 2) | 1.23e-7 | 1e-6 | -| `ffn_moe_topk-N` (the BF16 router) | 0 of 64 slots differ | identical | -| `ffn_moe_weights_norm-N` (the BF16 router) | 9.82e-3 | 1e-2, reported | -| `ffn_out-N` (`block_layer_post`) | 7.02e-8 | 1e-6 | -| `l_out-N` (`block_layer_post`) | 4.82e-8 | 1e-6 | -| `result_norm` (`lm_head_mix`) | 0.0 | 1e-6 | -| `result_output` (host projection of the engine's `result_norm`) | 1.63e-7 | 1e-5 | - -| the window (8 rows) | measured | tolerance | -| --- | ---: | ---: | -| `plain_norm_rows`, `plain_residual_rows`, `native_moe_combine_multi` against the one-row calls | bitwise | bitwise | -| `attn_norm-N` / `attn_residual-N` / `attn_post_norm-N` / `ffn_out-N` | 6.98e-8 / 2.61e-8 / 7.78e-8 / 2.52e-8 | 1e-6 | -| `l_out-N` per position, `R` carried from the embeddings (layers 0..3) | 1.99e-8 / 2.22e-8 / 2.65e-8 / 2.81e-8 | 1e-6 | -| `h_nextn` (all rows) / `result_norm` (row 7) | 4.75e-8 / 3.25e-8 | 1e-6 | - -| negative case | relative L1 against the oracle | required | -| --- | ---: | ---: | -| the GR read at hc = 1, identity bottleneck, against `attn_norm-0` | 0.423 | > 0.05 | -| the post-attention norm skipped | 0.276 | > 0.05 | -| the post-attention norm without its weight | 0.180 | > 0.05 | -| top-10 on the 8-expert file | refused: "the session routes top-10 but the file routes top-2 of 8 experts" | refused by name | -| the fixture's GDN state 16 | refused: "the T-token GDN kernels are built for state 128 and conv 4" | refused by name | -| `blk.4.attn_norm.weight` absent | refused by name | refused by name | - -The mixer seams, reported: layers 0-2 `blk.N.attn_qkv.weight is missing`, layer 3 `qsa_layer: position 0 is -outside the RoPE table (0 rows)` (no attention state is built for a mixer that cannot run on F32 weights). - -The 9.8e-3 on the router's renormalised weights is the BF16 contract on an F32 weight (2^-9 per element over a -64-long dot product); the picks are identical on this fixture, whose logits are spread for that purpose. The -real file's flip rate is the router branch's measurement (study 3.4). - -**Two things found on the way.** (1) `cmake/qwen36_synth_fixtures.cmake` (step 2's) fails on this cmake 3.28 -under policy CMP0007 (`list(GET)` on `"toy.gguf;"` with its empty flag element), so `ctest -R qwen36` cannot -reach `qwen36_block_test` until the step-2 branch fixes it; the fixtures were written by hand -(`python3 -I tools/qwen36_synth_gguf.py build/qwen36_synth/toy.gguf`, then the block fixture script with `-P`) -and the test run directly. (2) `read_model_geometry` leaves `n_vocab` at the Flash-Next default (248,320) on the -synthetic file; the engine takes the vocabulary from `output.weight`'s `ne1` (verify.cpp, mtp.cpp), and so does -the test, but a reader of `ModelGeometry::n_vocab` should know it is not the file's. - -### VM 211, the GTX 1080 Ti (sm_61, Pascal), 2026-10-11, under `/home/rk/VM-BUSY` - -The same tree (`/home/rk/qwen36-step3-block/`, the submodule copied from the step-2 tree), configured with -`-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61`, `cmake --build build -j 8 --target qwen36_block_test` -(the engine library and the kernels compile for sm_61), the fixtures by hand as above, then -`./build/qwen36_block_test build/qwen36_synth build/qwen36_block/o8`: all 30 checks pass with **the same numbers as -the 4090 to the printed digit** (1.13e-7, 1.23e-7, 7.02e-8, 4.82e-8, 1.63e-7, 9.82e-3; the window's 1.99e-8 .. -2.81e-8; the negatives 0.423 / 0.276 / 0.180; the router's 64 picks identical). The kernels the plain block adds -to the path are a block-per-row reduction and an elementwise add: nothing Pascal lacks. The lock was held for -the sync, the build, the run and released (about 12 minutes). - -## 6. The hunks, for the integrator (against 8b7525e) - -| file | hunks (old -> new line ranges) | what | -| --- | --- | --- | -| `include/strata/core/layer.hpp` | 479,8 -> 479,35 | `layer_verify_compatible(g, why)`, the plain-block section, `plain_norm_rows`, `plain_residual_rows` | -| `src/core/layer.cpp` | 473,17 -> 473,22 | `layer_verify_compatible` with the geometry; the no-argument form calls it with the defaults | -| | 1087,6 -> 1092,20 | `lm_head_mix`: the `hc == 1` branch (`output_norm`) in front of the GR mix | -| | 1167,7 -> 1186,115 | the two helpers, `plain_norm_weight`, `plain_block_pre`, `plain_block_post`; `block_layer_pre` dispatches on `g.hc == 1` as its first statement | -| | 1316,7 -> 1443,9 | `block_layer_post` dispatches on `g.hc == 1` as its first statement | -| `src/core/layout.cpp` ([shared]) | 2,6 -> 2,7; 81,6 -> 82,9; 96,6 -> 100,10; 108,6 -> 116,10 | ``; 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. - diff --git a/docs/qwen36-port/step3-experts.md b/docs/qwen36-port/step3-experts.md deleted file mode 100644 index 2606a81..0000000 --- a/docs/qwen36-port/step3-experts.md +++ /dev/null @@ -1,163 +0,0 @@ -# Qwen3.6 port, Phase 2 step 3, experts: the native GPU expert kernels' format coverage - -Working notes (2026-10-11, branch `qwen36-step3-experts`, from `qwen36-step2` at 8b7525e). The gap: the study's -section 3.7 called the native pack path "otherwise runtime", but `native_expert_supported()` refused every layer of -both real files because the DOWN-projection list `STRATA_D_FMTS` (`src/kernels/cuda/iq_kernels.cu`) held only the -types Flash-Next's and the Coder's packs use (IQ4_NL, IQ4_XS, Q2_0, Q5_1, Q5_0, Q8_0). Qwen3.6's files put IQ3_XXS -(37 layers) and IQ4_XS (34, 38, 39) on `ffn_down_exps` in UD-IQ3_XXS, and Q5_K (37) and Q6_K (34, 38, 39) in -UD-Q4_K_XL, whose layer 39 gate/up is Q5_K (`tests/data/native_experts/qwen36-{iq3_xxs,q4_k_xl}.txt`, step2-notes.md -section 3). The engine's refusal at `generate.cpp:2100` named the pair; it still does for anything not below. - -## 1. What changed, and why it was small - -| Decision | Where | Why | -| --- | --- | --- | -| IQ3_XXS (18) and Q5_K (13) join `STRATA_D_FMTS` | `iq_kernels.cu`, the three `STRATA_*_FMTS` lists | `native_down_kernel` and `native_down_multi_kernel` were already generic in `Fmt` (one row per warp, `row_dot` 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 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. diff --git a/docs/qwen36-port/step3-gdn.md b/docs/qwen36-port/step3-gdn.md deleted file mode 100644 index 6778fc7..0000000 --- a/docs/qwen36-port/step3-gdn.md +++ /dev/null @@ -1,173 +0,0 @@ -# Qwen3.6 port, Phase 2 step 3, area `gdn`: the GDN output gate, the router and the shared expert - -Working notes, kept as the step was done (2026-10-11, branch `qwen36-step3-gdn`, from `qwen36-step2` at 8b7525e). -The design is `docs/QWEN36-35B-A3B.md` sections 3.2 and 3.4 and step 3's first and third bullets in section 6; the -plan is `docs/PLAN-qwen36-35b-a3b.md` section 5 step 3. Every item says what was decided, where it lives, and how -it is checked, with the numbers from both cards. - -## 1. What changed - -| Decision | Where | Why | -| --- | --- | --- | -| `kernels::GdnGate { Sigmoid, Silu }` names the GDN output gate; every decode output kernel takes it as a required argument | `include/strata/kernels/gdn.hpp` | the one numerical difference between the two models (study 3.2, inventory row 39): `rms_norm(o) * ssm_norm * act(z)`, sigmoid for Flash-Next and SiLU for Qwen3.6. A required parameter, not a default, so a call site rewritten later cannot silently keep sigmoid | -| `ModelGeometry::gdn_gate()` returns SiLU for `qwen35moe`, sigmoid for `qwen4exp` | `include/strata/core/layout.hpp` (`[shared]`) | from the architecture string, like `hc` and the indexer; no key says it. No global anywhere: one process can serve both models | -| The four kernels: `gdn_out_norm` (legacy, `gdn.cu`), `fused_gdn_step_norm` (the default native decode, `fused_gdn.cu`), `native_gdn_out_norm` (pinned unfused, `native_gdn_preprocess.cu`), `gdn_step_norm_multi` (the verify window, `verify_kernels.cu`) | `src/kernels/cuda/` | SiLU is ggml's `op_silu` form `z / (1 + exp(-z))`; the sigmoid expression is untouched, so Flash-Next's arithmetic is bitwise what it was. `verify_kernels.cu` was not in the brief's list of three, but native packs decode only through the verify window (inventory row 114), so the gate had to reach it; it stays bitwise the fused kernel (checked) | -| The seven call sites pass `g.gdn_gate()`: `layer.cpp` (3), `verify.cpp` (4) | `src/core/layer.cpp`, `src/core/verify.cpp` (`[shared]`, one commit, nothing else touched) | the smallest change the block agent's files needed | -| No decode-path literal assumed 16/48 | (none) | `grep` of `src/kernels/cuda`, `src/core`, `src/program`, `include` for 48 / 6144 / 10240 / VPK finds only `ModelGeometry`'s defaults (step 2 reads them from the file), the PLE post-ops (Flash-Next only) and comments (`session.hpp:34`, `layer.hpp:10-16`, `gdn.hpp:11`). The kernels' only rule is `h_v % h_k == 0`; `fused_gdn_conv_l2` wants `channels % 128 == 0` (8192 is), `native_gdn_*` wants counts up to 65,535 (8192 is), `fused_gdn_ab` wants `n_embd % 8 == 0` (2048 is). The VPK 2 shape is run through every kernel in `gdn_parity` (16/32) and `qwen36_seam_parity` (2/4) | -| The router and the shared expert: parameterisation and tests only | `src/kernels/router_top10_parity.cpp`, `src/kernels/shared_expert_parity.cpp` | generic already (study 3.1): `router_top10` takes `n_expert <= 512, k <= 32` at runtime; the native 512 x 10 router is guarded by `n_expert == 512 && k == 10` in `layer.cpp:370` and `verify.cpp:915`, so 256/8 takes the generic kernel. No literal of 10 or 512 in the decode router path needed changing; `verify.cpp`'s `HIP_GFX906` branch already carries a 256-expert window path | -| The fixture tool grows `--gdn K,V,S`, `--experts E,K`, `--shexp-ff N`, `--quant-shexp q8_0`, `--bf16-exact` | `tools/qwen36_synth_gguf.py` (`[shared]`) | the CUDA GDN kernels are pinned to state 128 and the toy fixture has 16; the default fixture is byte-identical to before | - -## 2. The harnesses - -### `gdn_parity` (`src/kernels/gdn_parity.cpp`, `ctest -R gdn_parity`) - -Both geometries, 16/48 (VPK 3, sigmoid) and 16/32 (VPK 2, SiLU), through all four implementations; the existing -four traps (modulo versus interleaved pairing, decay order, conv direction, l2 epsilon) kept; the fifth trap is the -gate, and it is run THROUGH the kernels: each kernel with the other model's gate must differ from the reference by -more than 5%. The verify kernel is held bitwise to the fused one on the verify, commit and split-commit paths. - -Note for a later reader: the first version of this rewrite reported the native and fused kernels 7.5x off at the -32-head geometry and exact at 48. It was the harness: fixtures reset with pageable `cudaMemcpy` on a non-blocking -stream race the DMA. The stream is blocking now, and the comment at its creation says why. - -### `qwen36_seam_parity` (`src/kernels/qwen36_seam_parity.cpp`, `cmake/qwen36_oracle_dumps.cmake`) - -`ctest -R 'qwen36_oracle_dumps|qwen36_seam_parity'`. The fixture `k.gguf`: hidden 64, GDN 2 k-heads / 4 v-heads of -128 (VPK 2), conv 4, 256 experts top-8 of 32, shared expert 512 in Q8_0, the BF16-read weights BF16-exact; the oracle -run twice on the 11-token "hello world" sequence (F32, and `--act-quant q8`). The engine's kernels then hold, by -llama.cpp's `cb()` names, token by token with the state carried: - -| seam | through | tolerance | basis | -| --- | --- | --- | --- | -| `conv_output_silu-0`, `q_conv_predelta-0`, `k_conv_predelta-0` | legacy, native, fused (`fused_gdn_conv_l2`), verify window (`gdn_conv_l2_multi`) | 1e-6 | one 4-tap F32 dot per channel | -| `gate-0`, `beta_sigmoid-0` | fused (`fused_gdn_ab`), verify window (`gdn_ab_multi`) | 1e-6 | a 64-term dot against a BF16-exact weight | -| `final_output-0` (every token) | all four | 8e-5 | oracle-crosscheck.md's `gdn_out` class | -| `new_state-0` (after the 11th token; the verify window after two commits of 8 + 3) | all four | 2e-5 | the recurrence in F32 both sides | -| `ffn_moe_topk-0` | `router_top10` at 256/8 from the oracle's `ffn_moe_logits-0` | identical | exact top-k on the F32 fixture only | -| `ffn_moe_weights_norm-0` | same | 1e-5 | | -| `ffn_shexp_gated-0` | `shared_expert`, native Q8_0 projections, the 1-D BF16 scalar gate | 1e-5 against the Q8 oracle | the engine rounds activations to Q8_1 as ggml does; the F32 oracle is 1.2e-2 away, which is the rounding itself and is printed, not gated | -| `shared_expert_multi` | 8 + 3 tokens | bitwise the per-token call | verify.cpp's contract | - -Negative cases through the kernels: the sigmoid gate at `final_output-0` (the oracle's control says 1.07), the -un-normalised router weights at `ffn_moe_weights_norm-0`, the shared gate skipped at `ffn_shexp_gated-0`. - -### `router_top10_parity` and `shared_expert_parity` - -The router's five fixtures at both 512/10 and 256/8 (random, all-equal, a 12-way tie wider than k, a tie of exactly -k scattered through the range, a dominant expert) and the clamp proved unreachable at both (8/256 is 512x the -2^-14 clamp). The shared expert gains Qwen3.6's shape, 2048 x 512 with Q8_0 projections through `native_mmvq` and -Q8_1 activations and the native BF16 scalar gate, against a host reference written from the block layouts; the -silu-on-up reading and the skipped gate as negatives; `shared_expert_multi` bitwise the per-token call; and the -output moved by rounding the F32 gate weight to BF16 reported (2.5e-4 on a random gate), not asserted. - -## 3. The measured-not-asserted parity: the BF16 router (study 3.4) - -`tools/qwen36_router_bf16_flips.py REAL.gguf DUMP` on the oracle's `--act-quant q8` dump of the first 8 tokens of -`"Hello, world! How are you?"` (ids 9419, 11, 1814, 0, 2500, 513, 488, 30 by `llama-tokenize` on the IQ3_XXS file), -VM 221, 2026-10-11 (`/models/work/logs/qwen36-step3-gdn-flips.log`): - -| contract | top-8 slots differing (of 320) | experts in one set and not the other | tokens affected | rate | -| --- | ---: | ---: | ---: | ---: | -| F32 x F32 (llama.cpp, the oracle) | 0 | 0 | 0 | 0 | -| F32 x BF16(W) (the engine's native MMVF, `bf16_gemv_fp32_mmvf`) | **0** | **0** | **0** | **0** | -| BF16(x) x BF16(W) (the legacy `bf16_gemv`, both rounded) | 34 | 6 | 6 | 0.23% (layers 4, 9, 12, 31, 32, 37; one slot each) | - -**Why the native contract flips nothing: the F32 routers are already BF16.** A census of both shipped files -(IQ3_XXS and Q4_K_XL): every element of `ffn_gate_inp`, `ffn_gate_inp_shexp`, `ssm_alpha`, `ssm_beta` and -`ssm_conv1d` has its low 16 bits zero (20,971,520 of 20,971,520 router values per file); the checkpoint is BF16 and -the converter stored these as F32. So `BF16(W) == W`, the engine's BF16 reading is lossless, and the pack's own rule -("round exactly when the low 16 bits are zero", `upstream-tooling.md` section 4) already covers all four tensors -`moe_shared`, `fused_gdn_ab` and the router read as BF16: **`--compat-bf16` is not needed for Qwen3.6**. The only -rounding left is the activation's, in the legacy both-operands contract, which `native_bf16_projections` (step 2's -default for native packs) does not use. `attn_norm` is not BF16-exact (17%) and is read as F32, which is fine. -The study's "the router's flip rate is measured on the real file" (3.4, risk 6) stands, with the answer zero. - -## 4. Results - -### VM 221, the RTX 4090 (sm_89), 2026-10-11 - - rsync -rlpgoD --checksum --delete --exclude .git --exclude '/build/' --exclude '/build-mac/' --exclude '/logs/' \ - --exclude '/third_party/llama.cpp/' ~/Code/UnbiasedStrata-step3-gdn/ rk@192.168.50.151:/models/work/qwen36-step3-gdn/ - /models/work/build-step3-gdn.sh configure && /models/work/build-step3-gdn.sh all # 178 s clean, rc 0 - (cd build && ctest --output-on-failure -R 'qwen36_oracle_dumps|qwen36_seam_parity|gdn_parity|router_top10_parity|shared_expert_parity') - -(`rsync -a` preserves the Mac's mtimes, and an object built seconds after an edit then looks newer than the edit: -the first full build linked against a stale `verify.cpp.o`. `-rlpgoD --checksum` is `-a` without `-t`.) - -5 of 5 pass. The numbers (relative L1 unless stated): - -| harness | check | measured | tolerance | -| --- | --- | ---: | ---: | -| `gdn_parity` 16/48 | legacy / native / fused state vs reference | 4.0e-8 / 6.0e-8 / 6.0e-8 | 1e-5 | -| | legacy / native / fused y (sigmoid) | 2.3e-7 / 1.4e-7 / 1.7e-7 | 1e-5 | -| | the wrong gate (SiLU) through each kernel | 87% / 87% / 90% / 91% apart | > 5% | -| `gdn_parity` 16/32 | legacy / native / fused state vs reference | 4.4e-8 / 6.0e-8 / 6.0e-8 | 1e-5 | -| | legacy / native / fused y (SiLU) | 2.8e-7 / 1.4e-7 / 1.7e-7 | 1e-5 | -| | the wrong gate (sigmoid) through each kernel | 110% / 125% / 116% / 110% apart | > 5% | -| | verify kernel bitwise fused (y; commit; split commit) | yes / yes / yes | bitwise | -| | pairing, decay, conv layout, l2 eps traps | 128% / 83% / 128% / 1031% apart | > 5% | -| `qwen36_seam_parity` | `conv_output_silu-0`, worst path | 5.96e-8 | 1e-6 | -| | `q/k_conv_predelta-0` (fused, verify) | 9.4e-8 | 1e-6 | -| | `gate-0` / `beta_sigmoid-0` (fused_gdn_ab, gdn_ab_multi) | 2.3e-7 / 1.1e-7 | 1e-6 | -| | `final_output-0`, worst token, legacy / native / fused / verify | 2.28e-7 / 1.91e-7 / 2.15e-7 / 2.15e-7 | 8e-5 | -| | `new_state-0`, legacy / native / fused / verify (two commits) | 1.31e-7 / 1.49e-7 / 1.59e-7 / 1.59e-7 | 2e-5 | -| | sigmoid gate at `final_output-0` (fused; verify window) | 125.8% / 125.8% apart | > 5% | -| | `ffn_moe_topk-0` | 0 of 88 differ | identical | -| | `ffn_moe_weights_norm-0`; the un-normalised reading | 6.1e-8; 23.5% apart | 1e-5; > 5% | -| | `ffn_shexp_gated-0` vs the Q8 oracle; vs the F32 oracle | 3.5e-7; 1.2e-2 (reported) | 1e-5 | -| | the shared gate skipped; `shared_expert_multi` vs per-token | 51.5% apart; bitwise | > 5%; bitwise | -| `router_top10_parity` 512/10 and 256/8 | ids on 5 fixtures x 64 tokens; weights | exact; worst 1e-6-class | exact; 1e-5 | -| `shared_expert_parity` 2048 x 512 | native Q8_0 + BF16 gate vs reference | 9.6e-8 | 1e-4 | -| | silu-on-up; gate skipped; F32 vs BF16 gate weight | 83% / 272% apart; 2.5e-4 (reported) | > 5% | - -### VM 211, the GTX 1080 Ti (sm_61), 2026-10-11 - -`/home/rk/qwen36-step3-gdn-run.sh` (kept on the VM), under the card lock for 5 minutes: the rsync above to -`/home/rk/qwen36-step3-gdn/`, `set -o noclobber; echo qwen36-step3-gdn > /home/rk/VM-BUSY` after checking -`pgrep -x llama-server` and `pgrep -f "[s]weep_ladder_1080ti.py"` are empty (the bracket keeps `pgrep -f` from -matching its own shell, which it did on every earlier poll), then - - cmake -S . -B build -DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_PORTABLE=ON -DSTRATA_BUILD_TESTS=ON \ - -DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61 -DCMAKE_CUDA_HOST_COMPILER=g++-13 \ - -DCMAKE_C_COMPILER=gcc-13 -DCMAKE_CXX_COMPILER=g++-13 # 4 s - cmake --build build -j 8 -- -k # 287 s, rc 0, everything - (cd build && ctest --output-on-failure -R 'qwen36_oracle_dumps|qwen36_seam_parity|gdn_parity|router_top10_parity|shared_expert_parity') - rm /home/rk/VM-BUSY # the script's EXIT trap - -5 of 5 pass (`/home/rk/logs/qwen36-step3-gdn-1080ti.log`, the four binaries' printouts beside it). Every seam number -of `qwen36_seam_parity` is the same digits as on the 4090 (the kernels are F32 and the summation orders do not -depend on the card): `final_output-0` 2.28e-7 / 1.91e-7 / 2.15e-7 / 2.15e-7, `new_state-0` 1.31e-7 / 1.49e-7 / -1.59e-7 / 1.59e-7, `conv_output_silu-0` 5.96e-8 worst, `gate-0` 2.27e-7, `ffn_moe_topk-0` identical, -`ffn_moe_weights_norm-0` 6.1e-8, `ffn_shexp_gated-0` 3.5e-7 against the Q8 oracle, `shared_expert_multi` bitwise, -the three negatives 125.8% / 23.5% / 51.5%. `gdn_parity`: states 5.3e-8 to 6.0e-8, y 1.4e-7 to 2.8e-7, the verify -kernel bitwise the fused one on all three paths, the wrong gate 87% apart at 16/48 and 110% at 16/32 through every -kernel. `shared_expert_parity` at 2048 x 512: 9.6e-8; `router_top10_parity`: ids exact at both shapes, weights -worst 1.5e-7. - -Nothing in the changed kernels is architecture-conditional: the SiLU is an `expf` and a divide in kernels that -already ran on sm_61 in step 2's build, so no new guard was needed; the pass on the card is the proof. - -## 5. The interface other agents consume - - namespace strata::kernels { - enum class GdnGate : int { Sigmoid = 0, Silu = 1 }; // strata/kernels/gdn.hpp - inline const char* gdn_gate_name(GdnGate g); - void gdn_out_norm(const float* o, const float* z, const float* ssm_norm, float* y, int64_t h_v, int64_t S, - float eps, GdnGate act, void* stream); // gdn.hpp (legacy) - void fused_gdn_step_norm(float* state, const float* q, const float* k, const float* v, const float* gate, - const float* beta, const float* z, const float* gamma, float eps, GdnGate act, - float* y, int h_k, int h_v, void* stream); // fused_gdn.hpp - void native_gdn_out_norm(const float* output, const float* z, const float* gamma, float* destination, - int64_t heads, int64_t cols, float epsilon, GdnGate act, void* stream); // native_gdn_preprocess.hpp - void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta, - const float* z, const float* gamma, float eps, GdnGate act, float* y, int h_k, int h_v, - int n_tok, const int32_t* n_keep, void* stream, int t_out_begin = 0); // verify_kernels.hpp - } - kernels::GdnGate strata::core::ModelGeometry::gdn_gate() const; // strata/core/layout.hpp - -Everything else is unchanged: `GdnShapes{S, h_k, h_v}` at runtime, the state `(S, h_v, S)` with j fastest, the conv -history `[channel][3]`, `router_top10(logits, n_tokens, n_expert, k, ids, weights, stream)` at 256/8, `shared_expert` -and `shared_expert_multi` with `NativeSharedWeights` (type ids per `native_mmvq.hpp`) at `n_ff` 512. The prompt-path -GDN kernels (`src/prefill/kernels.cu:324, 612`) are the prefill agent's and still gate with sigmoid; they will want the -same `GdnGate` argument. `layer.hpp:16`'s comment still says "SIGMOID for qwen4exp; qwen3.5 used SiLU" (the block -agent's file; the code beneath it is right). diff --git a/docs/qwen36-port/step3-integration.md b/docs/qwen36-port/step3-integration.md deleted file mode 100644 index 454a2e5..0000000 --- a/docs/qwen36-port/step3-integration.md +++ /dev/null @@ -1,63 +0,0 @@ -# Qwen3.6 port, Phase 2 step 3: the integration branch `qwen36-step3` - -Branched from the step-2 head (0e40d4e) on 2026-10-11. Five areas were developed in parallel from 8b7525e, each on its -own branch with its own notes, and cherry-picked here in this order with no conflicts: block (`step3-block.md`, 5 -commits), gdn (`step3-gdn.md`, 8), experts (`step3-experts.md`, 7), attn (`step3-attn.md`, 9), prefill -(`step3-prefill.md`, 12 of 17: its five cherry-picks of attn and gdn commits were dropped here because the originals -are present). One commit of the integrator's own, 7cfb7dc: `generate.cpp` calls `qsa_kv_streaming_applies` right after -the geometry is read (the attention agent could not edit that file). - -## Both cards, the whole branch - -Configure for both: `-DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_PORTABLE=ON -DSTRATA_BUILD_TESTS=ON --DSTRATA_MMQ_KQUANTS=ON` with gcc-13 as the host compiler; the 1080 Ti adds `-DSTRATA_EXPERIMENTAL_SM60=ON --DCMAKE_CUDA_ARCHITECTURES=61`, the 4090 `-DCMAKE_CUDA_ARCHITECTURES=89`. `STRATA_MMQ_KQUANTS` is needed for the -Q4_K_XL file's prompt path (Q6_K down on layers 34, 38, 39) and defaults OFF; step 5 turns it on in the Makefile. - -| Card | Build | ctest | Failures | -| --- | --- | --- | --- | -| RTX 4090 (VM 221, sm_89) | 0 errors, 420 s for every target | 89 of 92 pass | ple_parity (no Flash-Next shard on the host), platform_memory_test (mlock limit), expert_multi_test (no AVX-512) | -| GTX 1080 Ti (VM 211, sm_61) | 0 errors, 302 s | 87 of 92 pass, 2 skipped (the sm_80 fused prompt MoE tests) | the same three | - -Every step-3 test (qwen36_block_test, qwen36_seam_parity, gdn_parity, router_top10_parity, shared_expert_parity, -qsa_dense_parity, the native_expert_parity pairs, prefill_mmq_kquant_test, gdn_rec_parity, prefill_qwen36_test) passes -on both cards; the per-seam numbers are in each area's notes and are identical on both cards to the printed digits. - -## The review (`step3-review`, read-only, on the 41-commit range) and what it changed - -1. HIGH, attn x block seam: `shapes_of` in verify.cpp and mtp.cpp left `idx_top_k = 2048` on a no-indexer geometry, a - "half set up" shape that `qsa.cu`'s validate refuses, so the verify window would have exited on the first Qwen3.6 - attention layer. Not covered by any test (no test drives `Verifier` on qwen35moe; that is step 4's runner test). - Fix: one exported shape builder for all four sites and one dense predicate. -2. MEDIUM, Flash-Next: the MTP drafter's attention (cap = the 32,768 draft window) took the new bounded split-K kernel, - a different summation order; drafts are verified, so draft quality, not correctness. Fix: sparse-model shapes keep - the previous grid. -3. LOW: the prefill fixture failed instead of skipping without numpy (fixed, c4f599f); native_expert_parity's 3e-2 - bound tightened to the policy's 2e-2 with separate CPU rows (77983af); `qsa_attn_bench` registered as a test - (removed from the suite). - -All fixed on the attention branch and cherry-picked here (one builder `strata::core::qsa_shapes(g)` in -`include/strata/core/qsa_shapes.hpp` used by layer, verify, mtp, session and prefill, the last by delegation from -prefill's `shapes_of`; `qsa_dense()` and the kernels' guard test the same three-zero predicate; the split-K bound applies -to dense shapes only, so Flash-Next's drafter keeps its 512-block grid and 12.09 MiB scratch, A/B equal within 1 us on -the 1080 Ti). After the fixes: 4090 88 of 91 (the same three host failures); 1080 Ti incremental build 81 s, the 33 -attention / prefill / expert / verify tests 33 of 33. -4. NOTE: the GDN head pairing is tiled (`h % 16`), as llama.cpp, the oracle and the engine all have it; the reviewer's - brief had said interleaved, which is the oracle's negative control. - -Not checked end to end until step 4's pack and runner exist: the verify window on qwen35moe, the decode mixers through -`block_layer_pre` stage 1 on a real pack, `native_rope_apply` against the Qwen3.6 oracle, dense attention above 20,000 -cells against a reference, the drafter on qwen35moe. - -## Findings that feed step 4 and 5 - -- The real files' F32 routers, `ffn_gate_inp_shexp`, `ssm_alpha`, `ssm_beta` and `ssm_conv1d` are BF16-exact - (low 16 bits zero in every element of both files), so the engine's BF16 reading is lossless and `--compat-bf16` is - not needed; the measured top-8 flip rate on the real file is 0 of 320 slots (`step3-gdn.md`). -- The native expert kernels accept every layer of both files; on the 1080 Ti the down projection per expert is - Q5_K 4.3 us, Q6_K 5.3, IQ3_XXS 6.8, IQ4_XS 6.6 against Q5_1's 4.4 (`step3-experts.md`). -- Dense attention per query row at 262,144 cells: 1.0 ms on the 4090, 2.4 ms on the 1080 Ti (fp16 KV); the split-K - scratch is 2.02 MiB per row (`step3-attn.md`). -- `moe_fused_iq.cu` (sm_80+) still lacks the new down types; those layers take MMQ in the prompt path. -- VM hygiene: sync with `rsync -rlpgoD --checksum` (`-a` keeps Mac mtimes and can leave a stale object linked); - `pgrep -f "[s]weep_ladder_1080ti.py"` (the unbracketed pattern matches its own shell). diff --git a/docs/qwen36-port/step3-prefill.md b/docs/qwen36-port/step3-prefill.md deleted file mode 100644 index ace64f4..0000000 --- a/docs/qwen36-port/step3-prefill.md +++ /dev/null @@ -1,217 +0,0 @@ -# Qwen3.6 port, Phase 2 step 3: the prompt path at Qwen3.6's geometry - -Working notes of the prefill item of step 3 (2026-10-11, branch `qwen36-step3-prefill`, branched from `qwen36-step2` at -8b7525e). The design is `docs/QWEN36-35B-A3B.md` section 3.6 (the table of literal sites) and section 6, step 3, the -prefill bullet; the rules are `step3-common.md`. Every item says what was decided, where it lives, how it is checked, -and the numbers from both cards. - -## 1. What changed, site by site - -`src/prefill/*` is the whole scope. The study's table (3.6) had eight literal sites; what each became: - -| Study's site | What it was | What it is now | -| --- | --- | --- | -| `prefill.cpp` constants `N, HC, D, LR, K, NE, C, ZV, HV` | file-wide `constexpr` (2560 / 4 / 10240 / 320 / 10 / 512 / 10240 / 6144 / 48) | a `Geom` struct built from the `ModelGeometry` (`Geom::of`): n_embd, hc, hc*n_embd, hc_lr, k, n_expert, n_ff (and 2 n_ff, the shared width), conv channels, value dim, value heads, key heads, heads, KV heads, head dim, `attn_q`'s width, n_head*256, n_head_kv*256, `indexer`, `silu`. Every count (`gdn_set_bytes`, `qsa_set_bytes`, `moe_bufs`, `moe_set_bytes`, `bytes_needed`) and every launch in `carve` and `run_impl` reads it. The old names stay as local aliases inside each function so the arithmetic reads as before | -| `Prefill::init`'s refusal (`n_embd == 2560 && hc == 4 && hc_lr == 320 && k == 10`) | one geometry | per architecture: `qwen4exp` keeps exactly that check; `qwen35moe` needs `hc == 1`; both need `ss.k == n_expert_used`, `k` in 1..32 and at most `n_expert`, a GDN geometry the kernels are built for (`gdn_geometry_supported`: 48/16/10240 or 32/16/8192, state 128, conv 4), head_dim 256, 2 KV heads, n_rot 64, n_embd a multiple of 256, n_ff of 64. Each refusal names what it saw | -| `Qf` as `T * 12288`, `q` / `attn` as `T * ZV`, `idx_raw`, `q_idx` | 24 heads x 512; the indexer's two buffers always | `T * G.qf` (n_head * 512), `T * G.av` (n_head * 256); the indexer's buffers, the selection scores and the ids rows only with an indexer (`G.indexer`). Dense attention carries no ids: a null is the identity selection (below) | -| MoE buffers `T*K*1280`, `T*K*640`, `1280 * 2560`, `2560 * 640`; `mmq::fits(gt, 1280)`, `matrix_bytes(dt, N, 640)` | 2 n_ff and n_ff as 1280 / 640 | `G.ff2`, `G.ff`, `G.ffs`; `mmq_plan()` takes each layer's widths from the native layout (`fmt[l].n_embd`, `fmt[l].n_ff`; the canonical Q2_0 pack's 2560 / 640 otherwise), so the plan is per pack, not per build. The peer paths (`set_peer`, `bind_stage_helper`, the peer products in `run_impl`) use the same members; `PeerPrefill`'s event ring and host bounds are sized once from `NE_MAX = 512` | -| `grs`, `gated`, `inj`, `xq`, `ident` from `HC`, `D`, `LR` (`:854-856, :1000-1026, :1375-1380`) | the hyper-connection's buffers and the GR read / write around every half | carved only at `hc > 1`. At `hc == 1` the half is `x = rms_norm(R, attn_norm) -> mixer -> R += out; x = rms_norm(R, post_attention_norm) -> MoE -> R += out` through two new kernels, `rms_norm_images` (the FP32 norm with its BF16 and FP16 images, gr_norm_kernel's arithmetic on one stream) and `residual_add`. The GR path is untouched (`gr_*` kernels, the F-2 fusion, `STRATA_GR_UNFUSED`); the embedding broadcast becomes a copy. `draft_kv` (the MTP drafter's K/V through this path) is Flash-Next's graph and returns false for `qwen35moe` (step 4 brings the nextn block) | -| GDN kernels on `HV`, `HK`, `C`, launched `<<>>`; `VPK = 3` | file constants | templates on `` (`gdn_gates_kernel`, the three conv kernels and the l2 norm on ``, `gdn_rec_kernel`, `gdn_rec_cols_kernel`, `gdn_rec_cols_pipe_kernel`, `gdn_rec_kh_kernel` with `VPK = HV / HK` and a `static_assert(HV % HK == 0 && VPK <= RG)`, `gdn_out_norm_kernel`, `gdn_keyhead_ok`), 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(z)`: `z * sigmoid(z)` for Qwen3.6, `sigmoid(z)` for Flash-Next, chosen from `g.arch` (`Geom::silu`) | -| `route_kernel` 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. diff --git a/docs/qwen36-port/step4-drafter.md b/docs/qwen36-port/step4-drafter.md deleted file mode 100644 index c74f1f9..0000000 --- a/docs/qwen36-port/step4-drafter.md +++ /dev/null @@ -1,266 +0,0 @@ -# Qwen3.6 port, Phase 2 step 4, area `drafter`: the MTP draft block from `blk.40` - -Working notes, kept as the step was done (2026-10-11, branch `qwen36-step4-drafter`, from the step-4 integration -branch `qwen36-step4` at 1db8252). The design is `docs/QWEN36-35B-A3B.md` 3.10 and section 6 (step 4); what the -block computes is `docs/qwen36-port/oracle-crosscheck.md` ("Nextn / MTP", 50 seams verified against llama.cpp) and -`gguf-metadata.md` ("The nextn block"); the trunk pack this one sits beside is `step4-pack.md`. Section 2 is the -pack's layout, section 5 the numbers from both cards, section 7 the interface the runner consumes. - -## 1. The numbers first - -**The real file, RTX 4090 (VM 221).** The draft pack cut from `/models/Qwen3.6-35B-A3B-UD-Q4_K_XL-MTP.gguf`'s -`blk.40`, loaded by the engine (506 MiB of VRAM: experts 464, dense 39, the K/V aside), fed the trunk's final residual -of a 33-token prompt (llama.cpp's own `l_out-39` from `tools/qwen36_dump_llama.cpp` on that file), one row per -position, token k with the hidden of k-1: - -| | | -| --- | --- | -| top-1 agreement with llama.cpp's MTP arm (its `graph_mtp` on the same pairs, `qwen36-dump ... mtp`) | **32 of 32** (the whole head); 31 of 32 with the shipped `data/draft_vocab.bin` subset (position 2's " fox", id 37550, is not in the subset) | -| top-1 equal to the prompt's next token (teacher-forced acceptance over 31 positions) | **engine 24 of 31 (77.4 %)**, llama.cpp's MTP 24 of 31 (77.4 %): the same 24 | -| seams vs llama.cpp's MTP graph (relative L2 per row, worst over 32 positions / relative L1 over all) | `mtp_eh_proj` 1.2e-3 / 5.6e-4, `mtp_attn_out` 1.2e-2 / 7.7e-3, `mtp_ffn_out` 2.5e-2 / 1.8e-2, `mtp_shared_head_norm` 2.2e-2 / 1.5e-2 | - -llama.cpp's figures are its CPU graph with Q8_K / Q8_0 activation rounding; the engine's are q8_1 activations on -the GPU. Those are the real-file numbers of the policy's Q8 class (`oracle-crosscheck.md`: `ffn_out` 4.5e-3 max per -forced layer; here the block's products compound) and the drafts agree at every position. This is the B4 arm of -the plan taken as a per-position reference rather than a generation: the 64-token greedy acceptance under the -runner's verify window is the runner's measurement, after the gate is lifted. - -**The synthetic fixture, both cards, all 37 checks** (section 5): every seam at every one of 75 positions within -the gates against the Q8 oracle (the first product `mtp_eh_proj` at 2.3e-4), the router's top-8 identical at -75 of 75 positions, the argmax identical at 74 and a near tie at the 75th, the three negatives 0.14 to 1.41 away. - -## 2. The pack, exactly - -`python3 -I tools/mtp_qwen36_pack.py --gguf <-MTP file>.gguf --out [--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 ` (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 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. diff --git a/docs/qwen36-port/step4-integration.md b/docs/qwen36-port/step4-integration.md deleted file mode 100644 index 6be8115..0000000 --- a/docs/qwen36-port/step4-integration.md +++ /dev/null @@ -1,58 +0,0 @@ -# Qwen3.6 port, Phase 2 step 4: the integration branch `qwen36-step4` - -Branch `qwen36-step4` (worktree `~/Code/UnbiasedStrata-step4`), from the step-3 head 355ce3c. Unmerged, unpushed. - -## What is on it, in order - -| range | from | what | -| --- | --- | --- | -| 3ad2847..1db8252 (7) | `qwen36-step4-pack` | `iq_pack` FORM_QWEN35MOE, the regex-free tokenizer, `make_profile --n-layer`, the 40x256 expert profile, `pack_load_check`; notes step4-pack.md | -| 02ff47e | integrator | step-3 notes | -| ad70f3d..84b4756 (6) | `qwen36-step4-drafter` | `tools/mtp_qwen36_pack.py`, the qwen35moe drafter in `mtp.cpp`, prefill draft K/V, `[shared] generate.cpp` draft geometry, `qwen36_mtp_test`; notes step4-drafter.md | -| 6d0d817..6042a32 (6, cherry-picked clean) | `qwen36-step4-runner` | the step-2 gate lifted, `[shared] verify.cpp` indexer tail, `qwen36_verify_test` + `qwen36_runner_check.py`, the llama.cpp teacher and the logits comparison, notes, the VRAM plan's drafter term | -| 85d5d12 | `main` f07b81e | the front end's SSE keepalive and client-gone cancel (another session's patch, cherry-picked on request) | -| e73adc6 | integrator | CMake applies the chat-parser patch at configure time (REGINA-104); `make build` turns `STRATA_MMQ_KQUANTS` on | - -The expected `generate.cpp` conflict between the drafter's draft-geometry hunk (:3307) and the runner's gate region -(:2184, :2557) did not occur; the three hunks sit apart. - -## Builds and tests - -- **VM 221, the RTX 4090**: the integrated tree at e73adc6 configures and builds with 0 errors (the common line, - `-DSTRATA_MMQ_KQUANTS=ON`, sm_89; logs `/models/work/logs/qwen36-step4-*.log`, script `/models/work/build-step4.sh`). - The full ctest of the integrated tree is **not** a result: 63 of 97 tests fail in under a second on - `malloc x: out of memory`, because another session's Flash-Next service (`unbiased-strata.service`, active since - 2026-10-12 22:08 UTC) holds 23.9 of 24.5 GB. The 34 that pass are the CPU tests (`vram_plan_test`, the pack and - planner tests, the tokenizer). Owed: the full run once the card has VRAM. -- **VM 211, the GTX 1080 Ti**: the runner's own tree ran steps 2-4 at 21:38 UTC 2026-10-11 (step4-runner.md section - 4): verify test and runner check pass; the real-file llama.cpp comparison did not run (fixtures not synced). The - integrated tree has not been built there: since 2026-10-12 22:04 UTC the card runs a Flash-Next coder service and - the user has asked that it not be interrupted. -- **The chat parser**: `make test-chat-parser MODEL=/models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf BUILD_DIR=build` passes - on VM 221 after the fix (all four argument orders). -- **The Mac** (arm64, CUDA off): the upstream CPU expert kernel is compiled with `-mavx512*` flags unconditionally - (CMakeLists.txt:1086), which clang rejects on arm64, so the CUDA-off Mac build has never linked past - `strata_kernels_cpu`. Not the port's regression; the Mac configure step was used only to verify the patch logic. - -## Numbers that carry forward - -- Speculation with the real drafter on the 4090 (step4-runner.md, round 8): IQ3_XXS 0.77 accepted / 3.20 tokens per - round with the full head, 0.72 / 3.05 with the subset head; Q4_K_XL (plain trunk, MTP-file draft) 0.53 / 2.54. -- The VRAM plan's drafter share is now the whole context's K/V plus the head subset plus the ids (f2e70c8); - `vram_plan_test` passes with the new cases. -- Correctness held on both cards: 1080 Ti argmax 40/40 vs the Q8 oracle, 4090 teacher-forced IQ3 64/64 x3 prompts. - -## Owed to step 5 - -1. ~~Full ctest of the integrated tree on a card with free VRAM.~~ Done 2026-10-13 once the 4090's service was - stopped: 95 of 98 at 22d72e6 (the three host-environment failures), including the serve fixes and - `pool_native_widths_test` of step5-serve.md. -2. The 1080 Ti real-file comparison (sync `/models/work/qwen36-step4-teacher` to VM 211) and the Q4 fit at 11 GB. -3. The ladder: serve and measure on 11 GB, then `--vram-cap` 8 and 6 GB; the three instruments; engine points on - `ladder-baseline.png`; acceptance A1-A5. -4. The step-6 fat binary, compile-checked on VM 221's CPU (`build-fat`, `/models/work/logs/qwen36-step4-fat-*.log`): - `CUDA_ARCHS=61;70;75;86;89` with `STRATA_EXPERIMENTAL_SM60=ON` and `STRATA_MMQ_KQUANTS=ON` configures and builds - `unbiased-strata` in 6 min 17 s at `-j 14`, 0 errors; `cuobjdump --list-elf` shows 62 ELF images per architecture - for all five; 235 MiB. **sm_120 cannot come from this host**: CUDA 12.4's nvcc rejects `compute_120` - ("Unsupported gpu architecture"); Blackwell needs a 12.8+ toolkit, so the step-6 release build either uses a newer - toolkit or ships 120 as PTX from 89. Nothing in this binary has run on a card yet. diff --git a/docs/qwen36-port/step4-pack.md b/docs/qwen36-port/step4-pack.md deleted file mode 100644 index 4456a82..0000000 --- a/docs/qwen36-port/step4-pack.md +++ /dev/null @@ -1,209 +0,0 @@ -# Qwen3.6 port, Phase 2 step 4, area `pack`: the native pack - -Working notes, kept as the step was done (2026-10-11, branch `qwen36-step4-pack`, from the step-3 integration -branch `qwen36-step3` at c6fa016). The design is `docs/QWEN36-35B-A3B.md` 3.7, 3.8, 3.11 and section 6 (step 4); -what the engine reads is `docs/qwen36-port/step3-block.md`, `step3-gdn.md`, `step3-attn.md`, `step3-prefill.md`; -the census that decided the forms is `step3-gdn.md` section 3. This file is the contract the drafter and runner -agents consume: section 2 is the pack's layout, exactly; section 5 is how the engine loads it and what was verified -on both cards. - -## 1. What changed - -| Where | What | Why | -| --- | --- | --- | -| `tools/iq_pack.py` | `FORM_QWEN35MOE` beside Flash-Next's `FORM` (`FORMS[arch]`, `form_of(name, arch)`); `NATIVE_PROJECTIONS_QWEN35MOE` / `NATIVE_PROJECTION_TYPES` / `NATIVE_EMBED_TYPES` with `native_type_problem`; the draft block (`blk.` 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 (` ... ` 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 .gguf --out ` 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 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 ; absolute offsets in )`; 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 "`` 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 .gguf --pack # section 5 - ./build/strata --native .gguf --pack --tokens 1 --max-context 262144 --kv q4_0 --spec 4 \ - --prefill 2048 --expert-profile /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. diff --git a/docs/qwen36-port/step4-runner.md b/docs/qwen36-port/step4-runner.md deleted file mode 100644 index d08a5f7..0000000 --- a/docs/qwen36-port/step4-runner.md +++ /dev/null @@ -1,195 +0,0 @@ -# Qwen3.6 port, Phase 2 step 4, area `runner`: the gate lifted, the first token held to the oracle and llama.cpp - -Working notes, kept as the step was done (2026-10-11, branch `qwen36-step4-runner`, from the step-4 integration -branch `qwen36-step4` = step 3 complete + the pack). The design is `docs/QWEN36-35B-A3B.md` sections 3.5 and 6 -(step 4) and 3.5; what the pack carries is `docs/qwen36-port/step4-pack.md` (section 2 the layout, section 6 the load -order); the references are `docs/qwen36-port/oracle-crosscheck.md` (the cases, the tolerance policy, the quantized-mode -gates). This file is the runner half; the drafter is `qwen36-step4-drafter` (mtp.cpp, blk.40), not touched here. - -## 1. What this makes the engine do - -With `--native --pack ` 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_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=`): 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 `, `qwen36_runner_check.py --strata S --fixture DIR`, both from - `qwen36_runner_fixture.py --out DIR`. diff --git a/docs/qwen36-port/step5-serve.md b/docs/qwen36-port/step5-serve.md deleted file mode 100644 index 9bf9123..0000000 --- a/docs/qwen36-port/step5-serve.md +++ /dev/null @@ -1,521 +0,0 @@ -# Qwen3.6 port, step 5, first part: serving on the 4090, and what broke below full residency - -Branch `qwen36-step4`, 2026-10-13, VM 221 (RTX 4090, 24 GB; the user handed the box to this work at 02:05 UTC and the -Flash-Next service on it was stopped). Tree `/models/work/qwen36-step4`, binary `build/unbiased-strata`, logs under -`/models/work/serve/`. The 1080 Ti (VM 211) is off limits: another session's service runs there. - -## The serve command - -``` -./build/unbiased-strata --model /models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf --pack /models/work/packs/qwen36-q4 \ - --mtp /models/work/packs/qwen36-mtp-draft-full --ctx 262144 --threads 8 --host 127.0.0.1 --port 18090 -- --kv q4_0 -``` - -`--mtp` takes a Qwen3.6 draft pack (`tools/mtp_qwen36_pack.py`); `qwen36-mtp-draft` carries a `draft_vocab.bin` -subset, `-full` has none. Everything after `--` goes to the engine: `--vram-cap MiB`, `--ram-cap GiB`, `--kv -fp16|q4_0|int8`, `--expert-cache N|auto`, `--pcie-frac F`, `--prompt-cache N`, `--vram-reserve-mib`. - -## Faults found in order, all fixed on the branch - -| # | Symptom | Cause | Fix | -| --- | --- | --- | --- | -| 1 | `unbiased-strata: missing file: .../qwen36-mtp-draft-full/draft_vocab.bin` | the front end required the Flash-Next draft vocabulary subset | optional in the front end as it already was in the engine (3a806b5) | -| 2 | first request: 220 tokens generated, then `saving a conversation checkpoint failed` (`conversation snapshot: invalid model geometry`, then `invalid indexer running-state target`) | the prompt-cache checkpoint and the snapshot rejected a geometry with no indexer (idx heads / key dim 0) and no hyper-connection rate, and demanded the indexer's tail / dead / block-position / pooled buffers | zeros allowed where `has_indexer()` is false and `hc` is 1, no indexer buffers or block positions for dense attention, pooled rows 0 (3a806b5). Two-turn conversation: 1 then 2 checkpoints, prefix reused | -| 3 | Q4 at 262,144: `2, 3! 5, 7, 11, !!!!!!...` (token 0 forever); IQ3 under any `--vram-cap` the same; both files fine at 8K / 32K; IQ3 at 256K fine | **the pool's native-pack phases iterated the canonical Q2_0 widths (FF 640, H 2560) instead of the layer's (512, 2048)**: every expert miss computed on the CPU wrote 512 rows past its output row. The runner's and drafter's tests all ran with every expert resident, so the miss path had never executed on Qwen3.6 | `run_split_multi_native` at `NativeFmt::n_ff / n_embd`; `native_fmt` refuses wider layers; `pool_native_widths_test` (22d72e6) | - -How fault 3 was isolated (each row one serve, the prime-numbers prompt, greedy, `bangs` = count of `!` in 120-200 -tokens): - -| Run | file | ctx | KV | slots resident | misses on | result | -| --- | --- | --- | --- | --- | --- | --- | -| e1 | Q4 | 8192 | fp16 | 10,240 / 10,240 | - | correct, 362 tok/s | -| e3 | Q4 | 262,144 | q4_0 | 9,980 | CPU + DMA | `2, 3, 5, 7, !!!` | -| e2 | Q4 | 262,144 | q4_0, `--vram-cap 20480` | 8,132 | CPU + DMA | `!!!` from the first token | -| e4 | Q4 | 262,144 | fp16 | 8,120 | CPU + DMA | `!!!` | -| e5 / e6 | Q4 | 8192 / 32,768 | q4_0 | 10,240 | - | correct, 354 / 356 tok/s | -| t1 | IQ3 | 262,144 | q4_0, `--vram-cap 15360` | 10,212 | CPU + DMA | `!!!` | -| t2 | Q4 | 262,144 | q4_0, `--vram-reserve-mib 1200` | 9,838 | CPU + DMA | `!!!` (so not VRAM pressure) | -| t3 | Q4 | 8192 | fp16, `--expert-cache 8000` | 9,587 | CPU + DMA | `!!!` (the cheap reproduction) | -| t4 | Q4 | 8192 | as t3, `--pcie-frac 1.0` | 9,587 | DMA only (GPU computes) | **correct**, 305 tok/s | -| t5 | Q4 | 8192 | as t3, `--pcie-frac 0.0` | 9,587 | CPU only | `!!!` | -| t6 / t7 / t8 | Q4 ggml dots only / IQ3 / one worker | 8192 | as t5 | 9,587 | CPU only | `!!!` all three: not the kernels | -| fix | Q4 | 8192 | as t5 | 9,587 | CPU only | correct, 328 tok/s | -| fix | Q4 | 262,144 | q4_0 | 9,980 | CPU + DMA | correct, 322 tok/s | -| fix | IQ3 | 262,144 | q4_0, `--vram-cap 11264` | 5,762 (56%) | CPU + DMA | correct, 169 tok/s; 63,526 VRAM hits of 73,553 lookups | - -| 4 | Pascal host (VM 211, step5-1080ti, REGINA-106): with CPU-computed misses iq3-test20 51/64 top-1, KL 0.84; Q4 52-54/64, KL 0.25; DMA misses correct; deterministic; `--spec 1` changes it | **the multi-token CPU dispatch addressed token t's activation at t x 2560 and its output row at i x 2560** (the canonical widths pulled in by `using namespace`), while the window publishes at the layer's 2048: every token after a group's first used another token's activation. Named by the Codex review of 22d72e6; the 4090's serve looked right because its text was checked, not its logits | the dispatch at the layer's width with refusals (the commit after 22d72e6); after it on VM 211 all three IQ3 prompts 64/64 (KL 1.4e-3 / 4.8e-3 / 2.0e-3), q4-test20 62/64 KL 6e-3, q4-prime 64/64 KL 8e-4, CPU misses forced. The ladder points taken with the old binary are rerun | -| 5 | the 4090 sweep's `--ram-cap 12` points: "ArenaExpertSource: the expert arena needs 18.32 GiB ... memory limit is 12.00 GiB ... --mmap-experts" | the plan chose RAM copies but the arena source still pinned the whole file | the engine picks the mapped tier with profile-ranked RAM copies itself when the arena exceeds the limit or available RAM (same commit) | -| 6 | planner (Codex review): a full-head draft pack charged 515 MiB the drafter never allocates; k8v4 undercounted the drafter's INT8 K/V by 60 MiB; a lowered context was printed but not applied | | all three in the same commit; multi-GPU helpers refused for this geometry | - -| 7 | second Codex review of fa69e82: the front end kept validating and advertising the requested `--ctx` when the engine's plan lowered it; the automatic mapped tier ignored an explicit `--shared-expert-arena` and the multi-GPU residency rules; the plan's session term keeps the RoPE table at the requested context | | the front end takes the context from the engine's `READY ` 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 (`` 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 `` block (with thinking off, without the empty `\n\n` -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 `), 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. diff --git a/docs/qwen36-port/upstream-tooling.md b/docs/qwen36-port/upstream-tooling.md deleted file mode 100644 index 618ac28..0000000 --- a/docs/qwen36-port/upstream-tooling.md +++ /dev/null @@ -1,106 +0,0 @@ -# Upstream Strata tooling the Qwen3.6 port needs back - -Surveyed 2026-10-11. Read-only references: - -- `/Users/robertkarl/Code/strata-upstream-6f32ec0`: exact snapshot, exported with `git archive 12a7825` from this repository's first commit ("Import Strata at 6f32ec0, unmodified"). Use this one. -- `/Users/robertkarl/Code/strata-upstream`: a clone of `Niko1221/Strata` main (1859 commits). **Commit `6f32ec0` is not in the public history**: `git checkout` fails with "unable to read tree", so the pinned commit was force-rewritten or never public. Main still carries the same tooling and adds `bench/bench_vs_llama.py`. - -Nothing was built. UnbiasedStrata was not modified. - -## 1. The finding that changes the plan - -Upstream's Python oracle is **not** published. `ref/` contains only `ref/load.py`, in the snapshot and in main, in every commit. The engine source cites `ref/gdn.py` (22 times), `ref/qsa.py` (26), `ref/moe.py` (12), `ref/gr.py` (11), `ref/ngram.py` (10), `ref/model.py` (9) and `ref/quant.py` (7), and `docs/semantics.md` and `docs/activation-contract.md` do not exist in any commit. The same holds for `bench/micro/` (the ggml-oracle tests), `tests/python/gen_ple_oracle.py`, `scripts/_gen_f16_oracle.py` and `tests/CMakeLists.txt`. The published CMake says so: "the test suite and the micro benchmarks live in tests/ and bench/micro/, which the published source leaves out". - -So the Maya recipe (`ref/glm.py` plus a synthetic GGUF and dumps) has no upstream Strata counterpart to restore for the mixers or the MoE. What is restorable is `ref/load.py`, the pack tools, the in-C++ parity tests, and the discipline. The Qwen3.6 oracle is new code. It is specified from the pinned llama.cpp graph `third_party/llama.cpp/src/models/qwen35moe.cpp`, as Maya specified `ref/glm.py` from `glm5-next.cpp`. - -## 2. Inventory - -### `ref/` - -- `ref/load.py` (212 lines). `Gguf(path)`: a demand-paged view of a possibly sharded GGUF (shard discovery from the `-0000N-of-0000M` suffix, a directory, or a list). `tensor(name)` returns FP32 shaped (out, in[, experts]). `expert(name, e)` decodes one expert of a fused `[in, out, experts]` tensor without touching the others. `rows(name, idx)` gathers rows of a 2-D tensor (built for the 27 GB PLE table; Qwen3.6 has no PLE). One dequant dispatch `_dequant_flat`: F32, F16, BF16 by hand; Q2_0 through `tools/gguf_writer.dequantize_q2_0`; everything else through gguf-py `quants.dequantize` (the table GEOM holds 13 entries: F32 F16 BF16 Q4_0 Q5_0 Q8_0 IQ4_NL Q3_K Q4_K Q5_K Q6_K IQ4_XS Q2_0). It lacks Q4_1, Q5_1, Q2_K and the IQ1/IQ2/IQ3 types the engine itself serves; a Q4_K_M or UD-Q4_K_XL Qwen3.6 file needs only Q4_K, Q5_K, Q6_K, Q8_0, F32, BF16 or F16, all present. It imports `gguf` without adding it to `sys.path`, so `PYTHONPATH` or `STRATA_GGUF_PY` must point at gguf-py (see section 5). - -### `tools/` (the ones a port uses) - -- `tools/iq_pack.py` (602 lines). The native-pack builder, described in section 4. Hardcodes Flash-Next assumptions listed in section 6. -- `tools/gguf_reader.py` (142). A GGUF v3 header reader with no gguf-py dependency; knows ggml type ids to 42 (Q2_0). Used by `iq_pack`, the tokenizer exporter and `ref/load.py`. It is the Python twin of `src/artifact/gguf_reader.cpp`. -- `tools/gguf_writer.py` (234). A minimal GGUF v3 writer with a Q2_0 quantizer. Its self-test writes a synthetic file with `general.architecture = qwen4exp`. Not a model generator. -- `tools/iq_fixture.py` (137). Writes deterministic i-quant blocks plus gguf-py's dequantized reference for `iq_parity` (see section 3). It is the one fixture generator upstream ships. -- `tools/test_iq_pack.py` (528). The closest thing to a synthetic-GGUF generator upstream ships: `write_gguf()` builds tiny sharded GGUFs with gguf-py's `GGUFWriter` and `quants.quantize`, then asserts pack behaviour (BF16 rounding to even, refused inexact F32 routers, split shards, a layer split across shards, interrupted packs, stale `experts.bin`). Arch string is `qwen4exp`. -- `tools/make_profile.py` (119). Writes `expert-profile.bin`, a ranking of every (layer, expert) pair, from the base profile plus routing traces from `generate --dump-routing FILE`. Has `--n-expert` but `N_LAYER = 48` is hardcoded (line 26) and the output header carries layer and expert counts that the engine checks. Test: `tools/test_make_profile.py`. The shipped `data/expert-profile.bin` is for Flash-Next and is useless for Qwen3.6 (40 layers, 256 experts). -- `tools/mtp_fetch.py` (308). Range-reads the 31 `mtp.*` tensors out of the 131-shard BF16 checkpoint over HTTP and verifies SHA256s (`inventory`, `fetch`, `verify`). Pinned to Qwen3.8-Flash-Next. -- `tools/mtp_pack.py` (193). Quantizes those tensors into an MTP GGUF (`--experts q2_0|q4_0|q8_0`). Hardcodes the Flash-Next tensor names and the 512-expert fused shapes. -- `tools/mtp_rt.py` (111). Turns the MTP GGUF into the engine's runtime files: `experts.bin`, `dense.bin`, `dense.txt`. Applies Gemma-style `+1` to RMSNorm weights. -- `tools/draft_vocab.py` (+ `test_draft_vocab.py`). Extends `draft_vocab.bin`, the token subset the draft head may propose, by script (`--add han|kana|...`) or corpus (`--corpus`, `--coverage`). Data files `data/draft_vocab*.bin` are tied to the Flash-Next vocabulary of 248,320 tokens. -- `tools/strata_tokenizer.py` (331). Exports `tokenizer/` (vocab, merges, chat template) from GGUF metadata. Refuses pre-tokenizer schemes it has not transcribed; Qwen3.6 uses `qwen35`, same family as Flash-Next. Called by `iq_pack` when `/tokenizer/` is missing. Needs `regex`. -- `tools/strata_pack.py`, `pack_layer.py`, `pack_index.py`, `canonical_xcheck.py`. The canonical Q2_0 pack (bakes in the 1,382,400-byte Flash-Next blob). The plan says Qwen3.6 rides the native pack instead, so these are reference only. `canonical_xcheck.py` shows the "bit-exact against gguf-py over every block" style. -- `tools/calibrate.py`, `needle_bench.py`, `batch_test.py`, `test_conversation_cache_*.py`. Server-level measurement and regression harnesses. `calibrate.py` tunes `--pcie-frac`, `--spec-min-p`, `--pool-workers` through an engine's per-request keys. `needle_bench.py` is recall at 32K to 262K through the HTTP API. `batch_test.py` checks batched against solo greedy tokens. -- `tools/_paths.py`. Finds gguf-py: `$STRATA_GGUF_PY`, then `/third_party/llama.cpp/gguf-py`. That second path exists in this fork's submodule, so the tools work unmodified. -- Not needed: `setup.py`/`test_setup_*.py` (the installer), `strata_mcp.py`, `embd_bf16_pack.py`, `ple_fp8_pack.py` (Flash-Next PLE), `hip/`, `vision/`. - -### `tests/` and the parity sources - -- `tests/` in the snapshot has 30 files and no `CMakeLists.txt`: `tests/core/*.cpp` (loader and cache tests, `gguf_fixture.hpp` is a C++ synthetic-GGUF writer with pattern-filled tensors), `tests/cuda/prefill_*_test.cpp`, `tests/hip/*`, `tests/data/native_experts/*.txt` (golden `native_experts.txt` files for q2_0, iq2_xs, iq3_s, iq3_xxs, coder-iq1_m, swift-iq2_xs). -- The root `CMakeLists.txt` references 23 `tests/` sources that are **absent in UnbiasedStrata** (the snapshot has 30 files there), and four `bench/micro/*` sources that upstream never published. Configuring this fork with `-DSTRATA_BUILD_TESTS=ON` would fail at `tests/core/gguf_split_test.cpp` (line 231). Restoring `tests/` fixes all but the `bench/micro` ones, which sit under the oracle option. -- The 36 `src/kernels/*_parity.cpp` files, `src/prefill/gdn_rec_parity.cu`, `src/prefill/gemm_bf16_parity.cu` and `src/kernels/cpu/*_parity.cpp` are **still in UnbiasedStrata**. Relevant to the port: `gdn_parity.cpp`, `router_top10_parity.cpp`, `shared_expert_parity.cpp`, `gr_parity.cpp` (the Flash-Next hyper-connection residual, which Qwen3.6 lacks), `rope_parity.cpp`, `qsa_parity.cpp` (indexer path, bypassed for dense attention), `native_expert_parity.cpp`, `native_grouped_parity.cpp`, `sampler_parity.cpp`, `kv_*_parity.cpp`, `iq_parity.cpp`, `gdn_rec_parity.cu`. - -### Docs - -- `docs/semantics.md`, `docs/activation-contract.md`: **do not exist upstream** (no commit). The semantics live in comments in the parity files and in the unpublished `ref/*.py`. -- `docs/ORCA.md` (95 lines) and `ORCA_Q4_K_S.md` (36). These are the precedent for a **different quantization of the same geometry** (512 experts), not for a different expert count: `iq_pack.py --compat-bf16` rounds the small projections the engine reads as BF16, records each in `compat-bf16.json`, and the pack carries its own tokenizer and `dense.bin`. The precedent for a **different expert count** is the Coder (256 of 512 experts): `iq_pack` reads `n_expert` from the router's shape, `make_profile.py --n-expert 256`, and `tests/data/native_experts/coder-iq1_m.txt`. `docs/MODELS.md` describes it. -- `docs/DETAILS.md` (1127 lines; this fork keeps it as `docs/upstream/DETAILS.md`), `docs/HOW_IT_WORKS.md`, `docs/OLDER_GPUS.md`, `docs/NVIDIA_V100.md`, `docs/paper/`. - -### `bench/` - -- Snapshot: results only (`bench/results/-/` with `README.md`, `matrix.md`, `matrix.json`). Useful as the format for reporting. The speed matrix of `2026-09-28-speed-0114` records the flags the setup writes (`--prefill auto`, `--expert-cache auto`, `--kv-resident`, `--spec 4 --spec-min-p 0.5`). -- Main only: `bench/bench_vs_llama.py` drives Strata's and llama.cpp's OpenAI-compatible servers with the same prompts and GGUF, takes server-side prompt and decode tokens per second, peak VRAM from `nvidia-smi` polling, RSS from `psutil`, interleaves engines across rounds, and has `prompts`, `run`, `quality`, `summary` subcommands. Needs `psutil`. This is the closest match for the plan's baseline-versus-engine comparison, and it is not in the pinned snapshot. -- The engine itself prints a `strata decode GPU stages (ms/window)` line and takes `--dump-routing` (`src/program/generate.cpp:1310`). - -## 3. How upstream produces oracle dumps for a parity test today - -1. There is no dump pipeline for the model. No script in the published tree runs a forward pass of the model and writes per-seam tensors. Everything below is what exists. -2. Most parity tests are self-contained: the oracle is a **host C++ transcription of the spec**, inside the test file. `gdn_parity.cpp` has `ref_step()` and `ref_conv()` "a transcription of `ref/gdn.py`", in double precision, with boolean switches for the rival readings. `router_top10_parity.cpp` has `reference()` (softmax, stable sort, renormalise). Random inputs come from `std::mt19937(2024)`. Nothing is read from `data/`. -3. Registration: `add_test(NAME gdn_parity COMMAND gdn_parity --selftest)` in the root `CMakeLists.txt` under `if(STRATA_BUILD_TESTS)` and a CUDA or HIP backend. `STRATA_BUILD_TESTS` defaults ON only when `tests/CMakeLists.txt` and `bench/micro` both exist, so a published checkout builds none of it unless `-DSTRATA_BUILD_TESTS=ON` is given. Run with `ctest` or the binary with `--selftest`. Exit 0 pass, 1 fail, 77 or 3 skip (`SKIP_RETURN_CODE`). -4. Vector tests embed the oracle as a generated header: `ple_oracle_vectors.inc` ("GENERATED by tests/python/gen_ple_oracle.py") holds token windows and expected hash rows; `qsa_oracle_vectors.inc` holds float32-to-float16 bit pairs from `np.float16(np.float32(x))`. Both generators are unpublished. Regenerating means rewriting them. -5. Fixture tests generate files into the build directory at test time: `iq_parity_fixtures` runs `tools/iq_fixture.py --out /iq_fixture`, which writes `.bin` (int32 header: kernel type id, rows, cols, then raw block bytes) and `.f32` (reference values from gguf-py). `iq_parity ` reads them. CMake probes interpreters for numpy (`-DIQ_FIXTURE_PYTHON` overrides) and uses `FIXTURES_SETUP`/`FIXTURES_REQUIRED` for ordering. This is the only dump-like flow in the published tree, and only for dequantization. -6. Real-GGUF tests take a path from an environment variable or argument: `STRATA_PLE_GGUF` (default `../../Q2_0/...-00002-of-00002.gguf`) and `--pack`, plus binary captures `bench/micro/ple_in.bin` and `ple_out.bin` recorded from ggml's graph by an unpublished `ple_layer_xcheck.cpp`, which "records EVERY intermediate" so a failure is attributable to a stage. -7. The independent-oracle tests (`bench/micro/native_{mmvq,bf16,shared,gr_norm,moe,gdn,gr_postops,router,gdn_preprocess,gdn_pipeline,qsa,rope,ple_postops,flash_attn,qsa_indexer,qsa_score}_parity.cpp`) link a pinned llama.cpp CUDA build as the oracle: `-DSTRATA_ORACLE_SOURCE_DIR=` and `-DSTRATA_ORACLE_BUILD_DIR=` (CMake lines 387 to 408; libraries `ggml`, `ggml-base`, `ggml-cpu`, `ggml-cuda` located with `find_library`). These sources are unpublished, so the 16 names are a list of what to rewrite, and the CMake foreach is the wiring to restore. -8. No dump file naming convention exists upstream. Maya's convention (llama.cpp `cb()` names, files under `data/glm5-synth-dumps/`) is the one to adopt. - -**Negative-test discipline, from `gdn_parity.cpp`.** Before the kernel is judged, each wrong reading of the spec is computed with the same reference and must differ from the right one by more than 5 % (relative L1). Four traps are pinned: modulo versus interleaved head pairing, decay before versus after the rank-1 update, conv slide direction (state rows labelled so every position is identifiable), and `l2_norm`'s epsilon on the squared norm versus the mean. It prints `yes` or `*** NO ***` for "is the rival observable" and counts a failure when it is not. The first fixture for the decay trap showed only 3.25 % apart, so the gate and the input range were changed (decay in (0.0025, 0.135], beta in [0, 1)) until the trap was clearly visible. The state layout test fills the state with `0.001*(i + 2j + 3h) - 1` so a layout mix-up yields a different number, not a plausible one. `router_top10_parity.cpp` shows the same idea for selection: all-equal logits, a 12-way tie, a dominant expert, and an assertion that the 2^-14 renormalisation clamp is unreachable (top-k sum at least k/n). Comparisons are NaN-safe (`le`/`gt` demand finite values first) after a NaN fixture once printed a perfect score. - -## 4. How a native pack is built from a GGUF - -Entry point: `python tools/iq_pack.py --gguf .gguf --out [--compat-bf16] [--experts-bin] [--skip-experts] [--base ]`. All sibling shards must exist (`Model.__init__` reads `-0000N-of-0000M`, a missing one is an error). `main()` runs `expert_layout()` first so a model that cannot be packed is refused before any file changes, then `index_standalone()`, then the tokenizer export, then writes `native_experts.txt` last. - -- **`native_experts.txt`** is the completion marker and the expert map. One line per layer: `layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard]`. `gu_type` and `d_type` are ggml type ids (gate and up must match; down may differ, e.g. IQ3_XXS gate/up with Q2_0 down). `offset` is the layer's start in the virtual `experts.bin`. `blob_bytes` is the per-expert size of gate + up + down. The last three are absolute byte offsets of the three role tensors in their GGUF shard. Header `v3`; `v4` only if one layer's roles sit in different shards (column becomes `gate,up,down`). The engine reads the experts straight from the GGUF unless `experts.bin` exists. Golden examples: `tests/data/native_experts/*.txt`. -- **`index.txt`**: "strata pack index v3", one row per non-expert tensor: `name, ?, kind, offset, bytes, arena_offset, arena_bytes, ne0, ne1, ...`. Kind 4 = BF16, 5 = F16, 2 = F32, 3 = F32 narrowed to F16 by the loader. A quantized tensor the engine serves natively from the GGUF has zero offsets and only its shape. The arena is 64-byte aligned. -- **`dense.bin`**: the float tensors the engine reads from the pack, in the form it reads them (table `FORM`: routers, hyper-connection and indexer projections, SSM gates BF16; norms, `ssm_a`, `ssm_conv1d`, `ssm_dt.bias`, `ssm_norm` F32; PLE conv F16). Exact conversions are the default (F32 whose low 16 bits are zero to BF16; F16 or BF16 widened to F32). Rounding conversions need `--compat-bf16`. Anything the engine requires in a form the GGUF does not hold, without the flag, is a hard error. -- **`conversions.json`** (schema 1): every converted tensor: shard, source and destination types, method, exact or not, max absolute error, SHA-256 of the source bytes, plus the source shard names and sizes. -- Also: `experts.bin` plus `experts.bin.src.json` (optional, only with `--experts-bin`, reuse is checked by shard sizes, the hash of `native_experts.txt` and six sampled blobs), `tokenizer/`, and `compat-bf16.json` with the flag. All files are written under `.tmp` names and renamed, so an interrupted run leaves no completion marker. - -## 5. Dependencies and GPU - -- Pack tools and `ref/load.py`: Python 3.10+, `numpy`, gguf-py from llama.cpp (the submodule's `third_party/llama.cpp/gguf-py` works through `_paths.py`; `ref/load.py` needs `PYTHONPATH` set to it). `regex` for the tokenizer export. `requirements.txt` pins numpy, jinja2, regex, pyyaml, tqdm. `psutil` for `bench_vs_llama.py`. `mtp_fetch.py` uses the standard library's HTTP client. -- **No torch, no safetensors library, no GPU** anywhere in `tools/` or `ref/`. The oracle is NumPy on the CPU. Maya's `ref/glm.py` is also NumPy; the full-attention and GDN loops are slow but small models are fine, and the synthetic GGUF keeps them fast. -- GPU is needed only to run the C++ parity binaries and the engine. -- For cross-checking, the submodule has `examples/eval-callback`, `src/models/qwen35moe.cpp`, `src/models/delta-net-base.cpp` and `convert_hf_to_gguf.py`. llama.cpp's `cb()` names in `qwen35moe.cpp` include `conv_output_silu`, `gate_sigmoid`, `beta_sigmoid` and `shared_expert_gate_sigmoid`. - -## 6. Hardcoded Flash-Next assumptions found while reading (each must be generalized or bypassed) - -- `iq_pack.py`: `FORM`/`ROUTERS` name Flash-Next tensors (`hc_*`, `indexer.*`, `ple_*`); `is_expert()` matches any `*_exps.weight`; `expert_layout()` takes `n_expert` from `blk.0.ffn_gate_inp.weight` and demands every layer to have all three expert tensors (true for qwen35moe, which has no dense-lead layers); tensors with more than two dimensions outside experts are refused; the `FORM` table has no qwen35moe entries, so SSM and attention tensors are served natively from the GGUF where quantized and copied as stored where float. Whether the engine needs `ssm_alpha`/`ssm_beta`, the router and the shared-expert gate as BF16 for the GDN and router kernels is a step 3 and 4 question; the `FORM` table is where that gets decided. `ffn_gate_inp_shexp.weight` is already in `ROUTERS`. -- `make_profile.py`: `N_LAYER = 48`, `N_EXPERT = 512`. -- `mtp_fetch.py`, `mtp_pack.py`, `mtp_rt.py`: Flash-Next tensor names, the 512-expert fused shapes, the revision pin. The Qwen3.6 MTP head comes from the MTP GGUF's `nextn` tensors per the plan. -- `gdn_parity.cpp` and `src/kernels/cuda/gdn.cu`: the out-norm is `rms_norm(o) * ssm_norm * sigmoid(z)` (`gdn.cu:148`), and the parity test's negative case asserts SiLU is the wrong reading. llama.cpp's `qwen35moe` `build_norm_gated` uses `ggml_silu(gate)`. The test's geometry is fixed at S = 128, h_k = 16, h_v = 48 against Qwen3.6's 32 v-heads. Re-pin both before reusing either. -- `tests/data/native_experts/` and `data/*.bin`: Flash-Next only. - -## 7. What to restore and what to write - -Restore into a dev checkout (copy from `/Users/robertkarl/Code/strata-upstream-6f32ec0`; a dev branch, or keep out of the fork's release tree): - -1. `ref/load.py`. -2. `tools/`: `_paths.py`, `gguf_reader.py`, `gguf_writer.py`, `iq_pack.py`, `test_iq_pack.py`, `make_profile.py`, `test_make_profile.py`, `strata_tokenizer.py`, `mtp_pack.py`, `mtp_rt.py`, `mtp_fetch.py` (for reference), `draft_vocab.py`, `iq_fixture.py`, `needle_bench.py`, `calibrate.py`, `batch_test.py`. -3. `tests/` whole (30 files), so that `-DSTRATA_BUILD_TESTS=ON` configures. `bench/micro/` cannot be restored; the CMake foreach for the llama.cpp-oracle parity tests stays dormant. -4. `requirements.txt` (numpy, regex, jinja2). -5. From upstream main only: `bench/bench_vs_llama.py`. - -Write new (nothing upstream to copy): `ref/qwen36.py`, `tools/qwen36_synth_gguf.py`, the oracle invariant tests, qwen35moe parity binaries (GDN at 32 v-heads with SiLU gating, the top-8 over 256 router with shared-expert gate, the gated full-attention layer), the layer composition test, and the streaming runner test. diff --git a/docs/upstream/DETAILS.md b/docs/upstream/DETAILS.md deleted file mode 100644 index d9484e6..0000000 --- a/docs/upstream/DETAILS.md +++ /dev/null @@ -1,1127 +0,0 @@ -# Strata - the details - -The technical side of Strata: every measured number, the API, images, all settings and how the engine works. -New here? Start with the [README](../README.md); installing step by step is in [INSTALL.md](INSTALL.md), the models in -[MODELS.md](MODELS.md), common problems in [TROUBLESHOOTING.md](TROUBLESHOOTING.md). - -> **On this page:** [Speed](#speed-measured) · [Other GPUs](#other-gpus-estimated) · [Which model?](#which-model) · -> [Requirements](#before-you-start) · [Windows](#windows) · [Linux](#linux) · [API](#using-it) · -> [MCP tools](#tools-from-mcp-servers) · [MCP server](#manage-strata-from-your-ai-assistant-mcp-server) · -> [Images](#images-vision) · -> [Troubleshooting](#troubleshooting) · [How it works](#how-it-works) - ---- - -## Speed (measured) - -RTX 5070 **12 GB**, Ryzen 5 7600 (6 cores), 64 GB DDR5-5200, Windows, engine 0.1.26 with the settings setup writes -(`--prefill auto`, 8-bit KV above 4K, KV streaming from 64K). One code-agent prompt per length, 256 generated tokens, -MTP speculative decoding on. "262K" is the model's full context window (a 259,943-token prompt). The IQ2_XS row was -measured with Swift 1.5's IQ2_XS, which runs at the original's speed. - -**Engine 0.1.36 (#136), the same PC:** Q2_0's prompt experts run on fused int8 tensor-core kernels (RTX 30 and newer): -4K 1,294 -> 1,570, 32K 2,170 -> 2,653, 128K 2,123 -> 2,468 tokens/s (+16-22%), as close to an FP16 reference as the -previous kernels (closer at 32K: teacher-forced KL 0.009 vs 0.012). The decode path's block selection and greedy -argmax run on thread-block clusters (RTX 50, sm_90+; other cards keep the previous kernels; the same tokens): Q2_0 output at 4K 89 -> 93.5, at 128K -64.5 -> 76.4 tokens/s. `STRATA_PF_FUSED=0` keeps the previous prompt kernels (byte-identical answers to 0.1.35); -`STRATA_PF_FUSED=1` also runs the native IQ packs' fused kernels (opt-in: IQ2_XS prompts +12% at 4K, +3% at 32K, the -IQ3 packs about even); `STRATA_QSA_CLUSTER=0` / `STRATA_ARGMAX_MULTI=0` turn the decode kernels off. The tables -below are 0.1.26's. - -### Prompt processing (tokens/s) - -| Model | 1K | 4K | 32K | 64K | 128K | 262K | -| --- | ---: | ---: | ---: | ---: | ---: | ---: | -| **Q2_0** | 536 | 1,299 | 2,171 | 2,126 | 2,107 | 1,304† | -| **IQ2_XS** | 534 | 1,256 | 2,092 | 1,754 | 1,752 | 1,181*† | -| **IQ3_XXS** | 482 | 1,007 | 1,745 | 1,609 | 1,602 | - | -| **IQ3_S** | 427 | 913 | 1,624 | 1,640 | 1,443 | - | -| **Coder** | 656 | 1,583 | 2,177 | 2,236 | 2,208 | 1,034** | - -Engine 0.1.26; `bench/results/2026-09-29-speed-0126`. At 32K-128K that is 8-28% faster than 0.1.22. † not measured -again: 0.1.22. \* measured with images on (the image encoder's VRAM reserve leaves fewer experts cached). \*\* not -measured again: 0.1.14. - -### Output (tokens/s) - -| Model | 1K | 4K | 32K | 64K | 128K | 262K | -| --- | ---: | ---: | ---: | ---: | ---: | ---: | -| **Q2_0** | 87.3 | 93.0 | 81.8 | 76.2 | 73.7 | 60.3† | -| **IQ2_XS** | 79.6 | 78.6 | 76.3 | 63.7 | 62.7 | 52.8† | -| **IQ3_XXS** | 61.9 | 61.6 | 58.5 | 57.2 | 49.0 | - | -| **IQ3_S** | 52.4 | 53.3 | 48.3 | 46.3 | 45.5 | - | -| **Coder** | 58.9 | 55.1 | 54.9 | 53.2 | 43.0 | 42.8† | - -Engine 0.1.26, the same runs. † not measured again: 0.1.14. - -Output speed depends on the text as well: speculative decoding runs faster when more of the drafted tokens are -accepted, so a different answer to the same prompt moves it by several percent. Run back to back on the 4K prompt, -0.1.14 writes 88.5 tokens/s and 0.1.12 85.7. The numbers before 0.1.13 (prompts about half as fast): -[`bench/results/2026-09-24-final`](../bench/results/2026-09-24-final/matrix.md); these: -[`bench/results/2026-09-28-speed-0114`](../bench/results/2026-09-28-speed-0114/README.md). - -IQ3_XXS and IQ3_S at 262K are not measured: with their 43 / 50 GB of experts, a 260K-token context brings a 64 GB PC -to its memory limit by setup's estimate (the experts + the context's KV cache + 24 GB), so setup recommends up to 128K -with them on 64 GB. A longer context you choose (`--context 262144`, or a pick in its list) is kept, with a note: users -ran IQ3_S at 256K on 64 GB with RAM to spare (#406). In the low-RAM mode the KV cache stays in VRAM and the context -does not count against RAM. IQ3_S (engine 0.1.4 or newer) is only published for the original model, not for Swift 1.5. - -**KV streaming (engine 0.1.5):** at 64K and more, setup keeps the context's KV cache in RAM and only the part the -attention reads in VRAM (`--kv-resident 32768`), so more experts fit on the GPU. Q2_0 at 262K: 50.9 -> 62.6 tokens/s -(1,589 -> 3,872 experts in VRAM); at 128K about +6%. The attention reads exactly the same values (only where the KV lives changes); it -costs ~13.7 KB of RAM per context token (1.7 GB at 128K). Existing installs: run `START-HERE.bat --setup` once to turn -it on. Setup turns it on when the RAM has room for it; `--kv-streaming on|off` overrides that (on past the RAM test with a -note; never with `--kv k8v4` or under WSL, which cannot stream). - -**4-bit KV cache (engine 0.1.8, optional):** `START-HERE.bat --setup` asks above 8K context (or pass `--kv q4_0`). It -halves the KV cache's memory with a Hadamard rotation before 4-bit rounding (PR #21), about 4% faster at 128K, but it -is measurably less precise on long documents (perplexity +8-12%; needle tests still pass). 8-bit stays the default. -Details: [`bench/results/2026-09-27-kv-q4`](../bench/results/2026-09-27-kv-q4/README.md). - -**Hybrid K8V4 KV cache (engine 0.1.25, optional, PR #120):** `--kv k8v4` (`START-HERE.bat --setup --kv k8v4`) keeps -the keys at 8 bits and stores the values as rotated 4-bit: 23% less KV memory than 8-bit, so more experts fit in -VRAM. RTX 3090, the Coder at 198K context: 99 instead of 85 tokens/s output, the same needle results, prompts 2-5% -slower. It does not stream its KV cache (KV streaming is on by default from 64K), so it pays off mostly on large -cards at long contexts. - -**Reproducible greedy output (0.1.30, opt-in, `STRATA_IQ_MT_MIN=1`):** with the IQ models, the CPU computes an -expert for one token with ggml's dot product and for several tokens with Strata's multi-token kernels, which round -slightly differently. How many tokens share an expert depends on the drafts in a verify window, so the same prompt -at temperature 0 can end in a different (equally good) answer when the drafting, the cache state or a resumed -conversation differ (issue #152). `STRATA_IQ_MT_MIN=1` (in the config's `env`) uses the multi-token kernels for -every group: the answer then no longer depends on the drafting. Measured on a Ryzen 7600 (AVX-512): IQ3_S decode --1..-3%, the other models the same; the default stays the fastest rule. Through the server, two more things carry -over from one request to the next (#410): the adaptive tier moves experts between RAM and VRAM (the GPU and the CPU -round an expert differently), and the prompt cache resumes a repeated prompt and reads only its tail through the -decode path. For byte-identical repeats add `--prompt-cache 0 --adapt-swaps 0 --pcie-frac 0` to the engine's args -as well (#410): the PCIe share of the missed experts (computed on the GPU instead of the CPU) still made the first -answer after a start differ from the next ones. Measured here (IQ3_XXS, a 3.6K-token prompt, 4 repeats): with all -three switches 1 answer of 4, without `--pcie-frac 0` 2 of 4 (the first one differs), with the defaults 2 of 4. -`--pcie-frac 0` costs decode speed (the missed experts all run on the CPU), so keep it for A/B runs. - -**The draft layer's tokens (0.1.27, `--draft-vocab`):** the MTP draft layer can only propose tokens from a subset -of the vocabulary (`mtp/rt/draft_vocab.bin`). Since 0.1.27 the subset includes every Chinese, Japanese and Korean -token (106,299 ids), so answers in those languages are 15-38% faster (Q2_0, RTX 5070). Its head takes ~180 MiB of -VRAM, which the expert cache leaves free for it (0.1.28). `START-HERE.bat --setup --draft-vocab en` keeps the -English/code subset from before (40,525 ids, ~110 MiB less VRAM, English answers 1-2% faster; CJK answers get -almost no drafts). `--draft-vocab cyrillic` takes the English/code subset plus the whole Cyrillic script (58,963 -ids): the shipped subsets hold 142 of the vocabulary's 18,580 Cyrillic tokens, so Ukrainian or Russian answers got -1.4 tokens a round; with it 2.1, and 83 -> 109 tokens/s (RTX 5090, the NVFP4 fork), English unchanged. -`--draft-vocab fr` (0.1.39, #597) takes the English/code subset plus the 5,686 tokens that cover 99% of a French -Wikipedia corpus (46,211 ids, `tools/draft_vocab.py --corpus`): 23.6% of French text's tokens were outside the -English/code subset, 0.7% are outside this one. Drafts accepted in French answers 0.51 -> 0.60 (IQ3_XXS, RTX 5070, -8 prompts x 2 passes; English 0.61 -> 0.63 and code 0.77 -> 0.78, no loss), and 141 -> 158 tok/s in French on an -RTX 5090 (IQ3_S, the reporter's measurement). -`tools/draft_vocab.py` builds and inspects subsets. When the start stops with "the draft head does not fit" (a -12 GB card with a long context, #474), the engine says how much the head needs, how much VRAM is free and which -smaller subset fits, and the server's start error repeats it; setup suggests `--draft-vocab en` on cards under -14 GB (only a suggestion: nothing changes unless you pass it). - -**Low-RAM mode (engine 0.1.26, chosen by setup):** normally all of a model's experts are copied into RAM (23-50 GB, -pinned) and the GPU holds a copy of the most-used ones. On a PC whose RAM cannot hold them beside the system (the -experts plus ~10 GB), setup instead maps them from one file in the model's folder (`--mmap-experts`, the pack's -`experts.bin`, +23-50 GB of disk). The OS file cache holds what the GPU does not, and it can give that memory back. -On the Coder the engine's committed memory drops from 36 to ~13 GB, with the same answers. With a big GPU (an RTX -5090 holds all of the Coder's experts, most of Q2_0's) it runs at nearly the usual speed. With a small one, most -experts come from the SSD and it is much slower (setup says so). `START-HERE.bat --setup --low-ram on|off` overrides -the choice. - -**Low-RAM mode, resident (engine 0.1.30):** when the experts the GPU does not hold fit the RAM (with the same ~10 GB -beside them), setup picks the resident variant instead (`--resident-experts`): at start the engine copies exactly those -experts from `experts.bin` into RAM (page-locked when the driver allows, else locked in RAM), so while it answers -nothing is read from the SSD, however little RAM the OS leaves for its file cache. Examples with setup's context: a -32 GB PC with a 24 GB GPU runs Q2_0, IQ2_XS and the Coder this way (~16-18 GB of experts in RAM, the GPU holds the -other ~18 GB), a 32 GB PC with a 12-16 GB GPU the Coder; IQ3_XXS on a 32 GB PC stays mapped. The details: -- The prompt path borrows room in the GPU's expert cache for its buffers and puts those experts back after the prompt; - as far as the RAM allows, their experts are kept in RAM too (so a prompt reads nothing from the SSD either). -- The cache still follows the conversation (`--adapt-every`): a swap copies the evicted expert back from VRAM into the - RAM place of the one that replaces it, so the RAM copy keeps holding exactly what the GPU does not. -- The answers are the plain mapped mode's for the same expert placement: the bytes are the file's. With a page-locked - copy the GPU also takes its usual share of the misses over PCIe (`--pcie-frac`), as with enough RAM; `--pcie-frac 0` - (or `STRATA_RESIDENT_PIN=0`) gives the mapped mode's exact tokens. -- The engine leaves 4 GB of the RAM it finds free (`STRATA_RESIDENT_HEADROOM_GIB`); when even the experts the GPU does - not hold do not fit, it says so and runs the plain mapped mode. The server log shows, per request, how many expert - reads went to the file (`resident RAM: ... blob reads from the file`: 0 in steady use). -- `--low-ram resident|mmap` forces one variant (also on a PC with enough RAM, e.g. to try it). -- Several GPUs (#364, #384): setup recommends one GPU in the low-RAM mode (the resident variant has no layer split - yet), and asks; `--gpus 0,1` (or answering 2) shares the model across them with the mapped variant - (`--mmap-experts`): the cards together hold more of the experts, and two users measured it 1.3-1.6x faster than - one card, but the OS file cache can fill the RAM to 0 free during long prompts. `--yes` keeps one GPU. A config - with `--resident-experts` started with `--gpus` switches to `--mmap-experts` with a note, and the engine runs that - pair as `--mmap-experts` with a warning instead of refusing it. - -**A mapped arena for small RAM (Linux, opt-in, 0.1.39, PR #640):** `STRATA_ARENA_MMAP=1` maps a native pack's expert -arena read-only from the pack's `experts.bin` instead of reading it into locked RAM, for a PC whose GPUs hold most -experts but whose RAM is small (2x 16 GB GPUs with 32 GB of RAM: ~1 GB -> 25 GB available while serving). The first -start writes `experts.bin` (when the drive has room for it), later starts map it; the pages of the experts a GPU holds -are handed back to the OS. Run it with `--pcie-frac 0` (the GPUs get no mapped alias). Without the variable nothing -changes. - -**Low-RAM mode without `experts.bin` (engine 0.1.31):** for the native packs (IQ2_XS, IQ3_XXS, IQ3_S, the Coder, Swift, -Q2_0 packed by `tools/iq_pack.py`; not the canonical Q2_0 pack setup makes for AVX-512 CPUs) the mapped mode no longer -needs the pack's `experts.bin`: when the pack has none, the engine -maps the model's GGUF files themselves and reads each expert's gate, up and down rows from where `native_experts.txt` -says they are (the files are checked against it first: every tensor's name, type, shape, offset and bounds). That -saves the 23-50 GB copy on the disk. The answers are the same: on the Coder, 64 greedy tokens from `experts.bin` and -from the GGUF gave identical tokens and logits. An expert read from the GGUF is three reads instead of one, so the -engine fetches a layer's missing experts on 8 threads (`STRATA_FETCH_THREADS`) with one batched page request -(Windows `PrefetchVirtualMemory`). With an `experts.bin` in the pack, nothing changes. Setup does not use this yet. - -**A RAM budget (engine 0.1.31, `--resident-budget-gib N`):** the resident variant for a model whose experts do not all -fit: the N GiB of experts the GPU cache does not hold that the expert profile ranks hottest are copied into RAM at -start (locked; page-locked when the driver allows the whole budget), and the rest are read from the files through the -OS file cache. It implies `--mmap-experts` and leaves 4 GB of free RAM (a larger N is clamped to that less 256 MiB, -with a message; #403: a clamped budget no longer fails the safety check that follows, and a budget that cannot be -kept at all is a warning, with every expert read from the files). Setup sets N with `--resident-budget-gib N`. With -the GGUF read in place it also warms the next layer's likely experts: while the CPU works on a layer, a thread applies -the next layer's router to this layer's input and asks the OS for the pages of the predicted experts that neither the -GPU nor the RAM budget holds (only pages - the experts computed are the same; `STRATA_LOOKAHEAD=0` turns it off). This -is what runs [Unsloth's UD-Q4_K_XL](UNSLOTH_Q4.md) (72 GiB of experts) on a 64 GB PC: 7-8.5 tokens/s at N = 40 on an -RTX 5070, against ~3 tokens/s before these changes. - -**How much came from where:** with `--stats` the engine prints the tiers of the decode (`expert tiers`: blobs from the -RAM copy, blobs and MB from the files, the time spent reading them; `routing prefetch`: how many of the file reads had -been warmed). The server log has the same per request (`expert tiers: GPU ... hits ...; RAM ... blobs, files ... -blobs ... MB read`), and `GET /metrics` lists `ram_blobs`, `file_blobs` and `file_mb` for each recent request (with -engine 0.1.31 or newer). It also lists each request's speculative drafts, `drafts_offered` and `drafts_accepted` -(`null` when the engine did not report them), and their sums since the server started in `totals` (#457). -Its `hit_rate` is the VRAM share of the experts looked up while answering: experts the GPU reads over PCIe -(`--pcie-frac`) are not in it, so a higher `--pcie-frac` raises it even when decoding gets slower. `pcie_share` -(engine 0.1.39 or newer, #588) is their share of all routed experts, and the server log and the Monitor tab show it -beside the hit rate. - -**Where a decode window's time goes (profiling, #610):** start the server with `STRATA_DECODE_TIMING=1` (and -`STRATA_VERIFY_PROFILE=1` for the GPU's side) in the environment. After each request the engine log then has one -`strata decode timing:` line - windows, tokens per window, and per window the verify time split into the wait for the -GPU, the CPU expert pool (plan, activation quantization, jobs) and the stage, plus commit and draft - and one -`strata decode GPU stages (ms/window):` line with the GPU time of each stage (GDN and QSA layers, the VRAM expert -hits, the router, the head, ...). The GPU profile times every stage with events, so it slows the decode a little: -use it to compare, not to measure speed. This works with every pack; `--gpu-stages` (a one-token replay of -per-layer graphs) refuses a native (IQ) pack, which has no such graphs. - -Time to first token is prompt length / prompt speed: with Q2_0 about 4 s at 4K, 25 s at 32K, under 2 minutes at 128K -and 4.5 minutes at 262K (engine 0.1.13 made long prompts about twice as fast, below). - -**Faster prompts (engine 0.1.13):** the prompt is read in chunks of up to 8,192 tokens instead of 2,048 (`--prefill -auto`: the largest chunk whose buffers fit in the expert-cache slots it borrows, and a request borrows only what its -prompt needs); the experts are multiplied by llama.cpp's quantized MMQ kernels instead of being expanded to FP16 -first; the next layer's experts stream over PCIe while the current layer's attention runs; the PLE block runs for the -whole chunk at once; unpinned experts are copied by helper threads. Measured on the RTX 5070 12 GB, 64 GB RAM, -32K-token prompt: Q2_0 572 -> 1,290 tokens/s, IQ3_S 383 -> 1,208. Through the server (Q2_0, 128K context): 999 tokens -353 -> 438 tokens/s, 6,927 tokens 529 -> 1,077, 28,584 tokens 584 -> 1,249. Output speed is unchanged. Needles 5/5 -(1K-262K). Details and the quality check: -[`bench/results/2026-09-28-prefill-speed`](../bench/results/2026-09-28-prefill-speed/README.md). Existing installs -switch to `--prefill auto` the next time START-HERE / setup.sh starts them. The raw numbers: -[`bench/results/`](../bench/results/). The [paper](paper/Strata-Paper.pdf) explains every number. - -## Other GPUs (estimated) - -Not measured - estimated from the runs above (same CPU and 64 GB RAM): the GPU part scaled by memory bandwidth, the CPU -part by how many more experts the card's VRAM holds. Treat as **±20%**. Numbers are *prompt / output* tokens/s. -The prompt figures predate engine 0.1.13, which about doubled prompt speed on the measured card; how much of that a -card gains depends on its PCIe link (the experts stream over it), so they are still the older estimates. - -| GPU | Model | 1K | 4K | 32K | 64K | 128K | 262K | -| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | -| RTX 5060 Ti 16GB | Q2_0 | ~341 / ~80 | ~472 / ~87 | ~501 / ~81 | ~492 / ~72 | ~476 / ~62 | ~435 / ~53 | -| | IQ2_XS | ~291 / ~80 | ~406 / ~77 | ~434 / ~63 | ~426 / ~62 | ~413 / ~51 | ~383 / ~47 | -| | IQ3_XXS | ~249 / ~66 | ~359 / ~65 | ~381 / ~56 | ~374 / ~54 | ~363 / ~45 | - | -| RTX 3090 24GB | Q2_0 | ~355 / ~128 | ~491 / ~140 | ~521 / ~130 | ~512 / ~115 | ~495 / ~100 | ~453 / ~85 | -| | IQ2_XS | ~303 / ~131 | ~422 / ~128 | ~451 / ~103 | ~444 / ~102 | ~430 / ~85 | ~398 / ~78 | -| | IQ3_XXS | ~260 / ~106 | ~374 / ~103 | ~396 / ~89 | ~390 / ~85 | ~378 / ~71 | - | - -More VRAM matters more than a faster GPU: every extra GB holds ~700 more experts, and every expert on the GPU is one the -CPU does not have to compute. A 3090's 24 GB takes most of the CPU work away. (Since 0.1.14 the expert profile ranks -all 24,576 experts; before, the cache stopped at 8,000, about 10-14 GB. `tools/make_profile.py` builds a profile from -your own prompts: run the engine once with `--dump-routing trace.bin`, see the tool's help. The shipped profile already -ranks every pair, so a trace only changes the order with `--reorder` (0.1.39, #587): your trace's pairs first, then the -base's, then the rest.) - -## Which model? - -All three are [ISTA-DASLab's GSQ-RCO quantizations](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF) -of [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next). - -| Model | Download | RAM it uses | Speed | Quality | -| --- | ---: | ---: | --- | --- | -| **Q2_0** | 66 GB | ~34 GB experts + ~6 GB | fastest | good | -| **IQ2_XS** | 68 GB | ~36 GB experts + ~6 GB | close to Q2_0 | a bit better | -| **IQ3_XXS** | 76 GB | ~43 GB experts + ~6 GB | slower (more CPU work) | best | - -With 64 GB of RAM all three fit (close the browser for IQ3_XXS, and keep its context at 128K or less). With 48 GB only Q2_0 / IQ2_XS may fit. With 32 GB: the Coder (below). - -### Or: the Coder (half the experts, for code) - -**[Qwen3.8-Flash-Next GSQ-RCO Coder](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF)** is -ISTA-DASLab's expert-pruned release: 256 of each layer's 512 experts are kept (still 10 active per token), chosen with -RCO on code, agentic and vision calibration data; its authors report 91.3% of the full model's SWE-bench Verified and -98.7% of LiveCodeBench v6. One size, named IQ1_M for its 1.89 bits per *original* parameter; the kept experts are -stored like IQ3_S (IQ2_S-IQ4_XS gate/up, IQ4_NL/Q2_0 down). Shard 1 is 29.6 GB (experts: 23 GB of RAM), so it runs -on **32 GB of RAM**, and at 262K on 64 GB. Its shard 2 and its vision encoder are the original's files: with the -original installed, setup downloads only shard 1. Strata ships its expert profile (`data/expert-profile-coder.bin`, -the shipped ranking mapped onto the kept experts through the release's `rco-allocation.txt`: 72% of the expert -reads hit the GPU on a 12 GB card). Images work; the experimental speed projection loads and runs on it (it was made -for the full model). - -``` -START-HERE.bat --setup --family coder -``` - -### Or: Swift 1.5 (a fine-tune that thinks shorter) - -The setup's first question also offers **[Swift 1.5](https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF)**, -UkisAI's fine-tune of Qwen3.8-Flash-Next, trained to reach the answer with much less thinking (its authors: 63% fewer -thinking tokens, 1.8x sooner answers, under 1% accuracy loss). Same architecture, the same three sizes, its own -vision encoder; Strata runs it at the same speed (4K, IQ2_XS: 465 prompt / 78.7 output tokens/s, vs 467 / 78.3 for -the original). Its authors recommend **IQ2_XS** (their Q2_0 is marked experimental). Its license is the Swift Open -License 1.0 - read it on the model page. - -Our small check (8 reasoning questions, default thinking, IQ2_XS): both models got **8/8**; Swift used **1,234** -output tokens in 28 s, the original **2,682** in 46 s - most of the difference from one question the original -thought about for 1,524 tokens. Not a benchmark, but consistent with the claim. - -``` -START-HERE.bat --setup --family swift --model IQ2_XS -``` - -### Experimental: Unsloth's UD-Q4_K_XL - -A 4-bit quantization of the same model (111 GB, 72 GiB of experts). Setup offers it from engine 0.1.32 -(`--family unsloth --model UD-Q4_K_XL`: a RAM budget of your RAM less 24 GB, the rest read from the SSD); what it -does and the manual workflow are in **[docs/UNSLOTH_Q4.md](UNSLOTH_Q4.md)**. On a 64 GB PC with a 12 GB RTX 5070 it writes 7-8.5 -tokens/s, most experts read from the SSD; it picks the same tokens as llama.cpp on the same file at 97.5-99% of -the positions of short greedy answers, 90-91% after a 16K prompt, differing mostly at near-ties -([measured](UNSLOTH_Q4.md#quality-against-llamacpp-on-the-same-file)). - -## Before you start - -You need **only a graphics driver**: NVIDIA 580 or newer (update it with the NVIDIA App or from -[nvidia.com/drivers](https://www.nvidia.com/drivers)), or for AMD the one in [INSTALL.md](INSTALL.md#what-you-need). -Everything else is installed for you the first time. - -| | | -| --- | --- | -| GPU | NVIDIA **RTX 20, 30, 40 or 50 series**, **12 GB VRAM or more** (8 GB runs, slowly). Measured on an RTX 5070 and an RTX 3090; RTX 20 (Turing, since 0.1.27) was tested by a contributor on an RTX 2070. Or AMD **Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT, Radeon AI PRO R9700, RX 6800 / 6900 series**: [AMD_HIP.md](AMD_HIP.md). | -| RAM | **64 GB** recommended (see the table above). | -| CPU | x86-64 with AVX2 (any Intel/AMD desktop CPU from the last ~8 years). AVX-512 (Ryzen 7000/9000) is a bit faster. Older CPUs without AVX2 are experimental and slow: [Older CPUs](INSTALL.md#older-cpus-experimental). | -| Disk | ~70-80 GB free for the model, ~6 GB for the MTP layer (+1 GB with images). **Q2_0 on an AVX-512 CPU** also writes a one-time ~40 GB pack for the fast CPU kernel (34 GB of experts in its layout, plus the dense weights). An NVMe SSD is strongly recommended. | -| OS | Windows 10/11, or Linux (Ubuntu 22.04/24.04 get everything installed automatically). | - -What the first start installs: in this folder `.venv/`, `engine/` and `third_party/`; the model files (`models/`, -`packs/`, `mtp/`, 70-120 GB) in **`Strata-data` next to this folder**, so a new copy of Strata (an update unzipped -elsewhere) finds them and sets itself up the same way. The place is remembered per user (`%APPDATA%\Strata\settings.json`, -`~/.config/strata/settings.json`); `--data-dir` chooses another. Installs from before 0.1.16 are moved there by the next -start (a rename on the same drive; files on another drive are used where they are). -Python 3.12 if you have none (for your user account, no admin), a private Python environment, NVIDIA's CUDA libraries -(from pip, ~0.4 GB), the ready-made Strata engine for RTX 20/30/40/50, the model and the MTP draft layer. If no -ready-made engine fits your PC, it offers to install the build tools (Visual Studio Build Tools + CUDA Toolkit on -Windows, `build-essential` + CUDA on Ubuntu) and compiles the engine for your GPU (asks first; 20-40 minutes once). - ---- - -## Windows - -### Double-click `START-HERE.bat` - -**The first time** it asks four questions and does the rest: - -1. **Which model?** Qwen3.8-Flash-Next (the original) or Swift 1.5 (the fine-tune that thinks shorter). -2. **Which size?** Q2_0, IQ2_XS or IQ3_XXS (it recommends one for your RAM). -3. **How much context?** 8K to 256K tokens (it recommends one for your VRAM). -4. **Images?** yes / no (see [Images](#images-vision)). - -Then it downloads and prepares everything (the model is 66-76 GB, so the first start takes a while; an interrupted -download continues where it stopped) and **starts the model**: your browser opens `http://127.0.0.1:8080`, the Strata -app. It has three tabs: -- **Chat:** streaming answers, the model's thinking (folded away once it answers), code with a copy button, pictures when - images are on, and sampling and thinking-level settings. Chats stay in your browser. -- **Monitor:** what the model is doing (reading the prompt, with progress, or writing, at how many tokens/s); GPU load, - VRAM, temperature, power and PCIe traffic; CPU, RAM and disk; the context in use; the last requests. -- **About:** the model and engine settings, and the addresses to connect other apps. - -`http://127.0.0.1:8080/?q=your question` opens it with a new chat already asking. The API is at -`http://127.0.0.1:8080/v1` for your apps. - -**Every time after that**, `START-HERE.bat` just starts the model (30-90 s to load 34-43 GB into RAM). Nothing is -downloaded again. Closing the window stops the model. - -``` -START-HERE.bat --setup install another model, or change context / images -SETUP.bat the same (double-click it) -START-HERE.bat --model IQ2_XS --context 32768 --vision yes --yes no questions -START-HERE.bat --gguf-dir D:\models\IQ2_XS use GGUF files you already have -START-HERE.bat --data-dir E:\Strata-data keep the model files somewhere else -START-HERE.bat --port 8081 another port -START-HERE.bat --gpu 1 another GPU (numbered as nvidia-smi; setup picks the one with the most VRAM) -START-HERE.bat --calibrate tune the engine for this PC (about 5-10 minutes), then start -``` - -With more than one model installed, it asks which one to start. `run-.bat` starts a model directly. - -**Tuning for your PC (`--calibrate`, engine 0.1.19).** Three engine settings depend on the PC more than on the model: -- the share of the experts missing from VRAM that are copied to the GPU instead of computed by the CPU - (`--pcie-frac`: a fast PCIe link and a slower CPU want more, a laptop's narrower link less); -- how sure the draft layer must be to add another guess to a check (`--spec-min-p`); -- how many CPU threads compute experts (`--pool-workers`: on CPUs with efficiency cores, fewer can be faster). - -The defaults were measured on a Ryzen 5 7600 with an RTX 5070. Setup offers to measure them on your PC after an -install; `START-HERE.bat --calibrate` (Linux: `./setup.sh --calibrate`) does it any time. It measures the output -speed with each setting and keeps one only when it is more than 3% faster. The result is remembered per PC and model -(in the settings file next to the data folder's record), so updates keep it. - -### Running it at startup (Task Scheduler) - -To have the model up at logon, people start the serve from **Task Scheduler** (or a service). Beware: Windows -throttles such contexts, and the model's ~40 GB expert load then crawls at **~0.05 GiB/s (13-14 minutes)** -instead of **~1.4-1.5 GiB/s (~35 seconds)** - a 24x slower start. Measured on an RTX 5070 Ti + Ryzen 7 9800X3D -+ NVMe, same binary, same args, same cache state: - -| How the serve starts | Expert load | -| --- | ---: | -| Double-click / terminal / SSH | 1.42-1.52 GiB/s (~35 s) | -| Task Scheduler with its defaults | 0.05 GiB/s (821-841 s) | -| Task Scheduler with the two settings below | 1.42 GiB/s (35 s) | - -In the task's properties set both of these (the defaults are the opposite): - -- **Priority level: Normal** (Options tab; the default is Below normal), and -- **Run with highest privileges** (General tab; without it the task runs with a limited user token - which - also strips `SeLockMemoryPrivilege`, the privilege Windows large pages need). - -(Both were changed at once, so the isolated effect of each is not measured.) If the model still starts -slowly, the engine prints a hint under its `loaded ... GiB at ...` line naming this cause. - -### Chat in the terminal (optional) - -``` -.venv\Scripts\python chat.py -``` - ---- - -## Linux - -```bash -./setup.sh -``` - -The same questions, the same automatic install (it uses `sudo apt` for Python and, only if it has to compile, -for the build tools), and the same start: `http://127.0.0.1:8080`. Later runs of `./setup.sh` (or `./run-.sh`) -start the model directly. Options as on Windows (`./setup.sh --setup`, `--model Q2_0 --yes`, `--gguf-dir /data/Q2_0`). -Terminal chat: `.venv/bin/python chat.py`. - -- **Updating:** `git pull`, then `./setup.sh`: it compiles the engine again when its source changed (a minute or - two for the changed files). If that compile fails, it says so and starts the engine you had. -- **Other distributions** (Arch, Fedora, ...): install the C++ compiler and the CUDA Toolkit 13 with your package - manager first (Arch: `sudo pacman -S base-devel cuda`); setup finds `nvcc` on PATH, in `/usr/local/cuda*` and in - `/opt/cuda*`, and does the rest. -- **WSL** works (Ubuntu 24.04 tested), with one limit: the NVIDIA driver pins only about 1 GB of RAM there, so KV - streaming (`--kv-resident`) is off and the KV cache stays in VRAM, and the experts are copied to the GPU from - unpinned RAM (slower prompts than native Linux). - ---- - -## Sharing the GPU with other programs (optional) - -By default the model stays loaded until you close Strata. On a PC that also games, renders or runs another model -server, three server options (all off by default; also as keys in `strata-.json`) give the VRAM back: - -| Option | Config key | What it does | -| --- | --- | --- | -| `--idle-unload 600` | `"idle_unload_s": 600` | unload the model after 600 s without requests; the next request loads it again | -| `--min-free-vram-mib 11000` | `"min_free_vram_mib": 11000` | load an unloaded model only when that much VRAM is free (it waits up to 15 s for memory being given back), else answer **503** "the GPU is in use by another program" instead of starting into what a game left (with several GPUs it checks the first one) | -| `--before-load "cmd"` | `"before_load": "cmd"` or `["cmd", "arg"]` | a command run before the model is loaded again, e.g. one that unloads another server's model | - -`POST /unload` unloads it now (`409` while a request is running) and `POST /load` loads it ahead of a request (both -with `Content-Type: application/json`, e.g. `curl -X POST -H "Content-Type: application/json" localhost:8080/unload`); -`/health` says `"loaded"`, `/v1/models` lists it as `unloaded` (like llama.cpp's router), `/props` sets -`is_sleeping` and the Monitor shows the state. Unloading ends the engine process - and the image encoder, when images -are on; it is started again first, as at a start - so their VRAM and RAM go straight back. The model files stay in -the OS file cache, so loading again takes seconds while that RAM is not needed elsewhere. Measured on an RTX 5060 Ti -16 GB with Q2_0 in the low-RAM mode: unloading takes ~0.3 s, and a request to an unloaded model answered after -4.6 s (text) or 14.7 s (a picture, image encoder on the CPU). - -**Giving part of the VRAM back while it keeps serving (#533, opt-in, one NVIDIA GPU).** With `"vram_elastic": true` -in the config (the engine flag `--vram-elastic`), the expert cache is allocated in 512 MiB segments -(`"vram_segment_mib"`), and `POST /v1/vram` with `{"reserve_mib": 8000}` shrinks it between requests until that much -VRAM is free for another program; `{"reserve_mib": null}` grows it back towards its full size, keeping the reserve -the engine started with (`--vram-reserve-mib`), and `{"reserve_mib": 0}` takes all of it back. A request that is -running finishes first. The experts of the segments given back are computed on the CPU, like any expert outside the -cache, so answers keep coming, slower; growing back puts the same experts in the same slots. Nothing resizes on its -own. Not with a layer split, the helper caches, `--peer-device` or the resident low-RAM mode. Measured on an RTX 5070 -12 GB with Q2_0 (4.8 GiB cache): `{"reserve_mib": 6000}` took 78 ms and freed 4.3 GiB (the cache keeps 0.5 GiB for -the prompt path), decode 44 -> 33 tok/s; growing back took 92 ms and the answers were token for token the ones before -the shrink. Without the flag nothing changes (the same answers as without it). - -**Keep what the expert cache learned across restarts (opt-in, engine 0.1.36, #477):** a start fills the GPU's expert -cache from the shipped profile, and the adaptive tier (`--adapt-every`) then moves in the experts your requests use. -With `"expert_profile_save": "expert-profile-learned.bin"` in `strata-.json` the engine saves that as a -profile - the experts in VRAM first, then the routing it counted since the start, then the shipped order - on a -clean exit and every 10 minutes between requests (`"expert_profile_save_every": 5` for another interval, `0` for -exit only), written to a temporary file and renamed, so a crash never leaves half a file. The next start begins from -it instead of the config's `--expert-profile` when it is a profile of the same model (else from the config's, as -before). A relative path is in the Strata folder; one file per model, and a profile per project works the same way -(point the key at another file). The file is a fingerprint of what you used the model for: it stays on your PC. -Without the key nothing is counted or written. Setup rewrites the config when run again: add the key again then. - ---- - -## Using it - -The server listens on `http://127.0.0.1:8080` (change with `--port` in setup, or edit the run script). - -| API | Endpoint | -| --- | --- | -| OpenAI Chat Completions (stream and non-stream, tools) | `POST /v1/chat/completions` | -| Anthropic Messages (stream and non-stream, tools) | `POST /v1/messages` | -| OpenAI Responses (stream and non-stream, tools; stateless, [below](#the-responses-api-and-codex-cli)) | `POST /v1/responses` | -| Model list / health | `GET /v1/models`, `GET /models`, `GET /health` | -| Model properties | `GET /props` (also accepts `?model=`) | -| What the model is doing right now | `GET /status`, `GET /slots` (single slot, busy or idle) | -| Everything the Monitor tab shows (engine, live state, last requests, hardware) | `GET /metrics` | -| The MCP servers, their state and tools ([below](#tools-from-mcp-servers)) | `GET /mcp` | - -`/models` and `/v1/models` list only the loaded model, with its context limit and input modalities. `/props` exposes the original chat template, context limit, configured generation defaults (shared settings take precedence), model path and engine version when available. Context means the full engine context, not the resident KV window. `n_predict: -1` means no fixed output cap. Unconfigured sampling fields are omitted. `autoload` has no effect; an unknown `model` returns 404. These metadata endpoints and `/slots` require the API key when one is configured. They do not load, unload or restart models. - -```bash -curl http://127.0.0.1:8080/v1/chat/completions -H "Content-Type: application/json" -d '{ - "model": "strata", "messages": [{"role": "user", "content": "Write a haiku about GPUs."}], "max_tokens": 512 }' -``` - -```python -from openai import OpenAI -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="none") -r = client.chat.completions.create(model="strata", messages=[{"role": "user", "content": "Hello!"}]) -print(r.choices[0].message.content) -``` - -- **Thinking levels: none, low, medium, high.** The model thinks before it answers (streamed as - `reasoning_content`, Anthropic: `thinking` blocks). Choose how much per request - in the chat page (the "Thinking" - menu), in `chat.py` (`/think low`), or over the API: - - | API | how | - | --- | --- | - | OpenAI | `"reasoning_effort": "none" \| "low" \| "medium" \| "high"` (also `"reasoning": {"effort": ...}`, or `"chat_template_kwargs": {"enable_thinking": false}`) | - | Anthropic | `"output_config": {"effort": "low" \| "medium" \| "high"}`, `"thinking": {"type": "disabled"}`, or `"thinking": {"type": "enabled", "budget_tokens": N}` (under 2K = low, under 8K = medium, more = high) | - - Without a setting the model uses its own default, **high**. `none` answers at once (fastest); `low` keeps the thinking - short. The levels are instructions the model was trained with, not a hard token limit: on easy questions all three - think briefly, on hard ones `high` thinks longest and is most accurate. -- **A hard thinking budget (opt-in).** `"reasoning_budget_tokens": N` in a request (OpenAI or Anthropic) caps the - thinking at N tokens: when it gets there the server ends it with a short wrap-up line and ``, and the model - answers from there (the engine continues from what it already holds, so nothing is read again). The wrap-up is - part of the thinking the client sees and counts as output tokens. `"reasoning_budget_tokens": N` in - `strata-.json` sets it for every request; a request's own value wins, and `0` means no budget. Off by default; - Anthropic's `"thinking": {"budget_tokens": N}` still only chooses the level, as above. -- **A reply stuck on one token is ended (0.1.39, #606).** When a reply repeats the same token 256 times in a row, the - server ends it there with `finish_reason` `"length"` and says so in its window: a model in a loop, or a broken - state that answers one token forever (#606 saw 36,689 tokens of `!`). `"repeat_stop_tokens": N` in - `strata-.json` sets the run length; `0` turns it off (for a request that really wants one token many times). -- **Changing the effort without re-reading the prompt (opt-in, 0.1.39, #458).** The effort's instruction is the - first thing in the prompt, so a request that only changes the effort (an agent's "think harder" switch, `none` for - a quick tool step) reads the whole conversation again. `"effort_position": "end"` in `strata-.json` renders - every request's prompt start as the default effort's and puts a `low` / `medium` effort in a short system turn - right before the answer (no thinking: the empty thinking block, as always); the engine (0.1.39+, which the server - checks) keeps its checkpoint in front of that turn, so the next request reuses the conversation whatever its - effort. The default (`"start"`) prompt is unchanged. The model sees a level that is not the default in another - place than it was trained with; how well it follows it there is not measured yet. -- **Anthropic requests that don't ask for thinking (opt-in, 0.1.32, #278).** By default a `/v1/messages` request - with no `"thinking"`, effort or budget thinks as the model's template does. `"anthropic_thinking": "on_request"` in - `strata-.json` renders such a request without thinking - Anthropic's own rule, and what Claude Code's short - helper calls (a session title in a few dozen tokens) need; its real turns ask for thinking when it is on there. -- **Streaming.** With `"stream": true` everything arrives as it is made: the thinking, the answer, and tool calls - (the tool's name first, then its arguments piece by piece, like OpenAI and Anthropic do). While the model reads a - long prompt the stream sends keep-alives, so agents do not time out; the server window prints progress every - 15 s, and `GET /status` says what it is doing (`reading the prompt`, `answering`, tokens so far). Closing the - connection or pressing stop in your app really stops the model, so the next request starts at once. -- **Chat apps.** Any app with an "OpenAI-compatible" provider works: base URL `http://127.0.0.1:8080/v1`, any API key. -- **OpenCode** (#543). A starting point for `opencode.jsonc` (in your project, or `~/.config/opencode/`); the field - names are OpenCode's, so check its config docs if your version differs: - - ```jsonc - { - "$schema": "https://opencode.ai/config.json", - "provider": { - "strata": { - "npm": "@ai-sdk/openai-compatible", - "name": "Strata (local)", - "options": { "baseURL": "http://127.0.0.1:8080/v1", "apiKey": "none" }, // or your api_key - "models": { - "strata": { - "name": "Qwen3.8-Flash-Next (Strata)", - // context: what you chose in setup; output: what one reply may use (prompt + output must fit) - "limit": { "context": 262144, "output": 32768 }, - "options": { "reasoningEffort": "high" }, // sent as reasoning_effort - "variants": { // switch between them in OpenCode - "low": { "reasoningEffort": "low" }, - "medium": { "reasoningEffort": "medium" }, - "none": { "reasoningEffort": "none" } - } - } - } - } - }, - "model": "strata/strata" - } - ``` - - Set `limit.context` to the context you chose in setup: OpenCode compacts the conversation before it gets there. - Keep `limit.output` well under it: a request whose prompt plus `max_tokens` runs past the context is refused (see - **Context** below), or add `"fit_max_tokens": true` to `strata-.json`. For a hard cap on the thinking, add - `"reasoning_budget_tokens": N` to `strata-.json` (see above). -- **Claude Code** (Strata 0.1.17 or newer): set `ANTHROPIC_BASE_URL=http://127.0.0.1:8080` and - `ANTHROPIC_MODEL` to a Claude model name it knows (it refuses names it doesn't; Strata ignores the name), plus any - `ANTHROPIC_AUTH_TOKEN` (or your `api_key`, if you set one). -- **Codex CLI** (0.1.39): see [the Responses API](#the-responses-api-and-codex-cli) below. -- **Context.** Chosen in setup (8K-262K). Requests longer than that are refused, never silently cut. A request whose - `max_tokens` would run past the context is refused too (400); agents that always ask for their full output cap - can instead get it shortened to the room left: add `"fit_max_tokens": true` to `strata-.json` (or pass - `--fit-max-tokens` to `serve/server.py`). A prompt that leaves no room at all is still refused. -- **Model aliases** (0.1.32). `"aliases": ["qwen", "local-model"]` in `strata-.json` lists the model under - those names too in `/v1/models` (each with its own `id`, and in the model's `aliases`), like llama-server's - `--alias`; a request naming one is answered under that name. Any other name is still served, as before. -- **Model settings in the web page (0.1.39, #564).** The About tab's Model settings card shows and changes a few of - the keys above in `strata-.json`: the `sampling` defaults (temperature, top_p, top_k, min_p), - `reasoning_budget_tokens`, `fit_max_tokens`, `anthropic_thinking`, `effort_position`, `aliases`, `idle_unload_s`, - `lazy_load`, `engine_silence_s`, `api_monitor`, `open_browser` and `--vram-reserve-mib`. An empty field removes the - key (its default). Every other key of the file stays as it is, the earlier file is kept as - `strata-.json.bak`, and the model uses the change from its next start. Only Strata's own page can save - (JSON, the API key when one is set, as for the Chat settings); the network, key, MCP and program keys are not - editable there. -- **From other devices on your network.** The server listens on your PC only (`127.0.0.1`) unless you say otherwise: - run setup with `START-HERE.bat --setup --host 0.0.0.0 --api-key some-long-secret` (or add `"host": "0.0.0.0"` and - `"api_key": "..."` to `strata-.json`). The server window then prints this PC's addresses - (`from other devices: http://192.168.x.x:8080/`); open that on the other device, or use `.../v1` as an API base URL. - On Windows the firewall blocks it until you allow it: accept its prompt for Python (private networks), or run - `New-NetFirewallRule -DisplayName "Strata 8080" -Direction Inbound -Protocol TCP -LocalPort 8080 -Action Allow -Profile Private` - in an admin PowerShell, and make sure the network is set to Private. -- **From the internet.** Put a tunnel in front of it, for example [cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/do-more-with-tunnels/trycloudflare/): - `cloudflared tunnel --url http://127.0.0.1:8080`. **Set a key first**, or anyone with the link can use your PC: - add `"api_key": "some-long-secret"` to `strata-.json` (or set the `STRATA_API_KEY` environment variable); - clients then send it as their API key. Streamed answers carry `X-Accel-Buffering: no`, so nginx-style proxies pass - each token on at once. The web app's settings and MCP tools only answer Strata's own page: when you open it through - a proxy or tunnel whose address differs, add that address, e.g. `"trusted_origins": ["https://strata.example.com"]`. - With the key set, any `Host` name reaches the server (see Host names below). -- **From web apps in a browser (CORS).** Off by default. `"cors_origins": ["https://chat.example.com"]` lets pages of - those origins call `/v1/*` from the browser (Open WebUI's direct connections, browser extensions); `["*"]` lets any - page do it - only sensible with an API key. It never opens `/settings`, `/unload` or the MCP tools. -- **Host names (DNS rebinding).** A web page of another site can point its own name at `127.0.0.1` and then reach - this server as if it were its own, so without an API key the server answers only requests whose `Host` is a name - it knows (with a key the check is off: such a page cannot send the key, and tunnels and proxies that pass their - own name on keep working): - `localhost` (and `*.localhost`), any IP address (`127.0.0.1`, `[::1]`, `192.168.x.x`, ...), the address it - listens on and, when it listens beyond this PC (`0.0.0.0` or a LAN address), this PC's name (`mypc`, `mypc.local`) - and `host.docker.internal`; any port. Others get **403** naming the setting, and the server window prints one line - for each. Reach it under another name (a reverse proxy that keeps the name, a tunnel, a DNS name on your network, - another container's name for it)? Add the name: `"allowed_hosts": ["strata.example.com"]` in - `strata-.json` or `STRATA_ALLOWED_HOSTS=strata.example.com` (comma-separated); `".example.com"` allows that - name and every name below it, and `["*"]` turns the check off (so does setting `api_key`). The hosts of - `trusted_origins` count as allowed. Requests without a `Host` header (HTTP/1.0 clients) pass. -- **Web pages without an API key.** Without `api_key`, a `POST` to `/v1/*` that carries an `Origin` header (a - browser page sent it) is answered only for Strata's own page, pages on `localhost` or an allowed host name (any - port), the origins in `trusted_origins` or `cors_origins`, and browser extensions and desktop apps - (`chrome-extension://`, `moz-extension://`, `app://`: no web site can send those), and only with a JSON body; any - other page, and `Origin: null`, gets **403**. Clients that send no `Origin` (curl, the OpenAI and Anthropic SDKs, - other servers) are not affected. With - an API key, the key decides. `POST /unload` and `POST /load` take `Content-Type: application/json` from Strata's - own page (or no `Origin`), like `/settings`. - -**Conversation cache.** A request that continues a chat reads only the part after what the engine already holds: the -live session, or one of the checkpoints it keeps in RAM (up to 6, ~118 MB each, taken at the start of each new -assistant turn and every 16K prompt tokens). A checkpoint is used only when the prompt starts with exactly its tokens -and pictures. The oldest checkpoint - in practice the end of the system prompt, which every chat of the same client -shares - is kept for good while the rest rotates by least recent use, so a NEW chat that shares that prefix starts -reading after it instead of from token 0. A prompt read from the start is also checkpointed at the end of its system -prompt when that is 2,048 tokens or more (engine 0.1.20; PR #62 + #65), so that root exists for agent clients with long -system prompts and tool lists. Engine options: `--prompt-cache N` (0 = off), `--prompt-cache-every N`, -`--prompt-cache-root N` (0 = no system-prompt checkpoint), `--turn-token ID`. - -**Multiple conversations (opt-in).** Add `--conversation-cache-mib 8192 ---conversation-cache-slots 4` to the engine arguments to park up to four conversations -in a bounded 8 GiB host-RAM cache. This preserves controller/worker histories when -their requests alternate; it does not execute requests concurrently. No client session -ID is required: only exact token/image prefixes with matching steering mode are reused. -The default budget is 0 (disabled); `--prompt-cache 0` also disables parking. -With `--layer-split`, a parked conversation holds one image per stage (each later stage's -session and its share of the conversation checkpoints), every image is validated before -anything is overwritten, and each is restored on its own GPU. Verified on a 4-GPU split: -a 9,276-token conversation restored in 51 ms, and its follow-up decodes exactly the tokens -it decodes when the conversation never left (`tools/parking_test.py`). FP16, -INT8, Q4_0 and identity-layout K8V4 snapshots are supported; the K8V4 draft ring -remains INT8, as in upstream. Windows/HIP and multi-GPU runtime coverage must be -reported separately from Linux/CUDA evidence. - -The web page's Monitor tab has a **Conversation cache** card (0.1.39, #596): the parked conversations against the -slots and the RAM budget, how many were parked, restored and evicted, and the last switch (read from the engine's -log), and for every setup how many prompt tokens the cache gave back - in the last request and since the start. -`/metrics` has the same under `"conversation_cache"`. - -Snapshots contain running state, checkpoints, used K/V pages, and draft-layer K/V. -They add host RAM, not another model or VRAM allocation. The byte budget also counts -an incoming snapshot during a switch. After a restore, unchanged K/V pages can be -retained for the next parking operation; growth appends storage without copying -the existing pages. Rewinds refresh the affected pages, and running state and -checkpoints are captured again. Retained active K/V counts against the same byte -budget and is discarded before evicting parked entries under memory pressure. -If reserving space for growth would evict another conversation, parking uses a -full capture instead. -Oldest parked entries are evicted first. -Oversized snapshots or host allocation failures fall back to ordinary prompt processing. -`--conversation-cache-min-free-mib N` (default 2560) additionally requires that -physical-RAM headroom remain available: the engine checks before allocation and -again after capture. Unknown telemetry or insufficient RAM skips parking. Windows -uses `GlobalMemoryStatusEx`, Linux uses `MemAvailable`; these are host-level samples, -not a reservation or enforcement of container/job memory limits. An 8 GiB budget -is a cap, not a recommendation for every machine. - -The shared snapshot core validates all layers and checkpoints before applying any -state. Invalid entries are discarded; transfer/synchronization failure is fatal -rather than permission to continue with partial state. Indexer spare keys and the -moving spare row are preserved, including checkpoint rewinds. -The engine log reports parking, restoration, bytes, evictions, individual snapshot -sizes and K/V bytes reused during capture. `STRATA_SNAPSHOT_FULL_CAPTURE=1` disables -retention for diagnostic comparisons. Snapshots are not -persisted across restarts. - -**Current limits (v1):** one request at a time unless `"parallel": N` is set (opt-in batch slots, up to N requests -decoded together: [BATCHING.md](BATCHING.md)), and one conversation cached at a time (switching between two chats -re-reads the other one unless the opt-in cache above is enabled, or each conversation keeps its own batch slot); images only when set up with them (below); no video. **Temperature / top_p / top_k / min_p / -seed** are honored per request (OpenAI and Anthropic fields); with the default adaptive expert tier a sampled result -is not reproducible run to run - for seed-reproducible output add `--adapt-every 100000` (static residency) to the -engine arguments. The run config's optional `sampling` block sets the defaults for requests that leave the fields out -(`"sampling": {"temperature": 1.0, "top_p": 0.95, "top_k": 20}`); a request's own fields always win, and with no -block at all a request without sampling keys decodes greedy. The penalties (`presence_penalty`, `frequency_penalty`, -`repetition_penalty`, with `penalty_last_n` capping how many recent tokens they count over, default 64 when any -penalty is set) ride the same path; they count the tokens the request has consumed, so a repetition penalty -suppresses what the model itself just said, not the prompt alone. Since engine 0.1.19 they apply to every token -the speculative decoding checks at once, exactly as if it decoded one token at a time (before, only the first of -each batch got them). That makes requests with penalties 1-11% slower than in 0.1.18: the draft layer guesses -without penalties, so more of its guesses are now rejected. Requests without penalties are unchanged. `top_k` keeps at most 64 candidates: `0` ("off") or anything above 64 uses all 64. - ---- - -### The Responses API and Codex CLI - -`POST /v1/responses` (0.1.39, #451) speaks OpenAI's newer Responses API, which Codex CLI uses (it no longer -speaks Chat Completions). It runs on the same path as `/v1/chat/completions`, so the thinking levels, the thinking -budget, the conversation cache and the same API key, Host and Origin checks apply. - -It is **stateless**: nothing is stored, so the client sends the whole conversation in `input` every time (Codex does, -with `store: false`). `previous_response_id`, `conversation`, `background` and the retrieve/delete/cancel endpoints -are refused with an error that says so. - -| Request | What Strata does | -| --- | --- | -| `input` as a string, or as items | `message` items (`user`, `assistant`, `system`, `developer`; text and images), `reasoning`, `function_call`, `function_call_output`, `custom_tool_call(_output)` | -| `instructions` | The system message (with leading `developer` messages; later ones become user messages, as on the chat path) | -| `tools` | `function` tools, `namespace` tools (the model sees `namespace.name`; calls come back with `namespace` and `name`), `custom` tools (one free-form `input` string). Hosted tools (`web_search`, `file_search`, ...) are left out: the model cannot run them | -| `tool_choice` | `"none"` hides the tools; anything else lets the model choose (it cannot be forced) | -| `reasoning.effort` | `none`/`minimal`, `low`, `medium`, `high`/`xhigh`; without it the model's default (high) | -| `max_output_tokens` | The output cap (thinking included). Running out ends the response `incomplete` (`max_output_tokens`) | -| `text.format` | `json_schema` and `json_object` use the [JSON response formats](#json-response-formats) (checked, not constrained) | -| `temperature`, `top_p`, `reasoning_budget_tokens`, ... | As on the chat path | - -The model's thinking comes back as a `reasoning` output item with `reasoning_text` content (streamed as -`response.reasoning_text.delta`). This model writes no separate summaries, so `summary` is empty. With -`"include": ["reasoning.encrypted_content"]` the item also carries `encrypted_content`: an opaque string (base64, not -encrypted; the client already holds the text). Send the reasoning items back with the rest of the conversation, as -Codex does: their thinking goes back into the prompt, so it matches what the model wrote and the conversation cache -is reused. - -With `"stream": true` the events are the official ones, in order: `response.created`, `response.in_progress`, then -for each output item `response.output_item.added`, its deltas (`response.reasoning_text.delta`, -`response.output_text.delta`, `response.function_call_arguments.delta`), its `...done` events and -`response.output_item.done`, and at the end `response.completed`, `response.incomplete` or `response.failed`. -While a long prompt is read, a `response.in_progress` event goes out every 15 s, which Codex counts as activity. -Errors before the answer starts have the Responses form (`{"error": {"message", "type", "param", "code"}}`); after -it started they arrive as `response.failed`. - -**Codex CLI.** In `~/.codex/config.toml` (Windows: `%USERPROFILE%\.codex\config.toml`): - -```toml -model = "strata" # any name; Strata answers with its model -model_provider = "strata" -model_context_window = 32768 # the context you chose in setup: Codex compacts before it gets there -show_raw_agent_reasoning = true # show the model's thinking (it writes no summaries) -# model_reasoning_effort = "medium" # none, low, medium or high; default: the model's (high) - -[model_providers.strata] -name = "Strata (local)" -base_url = "http://127.0.0.1:8080/v1" -wire_api = "responses" -stream_idle_timeout_ms = 600000 # a first, long prompt can take minutes to read -# env_key = "STRATA_API_KEY" # only if the server has an api_key: the variable holding it -``` - -Then run `codex` (or `codex exec "..."`) as usual. Codex warns `Model metadata for ... not found` for a local model -name; that is expected. Measured with Codex CLI 0.160.0 and Q2_0 on an RTX 5070: its first prompt (instructions and -tool descriptions) was 9,443 tokens, read in 10 s; in a tool loop, each later turn reused about 96% of the prompt from -the cache and read only the new part in 1-2 s. On Windows, Codex's sandbox rejected every shell command in that test -until it was started with `-c 'windows.sandbox="unelevated"'` (a Codex setting, not Strata's). - -## Tools from MCP servers - -The chat page can give the model tools from [MCP](https://modelcontextprotocol.io) servers, as LM Studio and Claude -Desktop do: reading your files, fetching web pages, searching, anything an MCP server offers. List the servers in -`strata-.json` under `"mcp_servers"` - the same shape as Claude Desktop's `mcpServers` block, which you can -also paste as it is (key `"mcpServers"`): - -```json -"mcp_servers": { - "files": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "C:\\Users\\me\\Documents\\notes"]}, - "search": {"url": "http://127.0.0.1:3000/mcp", "headers": {"Authorization": "Bearer ..."}} -}, -"mcp": {"timeout_s": 60, "max_result_chars": 20000, "max_rounds": 8} -``` - -Or keep them in their own file and start the server with `--mcp-config path\to\claude_desktop_config.json` (a file -with an `mcpServers` block; add it to the `serve/server.py` line of your run script). Restart Strata after a change. - -- **A program** (`command`, `args`, optional `env` and `cwd`) is started by Strata and spoken to over its - stdin/stdout; `npx`, `uvx`, `python` and friends are found on `PATH` as usual (Node.js is needed for `npx` - servers). **An address** (`url`, optional `headers`) uses MCP's Streamable HTTP transport (the older SSE-only - transport is not supported). `"disabled": true` leaves an entry out. -- The servers start with Strata, in the background; the server window says what each one offers - (`MCP server 'files': 14 tools (...)`), or why it did not start - its tools are then left out and the chat works - without them. The Monitor tab lists them, and the Sampling drawer has **Use tools from MCP servers** (on by - default). A server that stops later is started again at its next call. -- In the chat each call shows as a small block (tool, arguments, result); the model reads the result and goes on, - up to `max_rounds` calls in a row per answer. A tool that fails or takes longer than `timeout_s` (default 60 s) - gives the model an `error: ...` result instead of ending the chat. Results longer than `max_result_chars` - (default 20,000 characters) are cut, with a note, before the model reads them. Stop stops a running tool too. -- Only the chat page uses them. API clients (omp, Claude Code, OpenAI and Anthropic SDKs) see the API exactly as - before and keep their own tools; a request to `/v1/chat/completions` opts in with `"strata_mcp": true` (it then - gets `strata_mcp` tool events in the stream). - -**Security.** MCP tools run on your PC with your user's rights, and **the model decides when to call them** - also -because of what it reads (a web page or a file can contain instructions). Give a filesystem server only the folders -it needs, prefer read-only tools, and don't add servers you don't trust. The tools can only be used from the chat -page itself (a request with another site's Origin or without a JSON content type is refused); if Strata is reachable -from other devices, set an API key. - -**Context extension past 262K (rope scaling, EXPERIMENTAL, off unless you pick it).** The model was trained on -262,144 positions (rotary base 1e7). Rope scaling rescales the rotation angles so that longer contexts stay usable, -with llama.cpp's types and flag names. `linear` is Position Interpolation: every angle is shrunk by the factor. -`yarn` keeps the high-frequency angles, interpolates the low-frequency ones, and adds the magnitude correction -that keeps the attention temperature where training put it. **Without the flags nothing changes:** an unscaled -run computes exactly what it did before the feature existed, bit for bit. Scaled contexts need proportionally -more VRAM/RAM for the KV cache and the rope tables (~13 KB and ~0.26 KB per token). - -What was measured (contributors' runs, RTX 5080 + IQ3_S, native path, in PR #84): per-position perplexity on the -same tokens, with only the scaling flag changed. At 293K tokens (1.12x the trained length), `yarn` with factor 2 -lowered the NLL by 0.18 nats against both `none` and `linear` 2 (2.04 vs 2.22 / 2.22). That is 3-4x the path noise -measured at the same length. `linear` 2 was indistinguishable from `none`. At 2.7K and 32K no arm separated from the -noise. Needle tests do not tell the arms apart: the unscaled model also finds a needle at 413K. Long real-document -Q&A worked with `yarn` 2 at 421K and `yarn` 4 at 714K (8/8 each), and a 1M-token `yarn` 4 run read end to end. -Taken together, use **yarn**. It is still experimental: the numbers come from one machine and one quant. - -- setup: `START-HERE.bat --setup --context 393216` asks nothing extra - it picks the method (yarn; one - question when run interactively) and derives the factor from the final context for you (final context / - 262,144, at least 1: 1.5 at 393K, 2 at 512K, 1 inside the trained range; `--rope-scaling`/`--rope-scale` - override; an explicit `--rope-scale` is kept as given even when it is too small for the context actually - served, so check it if you set one). An explicit `--rope-scaling none` for a context past - 262,144 is refused: the setup will not configure a run with the stock angles past the trained range. If - the RAM check reduces a chosen 384K/512K back inside the trained range, an omitted method adds no - scaling, and an explicitly chosen one stays at factor 1 - the trained angles, no expansion (not a - switch for rope as a whole: explicitly supplied rope settings keep their behavior). -- engine: `--rope-scaling none|linear|yarn`, `--rope-scale F`, and the raw ggml knobs `--rope-freq-base`, - `--rope-freq-scale`, `--yarn-orig-ctx` (default 262,144), `--yarn-ext-factor`, `--yarn-attn-factor`, - `--yarn-beta-fast` (32), `--yarn-beta-slow` (1). The model file's `rope.scaling.*` keys, when a - fine-tune ships them, are the defaults the flags override. - -The scaling is fixed for the whole run - the engine stores keys in its cache after rotating them, so one -cache must never mix two scalings, and there is no per-request form. Within the trained 262,144 a scaled -run is a slightly different model: the rescaled angles, and `yarn`'s magnitude correction, apply at every -position, not only past the trained end. That is why the setup turns scaling on only for a context past -262,144. Pictures read the same scaled table (their (t, h, w) positions feed it). That should work, but it is -unmeasured: all the runs above are text. - ---- - -## Manage Strata from your AI assistant (MCP server) - -`tools/strata_mcp.py` is an MCP server for Claude Code, Claude Desktop, Cursor, VS Code, Codex and other assistants. -Once it is added, you can ask your assistant "install Strata for this PC", "start Strata" or "is Strata running?". -In Claude Code, add it with: - -```bash -claude mcp add strata -- python C:\Users\you\Strata\tools\strata_mcp.py -``` - -It has eight tools: status (the running model, what is installed, the hardware, a recommended size), the model -list, install, start, stop, logs, a speed test, and connection settings for other apps. - -Install runs `setup.py` with `--yes` in the background. Before it downloads anything, it shows the plan and waits -for your OK. Start and stop work like the run scripts and the server's own unload. The MCP server only ends -processes it started itself. It uses only Python's standard library, so it works before `.venv` exists. - -The config snippets for every client, the tool arguments and the safety rules are in -[docs/MCP_SERVER.md](MCP_SERVER.md). This is the opposite direction from -[Tools from MCP servers](#tools-from-mcp-servers) above, where the Strata model calls *your* MCP tools. - ---- - -## Images (vision) - -The model has a vision encoder: [`mmproj-Qwen3.8-Flash-Next-BF16.gguf`](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF) -(0.9 GB, a 27-layer ViT plus the projector into the language model). It is **optional**: say yes when the setup asks -"Images?", or run it again with `--vision gpu` (or `--vision cpu`). The setup downloads the encoder, builds a small -helper (`strata-vision`, from llama.cpp's `mtmd` library) and adds it to your start script. Nothing else changes. - -| Encoder on | Time per picture | Cost | -| --- | --- | --- | -| **GPU** (recommended) | **0.1-0.5 s** (up to 1,024 image tokens) | ~1.4 GB of VRAM is kept free for it, so the expert cache is smaller: text output is a few % slower (table below) | -| CPU | 10-30 s (pictures are scaled down to ~300 image tokens) | nothing on the GPU | - -A picture becomes up to 1,024 tokens of the context (a 640x480 photo: 300). The same picture sent again, as chat apps -do on every turn, is encoded only once. - -**More image tokens (0.1.39, #625):** `--vision-tokens N` at setup (`START-HERE.bat --setup --vision cpu ---vision-tokens 768`) sets the most tokens a picture becomes - `"max_tokens"` in the `"vision"` section of -`strata-.json`, which you can also edit by hand. More tokens keep more detail (small text, charts, screenshots) -and take longer to encode, on the CPU most of all; a setup run again keeps the value. - -**A Q8_0 encoder (#625):** `"mmproj"` in the `"vision"` section can point to another mmproj file of this model, for -example a Q8_0 one (llama.cpp's `convert_hf_to_gguf.py --mmproj --outtype q8_0` makes one): the encoder's library -reads quantized weights, the file is half the size, and on the CPU it can encode faster than BF16. Setup downloads -the BF16 file, and a setup run again keeps a file of your own that still exists. We have not measured its accuracy -against BF16 yet; numbers are welcome in #625. - -**A spare GPU for the encoder (0.1.33, #408):** with a card the engine doesn't use, add `"cuda_device": 2` (numbered -like `nvidia-smi`) to the `"vision"` section of `strata-.json`: the encoder then runs on that card alone. Lower -`--vram-reserve-mib` in `"args"` to 700 as well, so the engine's cards keep that VRAM for the expert cache. The -encoder's card needs code in the ready-made encoder (RTX 20/30/40/50). - -### Sending a picture - -**Terminal chat:** type `/image `, press Enter, then type your question. - -``` -you> /image C:\Users\me\Pictures\receipt.jpg -(picture attached: receipt.jpg - now type your question) -you> What is the total on this receipt? -``` - -**OpenAI API** (an `image_url` part: a `data:` URL, an `http(s)://` URL or a local file path): - -```python -import base64 -from openai import OpenAI -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="none") -img = base64.b64encode(open("photo.jpg", "rb").read()).decode() -r = client.chat.completions.create(model="strata", messages=[{"role": "user", "content": [ - {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img}"}}, - {"type": "text", "text": "What is in this picture?"}]}]) -print(r.choices[0].message.content) -``` - -**Anthropic API:** an `image` block with a `base64` (or `url`) source, as usual. - -JPEG, PNG, BMP, GIF, WebP, TIFF and AVIF work (the last ones are converted to PNG first; agents such as omp send -WebP). Chat apps with image upload work the same way. - -### Speed with images on (4K context, measured) - -| Model | Prompt tok/s, images off | Prompt tok/s, images on | Output tok/s, images off | Output tok/s, images on | -| --- | ---: | ---: | ---: | ---: | -| **Q2_0** | 541 | 531 | 90.7 | 86.9 | -| **IQ2_XS** | 468 | 458 | 77.1 | 74.0 | -| **IQ3_XXS** | 411 | 401 | 64.7 | 59.5 | - -"Off" is the published setup; "on" runs with the encoder loaded on the GPU and its VRAM kept free, so ~1,000 fewer -experts fit in VRAM and the CPU computes a few more per token: 2-8% slower. For text, turning images on changes -nothing else (the output is bit-identical when the VRAM is the same). - -A question about a picture (a 640x480 newspaper page = 300 image tokens, a 328-token prompt; the whole request, encoder -on the GPU, measured through the API): - -| Model | Answer ("MEN WALK ON MOON") | Picture encoded | Prompt | Output | -| --- | ---: | ---: | ---: | ---: | -| **Q2_0** | 1.9 s | ~0.1 s | 207 tok/s | 65-73 tok/s | -| **IQ2_XS** | 2.3 s | ~0.1 s | 173 tok/s | 50-60 tok/s | -| **IQ3_XXS** | 2.7 s | ~0.1 s | 144 tok/s | 41-50 tok/s | - -(Short prompts run below the 4K prompt speed: a 2,048-token chunk is where the prompt path is efficient. Short answers -run below the long-output speed: the first rounds have no draft yet.) - -**How it works inside:** the encoder turns the picture into rows of the same width as the model's word embeddings; -Strata puts them where the prompt has `<|image_pad|>` tokens and gives each one its 2-D position (row and column in the -picture; the model uses interleaved M-RoPE). Answers match llama.cpp's multimodal implementation token for token on our -test images. - ---- - -## Experimental speed projection (EXPERIMENTAL, off by default) - -**This is an experiment, not a finished feature.** It ships with Strata but stays off unless you turn it on. - -A 480 KB control vector for Qwen3.8-Flash-Next (`data/experimental-speed-projection/`, see its README). After each -of layers 4-44 the engine removes one direction from every hyper-connection stream of the residual: `h -= (h . v) v`, -one unit vector `v` per layer, exactly as llama.cpp does with the package's `--cvec-mode project` patches. - -**What it changes.** The vector's own package describes it as a **refusal-direction projection**: with it the model -declines far fewer requests (it reports 1 of 50 vs 50 of 50 on its test set), and removing refusals removes a safety -behaviour - you are responsible for what the model writes with it on. It also shifts ordinary answers a little -(measured below). It is not an optimization in the engine: on the same text it costs 0.2-0.4% per token. What a -chat's tokens/s does with it on depends on the text the model writes (length, repetition, how well the drafts land), -so measure it on your own prompts; the Monitor marks every request ESP or stock. - -**Turning it on (at setup).** `START-HERE.bat --setup` asks "Turn on the experimental speed projection?" (default: -no), or pass `--experimental-speed-projection on` (`off`, or a path to another vector GGUF). Only for the original -Qwen3.8-Flash-Next, not Swift 1.5. It writes these engine flags (llama.cpp's) into `strata-.json`: - -``` ---control-vector-scaled \data\experimental-speed-projection\Qwen3.8-Flash-Next-experimental-speed-projection.gguf:1.0 ---control-vector-layer-range 4 44 --cvec-mode project --cvec-dir per-layer -``` - -The engine log then says `control vector mode = project, dir = per-layer, layers 4..44 (41 steered)`, and the web -app's About tab lists it. (`--cvec-mode add` is llama.cpp's stock additive mode, for additive vectors.) - -**Per request.** A loaded vector is on for every request unless it says otherwise: the web app's Sampling drawer has -a switch, and the API takes `"experimental_speed_projection": false` in the request body (OpenAI and Anthropic; a -config default goes in `"sampling": {"experimental_speed_projection": false}`). Switching drops the conversation -cache once, since the model state was computed the other way. Switched off, the output is token-for-token the stock -model's. - -**Measured here** (Q2_0, fixed experts, 2,557 teacher-forced tokens of code, a document and a chat): the top-1 token -changes at 10% of positions, mean KL from the stock model 0.063 nats (max 4.1), perplexity +15% on code, +2.3% on -the document, +0.4% on the chat. Details: `bench/results/2026-09-27-esp/`. - ---- - -## Troubleshooting - -| Symptom | What to do | -| --- | --- | -| `the NVIDIA driver is too old` | Update the driver (NVIDIA App or nvidia.com/drivers), restart, run `START-HERE.bat` again. | -| Python or the build tools could not be installed | Install what it names (links are printed), then run it again. Everything already done is kept. | -| `port 8080 is already in use` | Strata is already running (look for its window), or another program uses the port: `START-HERE.bat --port 8081`. | -| `cudaHostRegister ... out of memory` in the log | Normal on Windows: the engine pins the experts in per-layer slices instead. Only a problem if the load then fails. | -| `ExpertCache: cudaMalloc(...) failed: out of memory` although VRAM is free | Windows' page file is off or tiny: every allocation on the graphics card is also charged to Windows' commit (RAM + page file). Set the page file to "System managed" (System > About > Advanced system settings > Performance > Advanced > Virtual memory) and restart. Since 0.1.19 the engine retries with a smaller cache instead of stopping, and setup warns about a page file under 4 GB (issue #60). | -| The first start takes minutes | It is reading 34-55 GB into RAM; the second start is faster while the files are in the OS cache. | -| The PC freezes for a few minutes at the start | Normal, most of all the first time (the server window says when it happens): the engine loads the experts into RAM, pins part of it for the GPU and sizes the expert cache. Wait; don't close the window. Still frozen after 10 minutes: restart the PC, close other programs, try again, or pick a smaller size. | -| `the engine stopped unexpectedly (exit code ...)` | The engine process ended mid-answer - usually out of RAM (Linux ends the biggest program: `sudo dmesg \| grep -i -E 'killed process\|out of memory'`). The next request starts it again by itself. If it repeats: close other programs or pick a smaller size. The server also warns at start when the model's experts leave less than ~6 GB of RAM for everything else. | -| Slow output, disk light busy | Not enough free RAM: close other programs, or choose Q2_0 / IQ2_XS. | -| `prompt ... exceeds the context` | The request is longer than the context you chose: run setup again with a bigger `--context`. | -| `the setup refuses --rope-scaling none for a past-trained context` | A context past the trained 262,144 needs the rotary angles rescaled (experimental rope scaling), and the setup will not configure one with the stock angles there. Let it pick (`START-HERE.bat --setup --context 393216` adds yarn and a covering factor), or pass `--rope-scaling linear` or `yarn` yourself. | -| Slower than the tables | The monitor plugged into the GPU and other GPU programs take VRAM from the expert cache; RAM running below its rated speed (enable EXPO/XMP in the BIOS) slows the CPU half. | -| `this server was started without the vision encoder` | The model was set up for text only: run setup again with `--vision gpu`. | -| A picture is refused or `cannot read the image` | The file is not a picture Pillow can open (JPEG, PNG, WebP, GIF, BMP, TIFF, AVIF work). | -| Pictures are slow (10-30 s) | The encoder runs on the CPU: run setup again with `--vision gpu` (needs ~1.4 GB of VRAM). | -| A request never finishes: "reading the prompt", GPU "100%" at low power | The GPU ran out of VRAM (engines before 0.1.9 could end with ~30 MiB free at large contexts). Run `START-HERE.bat` once to get engine 0.1.9 or newer; the log then says `... MiB of VRAM free with everything loaded` (a few hundred) and names the `--vram-reserve-mib` to add if it is low. | -| Generation stops mid-answer, GPU "100%", one CPU core busy | Fixed in engine 0.1.12 (issue #29, a race in the CPU expert pool on big-VRAM cards). Since then a request that stops moving ends with an error instead of hanging (after 2 minutes; 1 minute from 0.1.13): the log says `no progress for ... s ... (issue #29)` with where it stopped, and the next request starts the engine again. If you see that line, please open an issue with it. Engine 0.1.13 adds a stall report under it (what every expert-pool thread and the GPU handshake were doing, memory and page faults) and, on Windows, a `strata-stall-.dmp` file with every thread's stack: attach both. (`STRATA_WATCHDOG_S` sets the time in seconds; 0 turns it off.) Engine 0.1.14 fixes the stall those reports found (issue #31: with the IQ packs the host could wait forever inside the NVIDIA driver while copying experts in a verify window; the experts are now copied by a GPU kernel, `--pcie-mode dma` restores the old way). | -| `no progress for 60 s ... reading the prompt` on Linux, and the stall report says `threads waiting on the disk (state D): 16 ...` | The engine waits for the drive, not a deadlock: the n-gram table is read at random (`--ple-io direct`), which a rotational disk cannot keep up with (#605). The engine warns at start when the table is on one; `--ple-io ram` (Linux, needs RAM for the table) or the model on an SSD fixes it. Setup adds `--ple-io ram` itself on a rotational disk when the RAM holds the table (0.1.39). | -| `the engine said nothing for ... s during the request` or `... did not finish the request after it was stopped (STOP)` | Issue #481: the engine and the server lost step (the engine waits for its next command, the server for the request's end; GPU at 0 %, nothing in the log). The server ends the engine after 300 s without a line from it during a request (while a prompt is read: each chunk may take three times the previous one's time, the first one up to its tokens at 50 tok/s more), the request ends with an error and the next request starts the engine again. `"engine_silence_s": 600` in `strata-.json` sets the time (0 = wait forever, as before). If you see it, please add the end of the engine log to #481. | -| `out of memory: cudaFuncSetAttribute` in the log (IQ3_XXS, long prompt) | Fixed in engine 0.1.15: CUDA loaded a kernel's code when it was first needed, and mid-prompt there was no VRAM left for it. Run `START-HERE.bat` (Windows) or `./setup.sh` (Linux) once to update. | -| Anything else | The engine log is `strata-.log` in this folder. | - ---- - -## How it works - -

memory tiers

- -- **GPU (VRAM):** attention and DeltaNet mixers, the gated-residual weights, routers, shared experts, output head, the MTP - draft layer, the KV cache (from 64K: only its most-read part, the rest streams from RAM), and an **expert cache** that fills the rest of VRAM with the most-used experts (it adapts to - the conversation while you chat). -- **RAM:** all 24,576 experts, pinned. The CPU computes the experts that are not on the GPU **in place**, at the same time - as the GPU works on the cached ones (AVX-512 / AVX2 kernels, ggml's for the i-quants). -- **SSD:** the 28.8 GB n-gram table, a few rows per token, read unbuffered past the OS cache (`--ple-io direct`, the - default, made for SSDs; on a rotational disk `--ple-io ram` keeps the table in RAM, #605). -- **Speculation:** the model's own MTP layer drafts up to 3 tokens; one pass over all 48 layers checks them. 2.4-3.2 - tokens per pass on average. When the reply repeats the context (code edits, quoted text), **prompt lookup** (engine - 0.1.7) drafts up to 5 tokens from the earlier copy, but only where its measured acceptance and cost say it pays: - code edits 6-11% faster, other text unchanged. The drafts are checked like the MTP's, so the output is the same. -- **Prompts** are processed in chunks of up to 8,192 tokens (`--prefill auto`; 32,768 opt-in) with the experts - streamed to the GPU over PCIe. Since engine 0.1.39b (#583) the streamed ring is sized in bytes for the pack (a - native pack with bigger blobs gets fewer ring slots and keeps more cache slots) and `--prefill auto` picks the - largest chunk that keeps that ring full. It only gives up ring slots where 0.1.39's rule held the chunk at 4,096 - tokens or less; from 6,144 on it keeps 0.1.39's ring and only looks for a bigger chunk beside it (shrinking the - ring there measured slower: the Coder -12%), and a prompt that fits 0.1.39's chunk keeps 0.1.39's ring (one - chunk: a smaller ring only slowed it). RTX 5070, 32K prompts against `STRATA_RING_BYTES=0`, 2-3 interleaved - rounds: IQ3_XXS +18.5% at a 1,500-slot cache and +9% in another memory state, the Coder +3%, IQ3_S unchanged; 4K - prompts unchanged (-0.7% to +1.1%, bit-identical). Q2_0 (a fixed `--prefill 2048`) is not affected. It changes - the bits of a long prompt against 0.1.39 (the experts go through a different - mix of cached and streamed groups). Measured quality, teacher-forced over the next 2,001 tokens of a long document - against the FP16 prompt path (IQ3_XXS, `--prefill auto`): 8K prompt KL 0.042 (0.1.39: 0.054), top-1 agreement - 93.5% (92.2%); 32K prompt KL 0.020 (0.019), top-1 95.3% (95.0%) - the same band as before. `STRATA_RING_BYTES=0` - restores 0.1.39's ring, loan and chunk choice. - -The full story, with measurements, bottlenecks and what comes next: **[docs/paper/Strata-Paper.pdf](paper/Strata-Paper.pdf)**. - ---- - -## Credits and licenses - -Strata itself: [MIT](../LICENSE). The model files are not part of it; their licenses apply to them (below). - -- Model: [Qwen/Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next) by the Qwen team; quantizations: - [ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF). - The Coder: [ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF) - (Apache-2.0 per its card); its support in Strata came from @pjgmobile's PR #54. - Swift 1.5: [ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF](https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF) - by UkisAI. Their licenses apply to the weights. -- [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp) (MIT): the i-quant formats, the GPU dot products and - dequantizers transcribed in `src/kernels/cuda/iq_kernels.cu`, the CPU backend linked for the i-quant experts, the - `mtmd` library behind the image encoder (`tools/vision/`), and `gguf-py` used by the tools. See - `third_party/ggml/LICENSE`. -- Ideas from [Splash](https://github.com/incoai/splash), [ninfer](https://github.com/Neroued/ninfer) and - [HyperQwen](https://github.com/syv-ai/HyperQwen); references in the paper. -- The web app's font: [Outfit](https://github.com/Outfitio/Outfit-Fonts) (SIL Open Font License 1.1, see - `serve/web/fonts/OFL.txt`). Its Monitor tab started from @code-martin's dashboard idea (PR #22). -- The experimental speed projection's vector (`data/experimental-speed-projection/`): Qwen Community License 1.0, - made from the model's activations (see its README). - -### Start the text API without occupying the GPU - -`serve/server.py --engine strata --config strata-.json --lazy` (or `"lazy_load": true` in that -config) starts the lightweight HTTP API without spawning the native engine. The first generation request -loads it through the existing reload path, including `before_load` and `min_free_vram_mib`. Eager startup -remains the default. This option is text-only: a vision configuration with lazy startup is rejected explicitly. - -`POST /v1/load` and `/v1/unload` are JSON control aliases for integrations, accepting `{}` or -`{"model":""}` and returning model status. They require the configured API key, -`application/json`, and no foreign browser Origin. They return **409** while a request is active or queued, -and **404** for an unknown model. Existing `/load` and `/unload` behavior is preserved. `/api/health` aliases -`/health`; `/v1/status` exposes `loaded` and `auto_load`. The unloaded model remains discoverable. - -Unloading and shutdown close the native engine's stdin after sending `QUIT`, allowing Windows' detached -stdin reader to see EOF. Cleanup waits for process exit before releasing handles; if forced shutdown still -times out, the server keeps ownership and reports an error rather than claiming the model was unloaded. - -### JSON response formats - -`POST /v1/chat/completions` accepts `response_format: {"type":"json_object"}` or -`{"type":"json_schema","json_schema":{"name":"answer","strict":true,"schema":{"type":"object","properties":{"answer":{"type":"integer"}},"required":["answer"],"additionalProperties":false}}}`. -The schema must describe an object at its root. Local `#` references work; remote references are refused. -`json_schema` is checked with the Python package `jsonschema` when it is installed (`python -m pip install -"jsonschema>=4.23,<5"`; setup does not add it); without it the answer is only checked to be one JSON object, and the -server says so once. - -This is **schema prompting followed by server validation**, not grammar-constrained decoding. One generation -is made per request, with no hidden retry. Successful responses contain a validated JSON object. Malformed JSON, -duplicate keys, non-finite numbers, schema violations and incomplete generations return **502** with -`error.code: structured_output_failed`; invalid request schemas return **400**. JSON formats combined with -tools/MCP are refused explicitly. Without `response_format`, ordinary text and tool behavior stays the same. - -Structured SSE buffers the answer while sending keep-alive comments. It emits content only after validation, -then usage/timings and `[DONE]`; failures emit an SSE error and `[DONE]` without invalid content deltas. -`/v1/status.structured_output` advertises the formats, validation method and buffered streaming behavior. - -### API request monitor - -Off by default, since it keeps prompts and answers in memory: turn it on with `"api_monitor": true` in -`strata-.json` (or `serve/server.py --api-monitor`); otherwise nothing is recorded and the two endpoints below -answer 404. -Open `/api-monitor` to inspect API traffic without opening a chat. It shows the model state, safe -load/unload controls, active/queued requests, original request bodies, output, separate reasoning and -non-stream response bodies. Total wall-clock includes FIFO waits and automatic loading; load, queue, -first-token, prompt/output tokens and engine decode timing are shown separately. - -`GET /api/requests` returns compact summaries; `GET /api/requests?id=` returns one retained request. -Both use the existing API-key check. The monitor retains the newest **100 requests in memory** until restart, -with **262,144 characters per input/output/reasoning/response field** and visible truncation flags. The actual API -responses are unaffected. Headers are not recorded, and the monitor key is kept in this tab's session storage. -Treat request history as sensitive input/output when exposing Strata on a network: set an API key as above. -The page uses relative URLs and works through the existing host binding or a reverse proxy. diff --git a/docs/upstream/Strata-Paper.pdf b/docs/upstream/Strata-Paper.pdf deleted file mode 100644 index fcfd2eb..0000000 Binary files a/docs/upstream/Strata-Paper.pdf and /dev/null differ diff --git a/frontend/chat_parser_test.cpp b/frontend/chat_parser_test.cpp deleted file mode 100644 index 3eaec48..0000000 --- a/frontend/chat_parser_test.cpp +++ /dev/null @@ -1,132 +0,0 @@ -// Exercise request preparation and final tool parsing with the actual GGUF. -// No inference engine or CUDA context is created. -#define main unused_serving_main -#include "main.cpp" -#undef main -#include -#include - -int strata_engine_main(int, char**) { return 99; } - -int main(int argc, char** argv) { - if (argc != 2) return 2; - llama_log_set(quiet_log, nullptr); - llama_backend_init(); - Server server; - server.opt.ctx = 196608; - auto params = llama_model_default_params(); params.vocab_only = true; - server.model = llama_model_load_from_file(argv[1], params); - assert(server.model); - server.vocab = llama_model_get_vocab(server.model); - server.tmpls = common_chat_templates_init(server.model, ""); - assert(common_chat_templates_get_caps(server.tmpls.get()).at("supports_parallel_tool_calls")); - auto request = common_json::parse_no_throw(R"({ - "messages":[{"role":"user","content":"Check the files and the date."}], - "tools":[{"type":"function","function":{"name":"bash","parameters":{ - "type":"object","properties":{"command":{"type":"string"}},"required":["command"] - }}}] - })"); - const std::string output = "Reasoning.\n\n\n" - "\n\n\nls\n\n\n\n" - "\n\n\ndate\n\n\n"; - Prepared default_request, explicit_request; - std::string error; - assert(server.prepare(request, default_request, error)); - auto message = common_chat_parse(output, false, default_request.parser); - assert(message.tool_calls.size() == 2); - assert(message.tool_calls[0].arguments == "{\"command\":\"ls\"}"); - assert(message.tool_calls[1].arguments == "{\"command\":\"date\"}"); - request["parallel_tool_calls"] = true; - assert(server.prepare(request, explicit_request, error)); - assert(explicit_request.ids == default_request.ids); - assert(common_chat_parse(output, false, explicit_request.parser).tool_calls.size() == 2); - request["parallel_tool_calls"] = false; - assert(server.prepare(request, explicit_request, error)); - assert(explicit_request.ids == default_request.ids); - assert(common_chat_parse(output, false, explicit_request.parser).tool_calls.size() == 1); - // Arguments in any order: the model writes optional parameters before required ones, and upstream's - // required-first rule dropped such calls without an error (patches/llama.cpp-qwen3-coder-any-argument-order.patch). - auto read_request = common_json::parse_no_throw(R"({ - "messages":[{"role":"user","content":"Read the file."}], - "tools":[{"type":"function","function":{"name":"read","parameters":{ - "type":"object","required":["path"],"properties":{"path":{"type":"string"}, - "offset":{"type":"number"},"limit":{"type":"number"}} - }}}] - })"); - Prepared read_prepared; - assert(server.prepare(read_request, read_prepared, error)); - for (const char* order : {"limit offset path", "offset path limit", "path limit offset", "path"}) { - std::string text = "Reasoning.\n\n\n\n\n"; - std::istringstream names(order); - for (std::string name; names >> name;) - text += "\n" + (name == "path" ? "/tmp/a.txt" : "40") + "\n\n"; - text += "\n"; - auto parsed = common_chat_parse(text, false, read_prepared.parser); - assert(parsed.tool_calls.size() == 1); - 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 = "\n\n\nls -l \"a b\" | head -n 3\n" - "\n\n"; - const std::string answer = "A lighthouse stands on the cape: caf\xC3\xA9 lights, 2 < 3 and bold.\n\n" - "```json\n{\"a\": [1, 2], \"s\": \"x\\ny\"}\n```\nIt writes \n\n" + answer, 0}, - {"answer, thinking off", false, false, answer, 0}, - {"answer, tools declared", true, true, "No tool is needed.\n\n\n" + answer, 0}, - {"answer, tools declared, thinking off", false, true, answer, 0}, - {"text then a tool call", true, true, "List first.\n\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\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& 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()); - } - } - llama_model_free(server.model); - std::puts("PASS: omitted parallel_tool_calls uses the model capability; explicit false remains honored; " - "tool arguments parse in any order; the answer streams as it grows and tool calls arrive whole"); -} diff --git a/frontend/child_watch.hpp b/frontend/child_watch.hpp deleted file mode 100644 index 207f2b4..0000000 --- a/frontend/child_watch.hpp +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace strata_frontend { -// Called only by the supervisor, which is joined before Engine::quit(). -// Reap dead children: kill(pid, 0) would report a zombie as still alive. -inline bool child_running(pid_t& pid, std::string& why) { - int status = 0; - const pid_t result = ::waitpid(pid, &status, WNOHANG); - if (result == 0 || (result < 0 && errno == EINTR)) return true; - if (result < 0) why = std::string("waitpid: ") + std::strerror(errno); - else if (WIFSIGNALED(status)) why = "engine killed by signal " + std::to_string(WTERMSIG(status)); - else if (WIFEXITED(status)) why = "engine exited with code " + std::to_string(WEXITSTATUS(status)); - else why = "engine exited unexpectedly"; - pid = -1; - return false; -} -} diff --git a/frontend/child_watch_test.cpp b/frontend/child_watch_test.cpp deleted file mode 100644 index abcb3a1..0000000 --- a/frontend/child_watch_test.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "child_watch.hpp" -#include -#include -#include -#include -#include - -int main() { - for (bool crash : {false, true}) { - pid_t pid = ::fork(); - assert(pid >= 0); - if (pid == 0) { - const struct rlimit no_core{0, 0}; - ::setrlimit(RLIMIT_CORE, &no_core); - ::usleep(30000); - if (crash) ::raise(SIGABRT); - ::_exit(17); - } - std::string why; - assert(strata_frontend::child_running(pid, why)); - bool exited = false; - for (int i = 0; i < 100; ++i) { - if (!strata_frontend::child_running(pid, why)) { exited = true; break; } - ::usleep(10000); - } - assert(exited && pid == -1); - assert(why == (crash ? "engine killed by signal " + std::to_string(SIGABRT) : "engine exited with code 17")); - std::puts(why.c_str()); - } - std::puts("PASS: normal exit and watchdog-style abort reaped and diagnosed"); -} diff --git a/frontend/engine.hpp b/frontend/engine.hpp deleted file mode 100644 index 86e5ef1..0000000 --- a/frontend/engine.hpp +++ /dev/null @@ -1,189 +0,0 @@ -#pragma once -#include "child_watch.hpp" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace strata_frontend { -struct GenResult { - bool ok = false; - std::string error; - std::string finish = "length"; - long long produced = 0, prompt_n = 0, draft_accepted = 0, draft_offered = 0; - double prompt_ms = 0, decode_ms = 0; -}; - -class Engine { -public: - bool start(const std::vector& args, std::string& err, const char* executable = "/proc/self/exe") { - int to_child[2], from_child[2]; - if (::pipe(to_child) != 0 || ::pipe(from_child) != 0) { err = "pipe failed"; return false; } - pid_ = ::fork(); - if (pid_ < 0) { err = "fork failed"; return false; } - if (pid_ == 0) { - ::dup2(to_child[0], STDIN_FILENO); - ::dup2(from_child[1], STDOUT_FILENO); - ::close(to_child[0]); ::close(to_child[1]); ::close(from_child[0]); ::close(from_child[1]); - std::vector argv; - for (const std::string& a : args) argv.push_back(const_cast(a.c_str())); - argv.push_back(nullptr); - ::execv(executable, argv.data()); - std::fprintf(stderr, "unbiased-strata: could not start the engine: %s\n", std::strerror(errno)); - ::_exit(127); - } - ::close(to_child[0]); - ::close(from_child[1]); - in_fd_ = to_child[1]; - out_ = ::fdopen(from_child[0], "r"); - return out_ != nullptr; - } - - /// Reads the engine's start-up lines until it says READY. Loading the model takes minutes. The READY line - /// carries the context the engine actually allocated (`READY 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) { - 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)"; - return false; - } - - /// One request. `on_token` returns false when the client has gone: the engine is told to stop and the rest of - /// its output for this request is read and dropped, so the next request starts clean. - GenResult generate(const std::string& header, const std::vector& ids, - const std::function& on_token) { - GenResult r; - if (!alive_) { r.error = "the engine is not running"; return r; } - std::string req = header; - req.reserve(header.size() + ids.size() * 7 + 2); - for (size_t i = 0; i < ids.size(); ++i) { - if (i) req += ','; - req += std::to_string(ids[i]); - } - req += '\n'; - if (!send(req)) { r.error = "the engine is not running"; return r; } - bool stopped = false; - std::string callback_error; - std::string line; - while (read_line(line)) { - if (line.size() > 2 && line[0] == 'T' && line[1] == ' ') { - if (!stopped) { - bool keep_going = false; - try { - keep_going = on_token((int32_t) std::atoi(line.c_str() + 2)); - } catch (const std::exception& ex) { - callback_error = ex.what(); - std::fprintf(stderr, "unbiased-strata: response formatter failed; stopping and draining request: %s\n", ex.what()); - } - if (!keep_going) { - stopped = true; - send("STOP\n"); - } - } - } else if (line.rfind("DONE ", 0) == 0) { - char finish[32] = {0}; - std::sscanf(line.c_str(), "DONE %lld %lld %lf %lf %31s %lld %lld", &r.produced, &r.prompt_n, &r.prompt_ms, - &r.decode_ms, finish, &r.draft_accepted, &r.draft_offered); - r.finish = finish; - if (r.prompt_n != (long long) ids.size()) { - r.error = "engine response prompt size mismatch: submitted " + std::to_string(ids.size()) + - ", returned " + std::to_string(r.prompt_n); - std::fprintf(stderr, "unbiased-strata: %s; refusing this response\n", r.error.c_str()); - alive_ = false; - return r; - } - r.ok = callback_error.empty(); - if (!r.ok) r.error = "response formatter failed: " + callback_error; - return r; - } else if (line.rfind("ERR", 0) == 0) { - r.error = line.size() > 4 ? line.substr(4) : "the engine reported an error"; - return r; - } - // PP (prompt progress), RESUME, REUSED and INFO lines need no action here - } - alive_ = false; - r.error = "the engine exited during the request"; - return r; - } - - /// One command line between requests (the caller holds `mu`): the engine's one-line reply whose first word is - /// `reply_prefix` lands in `reply`; an ERR line is the error. `STATS` is the one in use (the server's /health). - bool command(const std::string& line, const char* reply_prefix, std::string& reply, std::string& err) { - if (!alive_) { err = "the engine is not running"; return false; } - if (!send(line + "\n")) { err = "the engine is not running"; return false; } - std::string got; - while (read_line(got)) { - if (got.rfind(reply_prefix, 0) == 0) { reply = got; return true; } - if (got.rfind("ERR", 0) == 0) { err = got.size() > 4 ? got.substr(4) : "the engine reported an error"; return false; } - } - alive_ = false; - err = "the engine exited"; - return false; - } - - void quit() { - if (pid_ > 0) { - send("QUIT\n"); - int status = 0; - for (int i = 0; i < 100 && ::waitpid(pid_, &status, WNOHANG) == 0; ++i) ::usleep(100 * 1000); - ::kill(pid_, SIGKILL); - ::waitpid(pid_, &status, 0); - pid_ = -1; - } - } - - bool reap_exit(std::string& why) { - if (strata_frontend::child_running(pid_, why)) return false; - alive_ = false; - return true; - } - - bool alive() const { return alive_; } - std::mutex mu; // one request at a time: the engine holds one conversation - -private: - bool send(const std::string& s) { - size_t off = 0; - while (off < s.size()) { - const ssize_t n = ::write(in_fd_, s.data() + off, s.size() - off); - if (n <= 0) { alive_ = false; return false; } - off += (size_t) n; - } - return true; - } - - bool read_line(std::string& line) { - char* buf = nullptr; - size_t cap = 0; - const ssize_t n = ::getline(&buf, &cap, out_); - if (n < 0) { std::free(buf); alive_ = false; return false; } - line.assign(buf, (size_t) n); - std::free(buf); - while (!line.empty() && (line.back() == '\n' || line.back() == '\r')) line.pop_back(); - return true; - } - - pid_t pid_ = -1; - int in_fd_ = -1; - FILE* out_ = nullptr; - std::atomic alive_{true}; -}; - -} diff --git a/frontend/engine_backpressure_test.cpp b/frontend/engine_backpressure_test.cpp deleted file mode 100644 index 287dce9..0000000 --- a/frontend/engine_backpressure_test.cpp +++ /dev/null @@ -1,71 +0,0 @@ -#include "engine.hpp" -#include -#include -#include -#include -#include - -// Enough output to fill a Linux pipe, with the same independent stdin reader -// and per-token STOP check as the backend. This requires no model or CUDA. -int fake_backend() { - std::setvbuf(stdout, nullptr, _IONBF, 0); - std::mutex mutex; - std::condition_variable ready; - std::deque commands; - std::atomic stop{false}; - auto reader = std::thread([&] { - std::string input; - char byte; - while (::read(0, &byte, 1) == 1) { - if (byte != '\n') { input += byte; continue; } - if (input == "STOP") { stop.store(true); input.clear(); continue; } - const bool quit = input == "QUIT"; - { std::lock_guard lock(mutex); commands.push_back(input); } - input.clear(); ready.notify_one(); - if (quit) return; - } - }); - std::puts("READY"); - for (;;) { - std::unique_lock lock(mutex); - ready.wait(lock, [&] { return !commands.empty(); }); - auto command = commands.front(); commands.pop_front(); lock.unlock(); - if (command == "QUIT") break; - stop.store(false); - const int token = command.find("99") != std::string::npos ? 99 : 11; - int count = 0; - while (count < 100000) { - std::printf("T %d\n", token); ++count; - if (stop.load()) break; - } - std::printf("DONE %d 1 1 1 stop 0 0\n", count); - } - reader.join(); - return 0; -} - -int main(int argc, char** argv) { - if (argc > 1) return fake_backend(); - strata_frontend::Engine engine; - std::string error; - assert(engine.start({argv[0], "--fake-backend"}, error, argv[0])); - assert(engine.wait_ready(error)); - auto failed = engine.generate("GEN 100000 ", {11}, [](int32_t) -> bool { - throw std::runtime_error("partial tool JSON formatter failure"); - }); - assert(!failed.ok); - int count = 0; - auto next = engine.generate("GEN 100000 ", {99}, [&](int32_t token) { - assert(token == 99); ++count; return true; - }); - assert(next.ok && count == 100000); - auto cancel = engine.generate("GEN 100000 ", {11}, [](int32_t) { return false; }); - assert(cancel.ok); - count = 0; - next = engine.generate("GEN 100000 ", {99}, [&](int32_t token) { - assert(token == 99); ++count; return true; - }); - assert(next.ok && count == 100000); - engine.quit(); - std::puts("PASS: large responses cannot fill an abandoned pipe or leak into the next request"); -} diff --git a/frontend/engine_entry.cpp b/frontend/engine_entry.cpp deleted file mode 100644 index 29fee7b..0000000 --- a/frontend/engine_entry.cpp +++ /dev/null @@ -1,6 +0,0 @@ -// frontend/engine_entry.cpp - the unmodified Strata engine program, compiled into this binary under another name. -// -// The engine's own source file is included as it is; only its entry point is renamed, so frontend/main.cpp can -// decide whether this process is the HTTP front end or the engine it starts as a child (`--engine`). -#define main strata_engine_main -#include "../src/program/generate.cpp" diff --git a/frontend/engine_test.cpp b/frontend/engine_test.cpp deleted file mode 100644 index 34c1baa..0000000 --- a/frontend/engine_test.cpp +++ /dev/null @@ -1,62 +0,0 @@ -#include "engine.hpp" -#include -#include - -int main(int argc, char** argv) { - if (argc > 1 && std::string(argv[1]) == "--fake-engine") { - std::puts("READY"); std::fflush(stdout); - char* line = nullptr; size_t capacity = 0; - while (::getline(&line, &capacity, stdin) > 0) { - 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"); - std::fflush(stdout); - continue; - } - const int base = request.find("99") != std::string::npos ? 99 : 11; - std::printf("T %d\nT %d\nDONE 2 1 1 1 stop 0 0\n", base, base+1); - std::fflush(stdout); - } - std::free(line); - return 0; - } - strata_frontend::Engine engine; - std::string error; - assert(engine.start({argv[0], "--fake-engine"}, error, argv[0])); - assert(engine.wait_ready(error)); - auto failed = engine.generate("GEN 2 ", {11}, [](int32_t) -> bool { - throw std::runtime_error("synthetic partial tool JSON diff error"); - }); - assert(!failed.ok && failed.error.find("synthetic") != std::string::npos); - std::vector tokens; - auto next = engine.generate("GEN 2 ", {99}, [&](int32_t token) { tokens.push_back(token); return true; }); - assert(next.ok && (tokens == std::vector{99,100})); - auto cancelled = engine.generate("GEN 2 ", {11}, [](int32_t) { return false; }); - assert(cancelled.ok); - tokens.clear(); - next = engine.generate("GEN 2 ", {99}, [&](int32_t token) { tokens.push_back(token); return true; }); - assert(next.ok && (tokens == std::vector{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{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); - auto rejected = engine.generate("GEN 2 ", {99}, [](int32_t) { return true; }); - assert(!rejected.ok && rejected.produced == 0); - engine.quit(); - std::puts("PASS: formatter exceptions and client cancellation drain the old request before the next request"); -} diff --git a/frontend/main.cpp b/frontend/main.cpp deleted file mode 100644 index 95cb851..0000000 --- a/frontend/main.cpp +++ /dev/null @@ -1,829 +0,0 @@ -// frontend/main.cpp - UnbiasedStrata's front end: tokenizer, chat template and an OpenAI-style HTTP endpoint in -// front of the unmodified Strata engine. -// -// One binary, two roles. Started normally it is the front end: it starts a copy of itself with `--engine`, which -// runs the engine's own program (frontend/engine_entry.cpp) in serve mode, and talks to it over a pipe in the -// engine's line protocol (token ids in, token ids out). That is the process model upstream's Python server uses, -// so the engine runs exactly as upstream tested it. -// -// The tokenizer and the chat template come from llama.cpp (the pinned submodule): the GGUF's own vocabulary and -// its own Jinja template. Nothing here opens an outgoing connection. -#include "engine.hpp" -#include "vision.hpp" -#include "chat.h" -#include "common.h" -#include "llama.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -int strata_engine_main(int argc, char** argv); - -namespace { - -// the model id reported on /v1/models and in every completion: the GGUF's base name (`Qwen3.6-35B-A3B-UD-IQ3_XXS`, -// `Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS` for shard 1 without its `-00001-of-00002`), set once the options are parsed -std::string g_model_name = "unbiased-strata"; -std::string model_name_of(const std::string& path) { - std::string b = path.substr(path.find_last_of('/') == std::string::npos ? 0 : path.find_last_of('/') + 1); - if (b.size() > 5 && b.compare(b.size() - 5, 5, ".gguf") == 0) b.resize(b.size() - 5); - const size_t at = b.rfind("-00001-of-"); - if (at != std::string::npos) b.resize(at); - return b.empty() ? std::string("unbiased-strata") : b; -} - -struct Options { - std::string model; // shard 1 of the GGUF - std::string pack; // the prepared pack directory - std::string mtp; // the prepared draft-head directory - std::string mmproj; - int vision_tokens = 1024; - std::string host = "127.0.0.1"; - int port = 8080; - long long ctx = 32768; - int threads = 0; // CPU expert workers; 0 = the engine's default (every physical core) - 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 - std::vector extra; // after `--`: passed to the engine as they are -}; - -void usage() { - std::fprintf(stderr, - "usage: unbiased-strata --model SHARD1.gguf --pack DIR --mtp DIR [options] [-- engine options]\n\n" - " --model PATH the model's first GGUF shard (...-00001-of-00002.gguf); the second must be beside it\n" - " --pack DIR the prepared pack for that model\n" - " --mtp DIR the prepared draft head\n" - " --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" - " --threads N CPU threads for the experts the GPU does not hold (default: every physical core,\n" - " or half the CPU quota inside a container that has one)\n" - " --host ADDR address to listen on (default 127.0.0.1)\n" - " --port N port to listen on (default 8080)\n" - " --vram-cap MIB emulate a smaller card: the engine uses at most MIB of VRAM (a 1080 Ti as 6 GB: 5722)\n" - " --ram-cap GIB bound the engine's RAM expert tier and pinned arena to GIB\n\n" - "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) { - struct stat st; - return ::stat(p.c_str(), &st) == 0; -} - -// ---------------------------------------------------------------------------------------------------- the engine - -using strata_frontend::Engine; -using strata_frontend::GenResult; - -// ------------------------------------------------------------------------------------------------ text handling - -/// The length of the longest prefix of `s` that does not end inside a UTF-8 character. -size_t utf8_complete_prefix(const std::string& s) { - size_t i = s.size(); - int back = 0; - while (i > 0 && back < 4) { - const unsigned char c = (unsigned char) s[i - 1]; - ++back; - if ((c & 0xC0) == 0x80) { --i; continue; } // a continuation byte: keep looking for its lead - const int need = c >= 0xF0 ? 4 : c >= 0xE0 ? 3 : c >= 0xC0 ? 2 : 1; - return need > back ? i - 1 : s.size(); - } - return s.size(); -} - -std::string make_id() { - static std::mt19937_64 rng{std::random_device{}()}; - static std::mutex mu; - std::lock_guard lk(mu); - char b[40]; - std::snprintf(b, sizeof b, "chatcmpl-%016llx", (unsigned long long) rng()); - return b; -} - -long long now_s() { - return (long long) std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()).count(); -} - -void json_error(httplib::Response& res, int status, const std::string& message, const char* type) { - common_json e = common_json::object(); - e["error"] = common_json::object(); - e["error"]["message"] = message; - e["error"]["type"] = type; - res.status = status; - res.set_content(e.dump_safe(), "application/json"); -} - -// ------------------------------------------------------------------------------------------------- the request - -struct Prepared { - std::shared_ptr images; - std::vector ids; - std::string header; // "GEN key=value ... " - the ids follow - std::string request_id; - common_chat_parser_params parser; // how to split the output into reasoning, answer and tool calls - 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 call_ids; - - std::vector 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 diffs = common_chat_msg_diff::compute_diffs(msg, now); - msg = now; - return diffs; - } -}; - -struct Server { - Options opt; - Engine engine; - strata_frontend::Vision vision; - llama_model* model = nullptr; - const llama_vocab* vocab = nullptr; - common_chat_templates_ptr tmpls; - - /// Parses an OpenAI chat request, renders the model's chat template and tokenizes the result. - bool prepare(const common_json& body, Prepared& p, std::string& err) { - if (!body.is_object() || !body.contains("messages")) { err = "the request needs a \"messages\" array"; return false; } - common_chat_templates_inputs in; - common_json messages = body.at("messages"); - std::vector markers; - std::vector> images; - { - std::lock_guard lock(engine.mu); - for (auto& message : messages) { - if (!message.contains("content") || !message.at("content").is_array()) continue; - for (auto& part : message["content"]) { - if (part.value("type", "") != "image_url") continue; - if (images.size() >= 32) throw std::invalid_argument("at most 32 images per request"); - const std::string url = part.at("image_url").at("url").get(); - images.push_back(vision.encode(url)); - markers.push_back("UNBIASED_IMAGE_" + make_id() + "_" + std::to_string(markers.size())); - part = common_json::object(); - part["type"] = "media_marker"; part["text"] = markers.back(); - } - } - } - in.messages = common_chat_msgs_parse_oaicompat(messages); - if (body.contains("tools") && body.at("tools").is_array() && body.at("tools").size() > 0) { - in.tools = common_chat_tools_parse_oaicompat(body.at("tools")); - if (body.contains("tool_choice") && body.at("tool_choice").is_string()) - in.tool_choice = common_chat_tool_choice_parse_oaicompat(body.at("tool_choice").get()); - const auto caps = common_chat_templates_get_caps(tmpls.get()); - in.parallel_tool_calls = body.value("parallel_tool_calls", caps.at("supports_parallel_tool_calls")); - } - in.add_generation_prompt = true; - in.use_jinja = true; - in.reasoning_format = COMMON_REASONING_FORMAT_DEEPSEEK; // reasoning goes to "reasoning_content" - in.enable_thinking = true; - // thinking: OpenAI's reasoning_effort, or the llama.cpp / vLLM convention chat_template_kwargs.enable_thinking - if (body.contains("reasoning_effort") && body.at("reasoning_effort").is_string()) { - const std::string effort = body.at("reasoning_effort").get(); - if (effort == "none") in.enable_thinking = false; - else in.chat_template_kwargs["reasoning_effort"] = common_json(effort).dump(); - } - if (body.contains("chat_template_kwargs") && body.at("chat_template_kwargs").is_object()) { - const common_json& kw = body.at("chat_template_kwargs"); - if (kw.contains("enable_thinking") && kw.at("enable_thinking").is_boolean()) - in.enable_thinking = kw.at("enable_thinking").get(); - 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(); - } - const common_chat_params cp = common_chat_templates_apply(tmpls.get(), in); - std::string rendered = cp.prompt; - if (images.empty()) { - p.ids = common_tokenize(vocab, rendered, false, true); - } else { - const auto pad = common_tokenize(vocab, "<|image_pad|>", false, true); - const auto literal_pad = common_tokenize(vocab, "<|image_pad|>", false, false); - const auto start = common_tokenize(vocab, "<|vision_start|>", false, true); - const auto end = common_tokenize(vocab, "<|vision_end|>", false, true); - if (pad.size() != 1 || start.size() != 1 || end.size() != 1) - throw std::runtime_error("model does not have the expected image special tokens"); - auto text_ids = [&](const std::string& text) { - for (auto id : common_tokenize(vocab, text, false, true)) { - if (id == pad[0]) p.ids.insert(p.ids.end(), literal_pad.begin(), literal_pad.end()); - else p.ids.push_back(id); - } - }; - size_t offset = 0; rendered.clear(); - for (size_t i = 0; i < images.size(); ++i) { - auto at = cp.prompt.find(markers[i], offset); - if (at == std::string::npos || cp.prompt.find(markers[i], at+markers[i].size()) != std::string::npos) - throw std::invalid_argument("chat template did not preserve each image exactly once"); - auto text = cp.prompt.substr(offset, at-offset); - text_ids(text); rendered += text + "<|vision_start|>"; - p.ids.push_back(start[0]); - p.ids.insert(p.ids.end(), images[i]->tokens, pad[0]); - for (int j = 0; j < images[i]->tokens; ++j) rendered += "<|image_pad|>"; - p.ids.push_back(end[0]); rendered += "<|vision_end|>"; - offset = at + markers[i].size(); - } - auto tail = cp.prompt.substr(offset); text_ids(tail); rendered += tail; - p.images = std::make_shared(); - strata_frontend::write_images(*p.images, images); - } - if (p.ids.empty()) { err = "the prompt is empty"; return false; } - - p.parser = common_chat_parser_params(cp); - p.parser.reasoning_format = COMMON_REASONING_FORMAT_DEEPSEEK; - p.parser.parse_tool_calls = true; - if (!cp.parser.empty()) p.parser.parser.load(cp.parser); - - // The engine refuses a request unless prompt + max_new + 8 <= context (generate.cpp, the GEN handler), so - // the slots it keeps back are not ours to promise. Without this a client that asks for "as much as fits" - // (pi sends max_tokens 32768 on a 64K card) was refused on every prompt longer than ctx - max_tokens. - constexpr long long kEngineReserve = 8; - const long long n = (long long) p.ids.size(); - if (n + 1 + kEngineReserve > opt.ctx) { - err = "the prompt is " + std::to_string(n) + " tokens, which does not fit the context of " + - std::to_string(opt.ctx); - return false; - } - long long max_new = opt.ctx - n - kEngineReserve; - 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(); - if (want >= 1) max_new = std::min(max_new, want); - break; - } - p.max_new = max_new; - p.stream = body.value("stream", false); - - // sampling: greedy unless the request sets a temperature above zero - std::string keys; - const double temperature = body.contains("temperature") && body.at("temperature").is_number() - ? body.at("temperature").get() : 0.0; - if (temperature > 0.0) { - const double top_p = body.contains("top_p") && body.at("top_p").is_number() ? body.at("top_p").get() : 0.95; - long long top_k = body.contains("top_k") && body.at("top_k").is_number() ? body.at("top_k").get() : 20; - top_k = std::max(1LL, std::min(64LL, top_k)); // the engine's sampler takes 1..64 - unsigned long long seed; - if (body.contains("seed") && body.at("seed").is_number()) seed = (unsigned long long) body.at("seed").get(); - else seed = std::random_device{}(); - char b[160]; - std::snprintf(b, sizeof b, " temperature=%g top_p=%g top_k=%lld seed=%llu", temperature, top_p, top_k, seed); - keys += b; - if (body.contains("min_p") && body.at("min_p").is_number()) { - std::snprintf(b, sizeof b, " min_p=%g", body.at("min_p").get()); - keys += b; - } - } - for (const auto& kv : {std::pair{"presence_penalty", "penalty_present"}, - std::pair{"frequency_penalty", "penalty_freq"}, - std::pair{"repeat_penalty", "penalty_repeat"}}) - if (body.contains(kv.first) && body.at(kv.first).is_number()) { - char b[64]; - std::snprintf(b, sizeof b, " %s=%g", kv.second, body.at(kv.first).get()); - keys += b; - if (keys.find("penalty_last_n") == std::string::npos) keys += " penalty_last_n=64"; - } - p.header = (p.images ? "GENI " : "GEN ") + std::to_string(max_new) + keys + " " + - (p.images ? p.images->path + " " : ""); - // Opt-in provenance capture: the exact first rendered request this - // process serves, including token IDs and the engine sampling header. - if (const char* path = std::getenv("SUGMEOFF_CAPTURE_FIRST_PROMPT")) { - if (FILE* f = std::fopen(path, "wx")) { - common_json capture = common_json::object(); - capture["request"] = body; - capture["rendered_prompt"] = rendered; - capture["token_ids"] = p.ids; - capture["engine_header"] = p.header; - const std::string text = capture.dump_safe(); - if (std::fwrite(text.data(), 1, text.size(), f) != text.size()) - std::fprintf(stderr, "unbiased-strata: prompt capture write failed: %s\n", path); - std::fclose(f); - } - } - return true; - } - - common_json usage_json(const GenResult& r) const { - common_json u = common_json::object(); - u["prompt_tokens"] = r.prompt_n; - u["completion_tokens"] = r.produced; - u["total_tokens"] = r.prompt_n + r.produced; - return u; - } - - common_json timings_json(const GenResult& r) const { - common_json t = common_json::object(); - t["prompt_n"] = r.prompt_n; - t["prompt_ms"] = r.prompt_ms; - t["prompt_per_second"] = r.prompt_ms > 0 ? 1000.0 * (double) r.prompt_n / r.prompt_ms : 0.0; - t["predicted_n"] = r.produced; - t["predicted_ms"] = r.decode_ms; - t["predicted_per_second"] = r.decode_ms > 0 ? 1000.0 * (double) r.produced / r.decode_ms : 0.0; - t["draft_n"] = r.draft_offered; - t["draft_n_accepted"] = r.draft_accepted; - return t; - } - - /// Runs one request. The text produced so far is parsed by llama.cpp's chat parser after every token, and - /// `emit` gets what changed (reasoning and answer text as they grow, tool calls once the message is complete: - /// see StreamParse); it returns false when the client has gone. `final_msg` is the whole parsed message. - /// `keepalive`, when given, is called whenever 15 s pass without an emit (a long tool call is silent while - /// its arguments are written): the stream writes an SSE comment, which keeps clients with an idle timeout - /// (pi: 5 minutes) attached and notices a client that has gone, so the generation is cancelled instead of - /// running to the end for nobody. - GenResult run(const Prepared& p, common_chat_msg& final_msg, - const std::function&)>& emit, - const std::function& keepalive = {}) { - std::lock_guard lk(engine.mu); - std::fprintf(stderr, "unbiased-strata: request %s start: prompt=%zu header=%s\n", - p.request_id.c_str(), p.ids.size(), p.header.c_str()); - std::string text, pending; - StreamParse parse; - common_chat_msg& msg = parse.msg; - bool client_ok = true; - auto last_write = std::chrono::steady_clock::now(); - auto update = [&](bool partial) { - const std::vector 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; - pending += common_token_to_piece(vocab, id, /*special=*/true); - const size_t n = utf8_complete_prefix(pending); - if (n > 0) { - text.append(pending, 0, n); - pending.erase(0, n); - if (p.stream) update(true); // a whole response is parsed once, at the end - } - 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; - }); - text += pending; - try { - update(false); - } catch (const std::exception& ex) { - r.ok = false; - r.error = std::string("response formatter failed: ") + ex.what(); - std::fprintf(stderr, "unbiased-strata: final response formatter failed: %s\n", ex.what()); - } - final_msg = msg; - if (final_msg.role.empty()) final_msg.role = "assistant"; - if (final_msg.tool_calls.empty() && text.find("") != std::string::npos) { - // The parser accepts a message with no tool call even when the text holds one it could not - // match (see third_party/llama.cpp/common/parsers/qwen3-coder.cpp); say so, with the text. - std::fprintf(stderr, "unbiased-strata: request %s: the output contains but no tool call was " - "parsed; the client sees finish=stop. raw-output-begin\n%s\n" - "unbiased-strata: request %s raw-output-end\n", - p.request_id.c_str(), text.c_str(), p.request_id.c_str()); - } - if (r.error.find("response formatter failed") == 0) { - std::fprintf(stderr, "unbiased-strata: request %s formatter-input-begin\n%s\n" - "unbiased-strata: request %s formatter-input-end\n", - p.request_id.c_str(), text.c_str(), p.request_id.c_str()); - } - std::fprintf(stderr, "unbiased-strata: request %s end: ok=%d prompt=%lld generated=%lld finish=%s error=%s\n", - p.request_id.c_str(), r.ok ? 1 : 0, r.prompt_n, r.produced, r.finish.c_str(), r.error.c_str()); - return r; - } - - static const char* finish_reason(const GenResult& r, const common_chat_msg& msg) { - if (!msg.tool_calls.empty()) return "tool_calls"; - return r.finish == "stop" ? "stop" : "length"; - } - - void handle_chat(const httplib::Request& req, httplib::Response& res) { - if (!engine.alive()) return json_error(res, 503, "the engine is not running", "server_error"); - const common_json body = common_json::parse_no_throw(req.body); - if (body.is_discarded()) return json_error(res, 400, "the request body is not valid JSON", "invalid_request_error"); - auto prep = std::make_shared(); - std::string err; - try { - if (!prepare(body, *prep, err)) return json_error(res, 400, err, "invalid_request_error"); - } catch (const std::exception& ex) { - return json_error(res, 400, ex.what(), "invalid_request_error"); - } - const std::string id = make_id(); - prep->request_id = id; - const long long created = now_s(); - - if (!prep->stream) { - common_chat_msg msg; - const GenResult r = run(*prep, msg, [](const std::vector&) { return true; }); - if (!r.ok) return json_error(res, 500, r.error, "server_error"); - common_json choice = common_json::object(); - choice["index"] = 0; - choice["message"] = msg.to_json_oaicompat(); - choice["finish_reason"] = finish_reason(r, msg); - common_json out = common_json::object(); - out["id"] = id; - out["object"] = "chat.completion"; - out["created"] = created; - out["model"] = g_model_name; - out["choices"] = common_json::array(); - out["choices"].push_back(choice); - out["usage"] = usage_json(r); - out["timings"] = timings_json(r); - res.set_content(out.dump_safe(), "application/json"); - return; - } - - res.set_header("Cache-Control", "no-cache"); - res.set_header("X-Accel-Buffering", "no"); - res.set_chunked_content_provider("text/event-stream", [this, prep, id, created](size_t, httplib::DataSink& sink) { - auto chunk = [&](const common_json& delta, const char* finish, const GenResult* done) { - common_json choice = common_json::object(); - choice["index"] = 0; - choice["delta"] = delta; - if (finish) choice["finish_reason"] = finish; else choice["finish_reason"] = nullptr; - common_json out = common_json::object(); - out["id"] = id; - out["object"] = "chat.completion.chunk"; - out["created"] = created; - 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); } - const std::string s = "data: " + out.dump_safe() + "\n\n"; - return sink.write(s.data(), s.size()); - }; - common_json first = common_json::object(); - first["role"] = "assistant"; - first["content"] = ""; - bool ok = chunk(first, nullptr, nullptr); - common_chat_msg msg; - const GenResult r = run(*prep, msg, [&](const std::vector& diffs) { - for (const common_chat_msg_diff& df : diffs) { - common_json d = common_json::object(); - if (!df.reasoning_content_delta.empty()) d["reasoning_content"] = df.reasoning_content_delta; - if (!df.content_delta.empty()) d["content"] = df.content_delta; - if (df.tool_call_index != std::string::npos) { - common_json fn = common_json::object(); - if (!df.tool_call_delta.name.empty()) fn["name"] = df.tool_call_delta.name; - fn["arguments"] = df.tool_call_delta.arguments; - common_json tc = common_json::object(); - tc["index"] = (long long) df.tool_call_index; - if (!df.tool_call_delta.id.empty()) { tc["id"] = df.tool_call_delta.id; tc["type"] = "function"; } - tc["function"] = fn; - d["tool_calls"] = common_json::array(); - d["tool_calls"].push_back(tc); - } - if (d.size() == 0) continue; - ok = ok && chunk(d, nullptr, nullptr); - } - return ok; - }, [&]() { - static const std::string ka = ": keepalive\n\n"; // an SSE comment: every client ignores it - ok = ok && sink.write(ka.data(), ka.size()); - return ok; - }); - if (ok) { - if (r.ok) { - chunk(common_json::object(), finish_reason(r, msg), &r); - } else { - common_json e = common_json::object(); - e["error"] = common_json::object(); - e["error"]["message"] = r.error; - e["error"]["type"] = "server_error"; - const std::string s = "data: " + e.dump_safe() + "\n\n"; - sink.write(s.data(), s.size()); - } - static const std::string end = "data: [DONE]\n\n"; - sink.write(end.data(), end.size()); - } - sink.done(); - return true; - }); - } -}; - -Server* g_server = nullptr; -httplib::Server* g_http = nullptr; - -void on_signal(int) { - if (g_http) g_http->stop(); -} - -void quiet_log(ggml_log_level level, const char* text, void*) { - if (level == GGML_LOG_LEVEL_ERROR || level == GGML_LOG_LEVEL_WARN) std::fputs(text, stderr); -} - -// The CPU expert workers to ask the engine for when --threads is not given: 0 lets the engine use every physical -// core it sees. Inside a container it sees the host's cores, not its own share, and that many workers on a small -// quota throttle one another; so with a cgroup CPU quota below the visible CPUs the quota decides. The quota -// counts hardware threads and the engine wants cores, hence the halving when SMT is on. -int default_threads() { - long long quota = 0, period = 0; - char q[32] = ""; - if (FILE* f = std::fopen("/sys/fs/cgroup/cpu.max", "r")) { // cgroup v2 - if (std::fscanf(f, "%31s %lld", q, &period) == 2 && std::strcmp(q, "max") != 0) quota = std::atoll(q); - std::fclose(f); - } else if (FILE* f1 = std::fopen("/sys/fs/cgroup/cpu/cpu.cfs_quota_us", "r")) { // cgroup v1 - if (std::fscanf(f1, "%lld", "a) != 1) quota = 0; - std::fclose(f1); - if (FILE* f2 = std::fopen("/sys/fs/cgroup/cpu/cpu.cfs_period_us", "r")) { - if (std::fscanf(f2, "%lld", &period) != 1) period = 0; - std::fclose(f2); - } - } - if (quota <= 0 || period <= 0) return 0; - const long long cpus = (quota + period / 2) / period; - if (cpus < 1 || cpus >= sysconf(_SC_NPROCESSORS_ONLN)) return 0; - int smt = 0; - if (FILE* f = std::fopen("/sys/devices/system/cpu/smt/active", "r")) { - if (std::fscanf(f, "%d", &smt) != 1) smt = 0; - std::fclose(f); - } - return (int) std::max(smt ? cpus / 2 : cpus, 1); -} - -bool parse_args(int argc, char** argv, Options& o) { - for (int i = 1; i < argc; ++i) { - const std::string a = argv[i]; - auto next = [&](const char* name) -> std::string { - if (i + 1 >= argc) { std::fprintf(stderr, "unbiased-strata: %s needs a value\n", name); std::exit(2); } - return argv[++i]; - }; - if (a == "--model") o.model = next("--model"); - else if (a == "--mmproj") o.mmproj = next("--mmproj"); - else if (a == "--vision-tokens") o.vision_tokens = std::atoi(next("--vision-tokens").c_str()); - else if (a == "--pack") o.pack = next("--pack"); - else if (a == "--mtp") o.mtp = next("--mtp"); - 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 == "--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]; - // one GPU only: the engine's multi-GPU and remote-expert modes are not part of this fork - for (const char* no : {"--gpus", "--layer-split", "--split-device", "--peer-device", "--peer-slots", - "--remote-expert", "--vision", "--batch"}) - if (e.rfind(no, 0) == 0) { - std::fprintf(stderr, "unbiased-strata: %s is not supported here (use --mmproj for image input)\n", e.c_str()); - std::exit(2); - } - o.extra.push_back(e); - } - } - else if (a == "-h" || a == "--help") return false; - else { std::fprintf(stderr, "unbiased-strata: unknown option %s\n\n", a.c_str()); return false; } - } - return !o.model.empty() && !o.pack.empty() && !o.mtp.empty(); -} - -} // namespace - -int main(int argc, char** argv) { - if (argc > 1 && std::strcmp(argv[1], "--engine") == 0) return strata_engine_main(argc - 1, argv + 1); - - Server srv; - Options& o = srv.opt; - if (!parse_args(argc, argv, o)) { usage(); return 2; } - g_model_name = model_name_of(o.model); - - // every file the engine needs must already be here: nothing is fetched - // Flash-Next ships as two shards and the second holds the PLE table, so it is the engine's --ple-gguf; a one-file - // model (Qwen3.6-35B-A3B) has no PLE and no second shard, and the engine decides from the file's architecture - std::string shard2 = o.model; - const size_t at = shard2.rfind("-00001-of-00002"); - if (at != std::string::npos) shard2.replace(at, 15, "-00002-of-00002"); - else shard2.clear(); - const std::string profile = o.pack + "/expert-profile.bin"; - // draft_vocab.bin is the draft head's vocabulary subset; a Qwen3.6 draft pack built with the full head - // (tools/mtp_qwen36_pack.py --full-head) has none and the engine then drafts over the whole vocabulary - for (const std::string& f : {o.model, shard2, o.pack + "/index.txt", profile, o.mtp + "/experts.bin"}) - if (!f.empty() && !file_exists(f)) { std::fprintf(stderr, "unbiased-strata: missing file: %s\n", f.c_str()); return 2; } - 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)) { - std::fprintf(stderr, "unbiased-strata: --mmproj must exist and --vision-tokens must be 16..4096\n"); return 2; - } - // the engine, started first: loading takes minutes, and it must be forked before any thread exists - std::vector eargs = { - "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)}; - 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) { - o.threads = default_threads(); - if (o.threads > 0) - std::fprintf(stderr, "unbiased-strata: this container's CPU quota gives %d expert threads (--threads N overrides)\n", - o.threads); - } - if (o.threads > 0) { eargs.push_back("--pool-workers"); eargs.push_back(std::to_string(o.threads)); } - for (const std::string& e : o.extra) eargs.push_back(e); - std::signal(SIGPIPE, SIG_IGN); - std::string err; - if (!srv.engine.start(eargs, err)) { std::fprintf(stderr, "unbiased-strata: %s\n", err.c_str()); return 1; } - - // the tokenizer and the chat template, from the GGUF itself - llama_log_set(quiet_log, nullptr); - llama_backend_init(); - llama_model_params mp = llama_model_default_params(); - mp.vocab_only = true; - srv.model = llama_model_load_from_file(o.model.c_str(), mp); - if (srv.model == nullptr) { - std::fprintf(stderr, "unbiased-strata: could not read the tokenizer from %s\n", o.model.c_str()); - srv.engine.quit(); - return 1; - } - srv.vocab = llama_model_get_vocab(srv.model); - srv.tmpls = common_chat_templates_init(srv.model, ""); - if (!o.mmproj.empty()) { - try { srv.vision.init(o.mmproj, srv.model, o.threads, o.vision_tokens); } - catch (const std::exception& ex) { - std::fprintf(stderr, "unbiased-strata: %s\n", ex.what()); srv.engine.quit(); return 1; - } - } - - std::fprintf(stderr, "unbiased-strata: loading the model (this takes a few minutes)...\n"); - long long engine_ctx = 0; - if (!srv.engine.wait_ready(err, &engine_ctx)) { - std::fprintf(stderr, "unbiased-strata: %s\n", err.c_str()); - srv.engine.quit(); - return 1; - } - if (engine_ctx > 0 && engine_ctx != o.ctx) { // the engine's VRAM plan lowered the context: serve that one - std::fprintf(stderr, "unbiased-strata: the engine allocated a context of %lld tokens, not the %lld requested; " - "requests are bounded by %lld\n", engine_ctx, o.ctx, engine_ctx); - o.ctx = engine_ctx; - } - - httplib::Server http; - g_server = &srv; - g_http = &http; - // /health: ok or error, plus the engine's expert tiers and counters when it is between requests (STATS: VRAM - // slots and how many hold an expert, RAM copies, mapped experts, tokens served, VRAM hits of lookups, RAM-copy - // and file reads, warm hints, major page faults). During a request the last reading is served, marked stale. - // httplib serves /health from several threads: the last reading has its own lock (engine.mu is the engine's, - // taken only to ask), and every read of it is a copy under that lock. - static std::mutex stats_mu; - static std::string last_stats; - http.Get("/health", [&](const httplib::Request&, httplib::Response& res) { - res.status = srv.engine.alive() ? 200 : 503; - std::string body = srv.engine.alive() ? "{\"status\":\"ok\"" : "{\"status\":\"error\""; - if (srv.engine.alive()) { - std::unique_lock 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 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 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"] = g_model_name; - m["object"] = "model"; - m["owned_by"] = "local"; - m["context_length"] = srv.opt.ctx; - m["input_modalities"] = common_json::array(); - m["input_modalities"].push_back("text"); - if (srv.vision.enabled()) m["input_modalities"].push_back("image"); - common_json out = common_json::object(); - out["object"] = "list"; - out["data"] = common_json::array(); - out["data"].push_back(m); - res.set_content(out.dump_safe(), "application/json"); - }); - http.Post("/v1/chat/completions", [&](const httplib::Request& req, httplib::Response& res) { - srv.handle_chat(req, res); - }); - http.set_payload_max_length(64 * 1024 * 1024); - http.set_read_timeout(600, 0); - http.set_write_timeout(600, 0); - std::signal(SIGINT, on_signal); - std::signal(SIGTERM, on_signal); - - if (!http.bind_to_port(o.host, o.port)) { - std::fprintf(stderr, "unbiased-strata: could not listen on %s:%d\n", o.host.c_str(), o.port); - srv.engine.quit(); - return 1; - } - std::fprintf(stderr, "unbiased-strata: ready on http://%s:%d (context %lld tokens)\n", o.host.c_str(), o.port, o.ctx); - // The engine watchdog intentionally aborts a stuck child. Exit the HTTP - // parent too so systemd's Restart=on-failure reloads the complete service. - // Do not fork a replacement from this multithreaded HTTP process. - std::atomic shutting_down{false}; - std::thread supervisor([&] { - while (!shutting_down.load()) { - std::string why; - if (srv.engine.reap_exit(why)) { - std::fprintf(stderr, "unbiased-strata: %s; exiting frontend for service restart\n", why.c_str()); - std::fflush(stderr); - std::_Exit(1); - } - if (!srv.engine.alive()) { - std::fprintf(stderr, "unbiased-strata: engine protocol failed; exiting frontend for service restart\n"); - std::fflush(stderr); - std::_Exit(1); - } - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } - }); - http.listen_after_bind(); - shutting_down.store(true); - supervisor.join(); - - std::fprintf(stderr, "unbiased-strata: stopping\n"); - srv.engine.quit(); - llama_model_free(srv.model); - return 0; -} diff --git a/frontend/vision.hpp b/frontend/vision.hpp deleted file mode 100644 index 79dde07..0000000 --- a/frontend/vision.hpp +++ /dev/null @@ -1,153 +0,0 @@ -#pragma once -#include "common.h" -#include "gguf.h" -#include "mtmd.h" -#include "mtmd-helper.h" -#include -#include -#include -#include -#include -#include -#include -#include - -namespace strata_frontend { -// Private per-request file, retained through streaming completion/cancellation. -struct ImageFile { - std::string path; - ImageFile() { - char name[] = "/tmp/unbiased-strata-image-XXXXXX"; - int fd = mkstemp(name); - if (fd < 0) throw std::runtime_error("cannot create image embedding file"); - close(fd); path = name; - } - ~ImageFile() { if (!path.empty()) unlink(path.c_str()); } - ImageFile(const ImageFile&) = delete; - ImageFile& operator=(const ImageFile&) = delete; -}; - -inline std::vector image_data(const std::string& url) { - const size_t comma = url.find(','); - if (url.rfind("data:image/", 0) != 0 || comma == std::string::npos || - comma < 7 || url.substr(comma - 7, 7) != ";base64") - throw std::invalid_argument("image_url must contain a base64 data:image URL (PNG, JPEG, BMP or GIF)"); - const std::string data = url.substr(comma + 1); - if (data.empty() || data.size() > 32 * 1024 * 1024 || data.size() % 4) - throw std::invalid_argument("empty, oversized or malformed base64 image"); - const std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - std::array table; table.fill(-1); - for (size_t i = 0; i < alphabet.size(); ++i) table[(unsigned char) alphabet[i]] = (int) i; - std::vector out; out.reserve(data.size() / 4 * 3); - for (size_t i = 0; i < data.size(); i += 4) { - int a = table[(unsigned char)data[i]], b = table[(unsigned char)data[i+1]]; - bool p2 = data[i+2] == '=', p3 = data[i+3] == '='; - int c = p2 ? 0 : table[(unsigned char)data[i+2]], d = p3 ? 0 : table[(unsigned char)data[i+3]]; - if (a < 0 || b < 0 || c < 0 || d < 0 || (p2 && !p3) || - ((p2 || p3) && i + 4 != data.size()) || (p2 && (b & 15)) || (!p2 && p3 && (c & 3))) - throw std::invalid_argument("malformed base64 image"); - out.push_back((a << 2) | (b >> 4)); - if (!p2) out.push_back((b << 4) | (c >> 2)); - if (!p3) out.push_back((c << 6) | d); - } - return out; -} -struct EncodedImage { - int32_t tokens, nx, ny, width; - std::vector values; -}; - -// CPU encoder leaves the engine's full VRAM expert cache available. Its callers -// take engine.mu, serializing image encoding and generation just like upstream. -class Vision { - mtmd_context* ctx_ = nullptr; - int width_ = 0; - int max_tokens_ = 1024; - size_t cache_bytes_ = 0; - std::map> cache_; -public: - ~Vision() { if (ctx_) mtmd_free(ctx_); } - bool enabled() const { return ctx_ != nullptr; } - void init(const std::string& path, const llama_model* model, int threads, int max_tokens) { - gguf_init_params gp{true, nullptr}; - auto gg = std::unique_ptr(gguf_init_from_file(path.c_str(), gp), gguf_free); - auto key = gg ? gguf_find_key(gg.get(), "clip.vision.projection_dim") : -1; - if (key < 0) throw std::runtime_error("vision encoder has no projection_dim"); - width_ = (int) gguf_get_val_u32(gg.get(), key); - // the projector must produce rows of the model's own width (2560 for Flash-Next, 2048 for Qwen3.6-35B-A3B); - // the tokenizer-only model the front end holds has no hparams, so the width is read from its metadata - char arch[64] = {0}, val[32] = {0}; - int want = 0; - if (llama_model_meta_val_str(model, "general.architecture", arch, sizeof arch) > 0 && - llama_model_meta_val_str(model, (std::string(arch) + ".embedding_length").c_str(), val, sizeof val) > 0) - want = std::atoi(val); - if (want <= 0) throw std::runtime_error("cannot read the model's embedding width"); - if (width_ != want) - throw std::runtime_error("vision projector width " + std::to_string(width_) + - " does not match the model's embedding width " + std::to_string(want)); - max_tokens_ = max_tokens; - auto cp = mtmd_context_params_default(); - cp.use_gpu = false; cp.print_timings = false; cp.warmup = false; - cp.n_threads = threads > 0 ? threads : 8; - cp.image_max_tokens = max_tokens; - ctx_ = mtmd_init_from_file(path.c_str(), model, cp); - if (!ctx_ || !mtmd_support_vision(ctx_)) throw std::runtime_error("cannot load vision encoder: " + path); - } - std::shared_ptr encode(const std::string& url) { - if (!ctx_) throw std::invalid_argument("image input requires starting UnbiasedStrata with --mmproj PATH"); - auto bytes = image_data(url); - auto t0 = std::chrono::steady_clock::now(); - auto bw = mtmd_helper_bitmap_init_from_buf(ctx_, bytes.data(), bytes.size(), false, mtmd_helper_init_opt_default()); - std::unique_ptr bitmap(bw.bitmap, mtmd_bitmap_free); - if (bw.video_ctx) mtmd_helper_video_free(bw.video_ctx); - if (!bitmap || mtmd_bitmap_is_audio(bitmap.get())) throw std::invalid_argument("cannot decode image; use PNG, JPEG, BMP or GIF"); - const char* hash = mtmd_bitmap_get_id(bitmap.get()); - if (!hash || !*hash) throw std::runtime_error("image decoder did not supply a content hash"); - std::string id(hash); - auto cached = cache_.find(id); - if (cached != cache_.end()) return cached->second; - auto chunks = std::unique_ptr(mtmd_input_chunks_init(), mtmd_input_chunks_free); - std::string marker = mtmd_default_marker(); - mtmd_input_text txt{marker.c_str(), marker.size(), false, true}; - const mtmd_bitmap* bm[] = {bitmap.get()}; - if (mtmd_tokenize(ctx_, chunks.get(), &txt, bm, 1)) throw std::invalid_argument("image preprocessing failed"); - const mtmd_input_chunk* image = nullptr; - for (size_t i = 0; i < mtmd_input_chunks_size(chunks.get()); ++i) { - auto ch = mtmd_input_chunks_get(chunks.get(), i); - if (mtmd_input_chunk_get_type(ch) == MTMD_INPUT_CHUNK_TYPE_IMAGE) { - if (image) throw std::invalid_argument("multiple image chunks are unsupported for this model"); - image = ch; - } - } - if (!image) throw std::invalid_argument("no image tokens produced"); - size_t n = mtmd_input_chunk_get_n_tokens(image); - if (!n || n > (size_t)max_tokens_) throw std::invalid_argument("image token count exceeds configured limit"); - if (mtmd_encode_chunk(ctx_, image)) throw std::runtime_error("vision encoding failed"); - auto last = mtmd_image_tokens_get_decoder_pos(mtmd_input_chunk_get_tokens_image(image), 0, n-1); - int nx = (int)last.x + 1, ny = (int)last.y + 1; - if ((size_t)nx * ny != n) throw std::runtime_error("image grid is not rectangular"); - auto result = std::make_shared(); - result->tokens = (int32_t)n; result->nx = nx; result->ny = ny; result->width = width_; - auto values = mtmd_get_output_embd(ctx_); - if (!values) throw std::runtime_error("encoder returned no image embeddings"); - result->values.assign(values, values+n*width_); - size_t size = result->values.size()*sizeof(float); - if (cache_bytes_ + size > 128*1024*1024) { cache_.clear(); cache_bytes_ = 0; } - cache_[id] = result; cache_bytes_ += size; - auto ms = std::chrono::duration(std::chrono::steady_clock::now()-t0).count(); - std::fprintf(stderr, "unbiased-strata: encoded image %.0f ms, %d tokens (%dx%d), CPU\n", ms, result->tokens, nx, ny); - return result; - } -}; -inline void write_images(const ImageFile& file, const std::vector>& images) { - auto f = std::unique_ptr(std::fopen(file.path.c_str(), "wb"), std::fclose); - if (!f) throw std::runtime_error("cannot open image embedding file"); - for (auto& im : images) { - int32_t hdr[] = {0x31455653, im->tokens, im->nx, im->ny, im->width}; - if (std::fwrite(hdr, sizeof(hdr), 1, f.get()) != 1 || - std::fwrite(im->values.data(), sizeof(float), im->values.size(), f.get()) != im->values.size()) - throw std::runtime_error("short write to image embedding file"); - } - if (std::fflush(f.get())) throw std::runtime_error("cannot flush image embedding file"); -} -} // namespace strata_frontend diff --git a/include/strata/artifact/dequant.hpp b/include/strata/artifact/dequant.hpp deleted file mode 100644 index d5a314c..0000000 --- a/include/strata/artifact/dequant.hpp +++ /dev/null @@ -1,292 +0,0 @@ -#pragma once -// src/artifact/dequant.cpp - P1.S3: scalar reference dequantizers, transcribed from ggml. -// -// P1.S3 asks for every encoding present in the Q2_0 file. This starts with the ones on the critical -// path (the routed experts are all Q2_0) plus the trivial element types, and is structured so the -// rest drop in. Source of truth per encoding is quoted in each function. -// -// Q2_0 is the one that matters, and its contract is settled from source in docs/q2_0-contract.md: -// block = { fp16 d; uint8 qs[16] } = 64 elements, 18 bytes -// code {0,1,2,3} -> symbol {-1,0,+1,+2}; v = (code - 1) * d -// 4 codes per byte, LSB-first: byte j/4, bits (j%4)*2 -// QK2_0 = 64 is PROVEN from the artifact's own offset brackets, not assumed (the llama.cpp PR that -// introduced the type used 128; this artifact is 64). -// -// Validation: `--check ` dequantizes real blocks and asserts the STRUCTURAL invariant that -// every output value is one of {-d, 0, +d, +2d} for that block's own scale. That catches bit-order, -// sign and stride bugs, which are the failure modes a dequantizer actually has. It is deliberately -// not a correctness-vs-ggml test - that needs ggml linked, which is P1.S3's next step. - -#include -#include -#include -#include -#include -#include - -#define STRATA_GGUF_MAIN_DISABLED 1 -#include "strata/artifact/gguf_reader.hpp" - -namespace strata { - -// ---- fp16/bf16 -> fp32. Both handle subnormals and infinities; naive shifts do not. -inline float fp16_to_fp32(uint16_t h) { - const uint32_t sign = (uint32_t)(h >> 15) & 1u; - uint32_t exp = (h >> 10) & 0x1Fu, man = h & 0x3FFu, f; - if (exp == 0) { - if (man == 0) - f = sign << 31; - else { - exp = 127 - 15 + 1; - while (!(man & 0x400u)) { - man <<= 1; - --exp; - } - man &= 0x3FFu; - f = (sign << 31) | (exp << 23) | (man << 13); - } - } else if (exp == 31) - f = (sign << 31) | 0x7F800000u | (man << 13); - else - f = (sign << 31) | ((exp - 15 + 127) << 23) | (man << 13); - float out; - std::memcpy(&out, &f, 4); - return out; -} - -inline float bf16_to_fp32(uint16_t h) { - const uint32_t f = (uint32_t)h << 16; - float out; - std::memcpy(&out, &f, 4); - return out; -} - -inline uint16_t read_u16(const uint8_t* p) { - return (uint16_t)(p[0] | (p[1] << 8)); -} - -// ---- Q2_0: 64 elements from an 18-byte block. Mirrors dequantize_row_q2_0 (ggml master 3cf03257). -inline void dequantize_q2_0(const uint8_t* block, float* out) { - const float d = fp16_to_fp32(read_u16(block)); - const uint8_t* qs = block + 2; - for (int j = 0; j < 64; ++j) { - const int byte_index = j / 4; - const int bit_offset = (j % 4) * 2; - const int code = (qs[byte_index] >> bit_offset) & 0x03; - out[j] = (float)(code - 1) * d; // code {0,1,2,3} -> symbol {-1,0,+1,+2} - } -} - -// ---- Q8_0: 32 elements from a 34-byte block. -inline void dequantize_q8_0(const uint8_t* block, float* out) { - const float d = fp16_to_fp32(read_u16(block)); - const int8_t* qs = (const int8_t*)(block + 2); - for (int j = 0; j < 32; ++j) out[j] = (float)qs[j] * d; -} - -// ---- Q4_0: 32 elements from an 18-byte block. Low nibble is element j, high nibble is j+16. -inline void dequantize_q4_0(const uint8_t* block, float* out) { - const float d = fp16_to_fp32(read_u16(block)); - const uint8_t* qs = block + 2; - for (int j = 0; j < 16; ++j) { - out[j] = (float)((int)(qs[j] & 0x0F) - 8) * d; - out[j + 16] = (float)((int)(qs[j] >> 4) - 8) * d; - } -} - -// ---- Q5_0: 32 elements from a 22-byte block. Same nibble layout as Q4_0 plus a 5th bit per element -// packed in qh[4]; the 32 bits of qh are the high bits of elements 0..31 in order. -inline void dequantize_q5_0(const uint8_t* block, float* out) { - const float d = fp16_to_fp32(read_u16(block)); - const uint8_t* qh = block + 2; - const uint8_t* qs = block + 6; - const uint32_t h = - (uint32_t)qh[0] | ((uint32_t)qh[1] << 8) | ((uint32_t)qh[2] << 16) | ((uint32_t)qh[3] << 24); - for (int j = 0; j < 16; ++j) { - const int x0 = (int)(qs[j] & 0x0F) | (int)(((h >> j) & 1u) << 4); - const int x1 = (int)(qs[j] >> 4) | (int)(((h >> (j + 16)) & 1u) << 4); - out[j] = (float)(x0 - 16) * d; - out[j + 16] = (float)(x1 - 16) * d; - } -} -// ---- IQ4_NL: 32 elements from an 18-byte block. Non-linear 4-bit codebook, NOT a linear grid, so -// the table must be exact. Copied verbatim from ggml-common.h `kvalues_iq4nl` at 3cf03257: -// -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113 -// Layout matches dequantize_row_iq4_nl (ggml-quants.c): low nibble is element j, high nibble j+16. -static const int8_t kvalues_iq4nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, - 1, 13, 25, 38, 53, 69, 89, 113}; - -inline void dequantize_iq4_nl(const uint8_t* block, float* out) { - const float d = fp16_to_fp32(read_u16(block)); - const uint8_t* qs = block + 2; - for (int j = 0; j < 16; ++j) { - out[j] = d * (float)kvalues_iq4nl[qs[j] & 0x0F]; - out[j + 16] = d * (float)kvalues_iq4nl[qs[j] >> 4]; - } -} -// ---- Q6_K: 256 elements from a 210-byte super-block, transcribed from dequantize_row_q6_K -// (ggml-quants.c at 3cf03257). Layout: ql[128] low nibbles, qh[64] high 2 bits, scales[16] int8, -// fp16 d LAST. Processed in two 128-element halves, each advancing ql by 64, qh by 32, sc by 8. -// The `sc` indices are is+{0,2,4,6} with is = l/16 - so each 32-element group draws from 8 of the 16 -// scales, and the four output positions within a 32-group use different scales. Easy to get subtly -// wrong, which is why it is transcribed rather than recalled. -inline void dequantize_q6_K(const uint8_t* block, float* out) { - const uint8_t* ql = block; // 128 bytes - const uint8_t* qh = block + 128; // 64 - const int8_t* sc = (const int8_t*)(block + 192); // 16 - const float d = fp16_to_fp32(read_u16(block + 208)); - float* y = out; - for (int n = 0; n < 256; n += 128) { - for (int l = 0; l < 32; ++l) { - const int is = l / 16; - const int q1 = (int)((ql[l + 0] & 0x0F) | (((qh[l] >> 0) & 3) << 4)) - 32; - const int q2 = (int)((ql[l + 32] & 0x0F) | (((qh[l] >> 2) & 3) << 4)) - 32; - const int q3 = (int)((ql[l + 0] >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32; - const int q4 = (int)((ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32; - y[l + 0] = d * (float)sc[is + 0] * (float)q1; - y[l + 32] = d * (float)sc[is + 2] * (float)q2; - y[l + 64] = d * (float)sc[is + 4] * (float)q3; - y[l + 96] = d * (float)sc[is + 6] * (float)q4; - } - y += 128; - ql += 64; - qh += 32; - sc += 8; - } -} -// ---- Q4_K: 256 elements from a 144-byte super-block. Layout is `fp16 d`, `fp16 dmin` (so the FIRST -// four bytes are the scale pair, unlike Q6_K where d is last), `scales[12]`, `qs[128]`. -// Both functions transcribed from ggml-quants.c at 3cf03257. The 6-bit scale/min unpacking in -// get_scale_min_k4 is the part that is impossible to recall reliably: the low 4 bits of the second -// half come from q[j+4], and the high 2 bits from the low halves' top bits (q[j-4] and q[j]). -static inline void get_scale_min_k4(int j, const uint8_t* q, uint8_t& d, uint8_t& m) { - if (j < 4) { - d = q[j] & 63; - m = q[j + 4] & 63; - } else { - d = (q[j + 4] & 0x0F) | ((q[j - 4] >> 6) << 4); - m = (q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4); - } -} - -inline void dequantize_q4_K(const uint8_t* block, float* out) { - const float d = fp16_to_fp32(read_u16(block)); // d - const float mn = fp16_to_fp32(read_u16(block + 2)); // dmin - const uint8_t* scales = block + 4; // 12 bytes - const uint8_t* q = block + 16; // 128 bytes - float* y = out; - int is = 0; - for (int j = 0; j < 256; j += 64) { - uint8_t sc, m; - get_scale_min_k4(is + 0, scales, sc, m); - const float d1 = d * (float)sc, m1 = mn * (float)m; - get_scale_min_k4(is + 1, scales, sc, m); - const float d2 = d * (float)sc, m2 = mn * (float)m; - for (int l = 0; l < 32; ++l) *y++ = d1 * (float)(q[l] & 0x0F) - m1; - for (int l = 0; l < 32; ++l) *y++ = d2 * (float)(q[l] >> 4) - m2; - q += 32; - is += 2; - } -} -// ---- Q5_K: 256 elements from a 176-byte super-block: `fp16 d`, `fp16 dmin`, `scales[12]`, -// `qh[32]`, `qs[128]`. Same shape as Q4_K plus the 5th bit plane. Transcribed from -// dequantize_row_q5_K (ggml-quants.c, 3cf03257). The 5th bits are selected by a mask that SHIFTS LEFT -// BY 2 each 64-element group (u1 = 1,4,16,64; u2 = 2,8,32,128) - a recalled version would very likely -// have used a fixed mask or a shift by 1. -inline void dequantize_q5_K(const uint8_t* block, float* out) { - const float d = fp16_to_fp32(read_u16(block)); - const float mn = fp16_to_fp32(read_u16(block + 2)); - const uint8_t* scales = block + 4; // 12 - const uint8_t* qh = block + 16; // 32 - const uint8_t* ql = block + 48; // 128 - float* y = out; - int is = 0; - uint8_t u1 = 1, u2 = 2; - for (int j = 0; j < 256; j += 64) { - uint8_t sc, m; - get_scale_min_k4(is + 0, scales, sc, m); - const float d1 = d * (float)sc, m1 = mn * (float)m; - get_scale_min_k4(is + 1, scales, sc, m); - const float d2 = d * (float)sc, m2 = mn * (float)m; - for (int l = 0; l < 32; ++l) *y++ = d1 * (float)((ql[l] & 0x0F) + ((qh[l] & u1) ? 16 : 0)) - m1; - for (int l = 0; l < 32; ++l) *y++ = d2 * (float)((ql[l] >> 4) + ((qh[l] & u2) ? 16 : 0)) - m2; - ql += 32; - is += 2; - u1 = (uint8_t)(u1 << 2); - u2 = (uint8_t)(u2 << 2); - } -} -// ---- Q3_K: 256 elements from a 110-byte super-block: `hmask[32]`, `qs[64]`, `scales[12]`, `fp16 d` -// LAST. Transcribed from dequantize_row_q3_K (ggml-quants.c, 3cf03257). This type has NO `dmin` - its -// scales are SIGNED 6-bit with a `- 32` bias - so it does not follow the Q4_K/Q5_K pattern at all. -// Two details that cannot be recalled: -// * the 12 scale bytes are bit-repacked through three 32-bit masks before use (kmask1/2 below), -// because 16 six-bit scales do not fit in 12 bytes linearly; -// * the low 2 bits are offset by -4 when the high bit is CLEAR, i.e. the correction is NEGATIVE. -inline void dequantize_q3_K(const uint8_t* block, float* out) { - const uint8_t* hm = block; // 32 - const uint8_t* q = block + 32; // 64 - const float d_all = fp16_to_fp32(read_u16(block + 108)); - - const uint32_t kmask1 = 0x03030303u, kmask2 = 0x0f0f0f0fu; - uint32_t aux[4] = {0, 0, 0, 0}; - std::memcpy(aux, block + 96, 12); - const uint32_t tmp = aux[2]; - aux[2] = ((aux[0] >> 4) & kmask2) | (((tmp >> 4) & kmask1) << 4); - aux[3] = ((aux[1] >> 4) & kmask2) | (((tmp >> 6) & kmask1) << 4); - aux[0] = (aux[0] & kmask2) | (((tmp >> 0) & kmask1) << 4); - aux[1] = (aux[1] & kmask2) | (((tmp >> 2) & kmask1) << 4); - const int8_t* scales = (const int8_t*)aux; - - float* y = out; - int is = 0; - uint8_t m = 1; // hoisted: ggml declares this BEFORE the n loop, so it does not reset between halves - for (int n = 0; n < 256; n += 128) { - int shift = 0; - for (int j = 0; j < 4; ++j) { - float dl = d_all * (float)(scales[is++] - 32); - for (int l = 0; l < 16; ++l) - *y++ = dl * (float)((int8_t)((q[l + 0] >> shift) & 3) - ((hm[l + 0] & m) ? 0 : 4)); - dl = d_all * (float)(scales[is++] - 32); - for (int l = 0; l < 16; ++l) - *y++ = dl * (float)((int8_t)((q[l + 16] >> shift) & 3) - ((hm[l + 16] & m) ? 0 : 4)); - shift += 2; - m = (uint8_t)(m << 1); - } - q += 32; - } -} -// ---- IQ4_XS: 256 elements from a 136-byte super-block: `fp16 d`, `uint16 scales_h`, `scales_l[4]`, -// `qs[128]`. Transcribed from dequantize_row_iq4_xs (ggml-quants.c, 3cf03257). Reuses the IQ4_NL -// codebook. Eight 32-element groups; each group's scale is 6 bits assembled from the LOW nibble of -// `scales_l[ib/2]` (selected by ib%2) and TWO bits of `scales_h` at shift 2*ib - so the high bits come -// from a 16-bit field indexed by group, not from a byte array. Then `- 32`, as in Q3_K. -inline void dequantize_iq4_xs(const uint8_t* block, float* out) { - const float d = fp16_to_fp32(read_u16(block)); - const uint16_t scales_h = read_u16(block + 2); - const uint8_t* scales_l = block + 4; // 4 - const uint8_t* qs = block + 8; // 128 - float* y = out; - for (int ib = 0; ib < 8; ++ib) { - const int ls = ((scales_l[ib / 2] >> (4 * (ib % 2))) & 0x0F) | (((scales_h >> (2 * ib)) & 3) << 4); - const float dl = d * (float)(ls - 32); - for (int j = 0; j < 16; ++j) { - y[j + 0] = dl * (float)kvalues_iq4nl[qs[j] & 0x0F]; - y[j + 16] = dl * (float)kvalues_iq4nl[qs[j] >> 4]; - } - y += 32; - qs += 16; - } -} -// ---- element types -inline void dequantize_f32(const uint8_t* p, float* out, int n) { - std::memcpy(out, p, (size_t)n * 4); -} -inline void dequantize_f16(const uint8_t* p, float* out, int n) { - for (int i = 0; i < n; ++i) out[i] = fp16_to_fp32(read_u16(p + 2 * i)); -} -inline void dequantize_bf16(const uint8_t* p, float* out, int n) { - for (int i = 0; i < n; ++i) out[i] = bf16_to_fp32(read_u16(p + 2 * i)); -} - -} // namespace strata diff --git a/include/strata/artifact/gguf_reader.hpp b/include/strata/artifact/gguf_reader.hpp deleted file mode 100644 index 3dad4a8..0000000 --- a/include/strata/artifact/gguf_reader.hpp +++ /dev/null @@ -1,627 +0,0 @@ -// include/strata/artifact/gguf_reader.hpp - generated from src/artifact/gguf_reader.cpp by -// scripts/split_artifact.py. Header-only on purpose: the reader is one translation unit's worth of -// code with no state to hide, and a header-only split cannot introduce a duplicate-symbol or -// missing-declaration bug in code that is already validated. -#pragma once -// src/artifact/gguf_reader.cpp - P1.S2: GGUF v3 reader, mmap, no ggml dependency. -// -// The C++ counterpart of tools/gguf_reader.py, which has been the reference since P0.S6 (written -// because gguf-py cannot represent type 42 / Q2_0). Per P1.S2 it must: -// * mmap the file and parse header, metadata KV (ALL value types incl. arrays), tensor directory -// * be multi-shard aware (split.* keys) -// * carry an architecture guard: general.architecture == "qwen4exp" and the compiled-in constants -// must match, refusing with a precise error otherwise -// * have no ggml dependency -// -// This file is the reader plus a `--check` mode that validates it the way the Python one is -// validated: parse the tiny model AND both real shards, and report counts that other harnesses have -// already established independently (1,223 / 1 tensors; 202 Q2_0 in shard 1). Agreement with those -// numbers is the test. -// -// Build: scripts/build_artifact.bat Run: gguf_reader.exe [--check] - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "strata/artifact/gguf_split.hpp" - -#ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN -#ifndef NOMINMAX -#define NOMINMAX // windows.h's min/max macros would break std::min/std::max in every file that includes this one -#endif -#include -#else -#include -#include -#include -#include -#endif - -namespace strata { - -// ---- ggml type ids we care about. 42 = Q2_0, the PrismML ternary 2-bit encoding this engine targets. -inline const char* ggml_type_name(uint32_t t) { - switch (t) { - case 0: - return "F32"; - case 1: - return "F16"; - case 2: - return "Q4_0"; - case 3: - return "Q4_1"; - case 6: - return "Q5_0"; - case 7: - return "Q5_1"; - case 8: - return "Q8_0"; - case 9: - return "Q8_1"; - case 10: - return "Q2_K"; - case 11: - return "Q3_K"; - case 12: - return "Q4_K"; - case 13: - return "Q5_K"; - case 14: - return "Q6_K"; - case 15: - return "Q8_K"; - case 16: - return "IQ2_XXS"; - case 17: - return "IQ2_XS"; - case 18: - return "IQ3_XXS"; - case 19: - return "IQ1_S"; - case 20: - return "IQ4_NL"; - case 21: - return "IQ3_S"; - case 22: - return "IQ2_S"; - case 23: - return "IQ4_XS"; - case 24: - return "I8"; - case 30: - return "BF16"; - case 34: - return "TQ1_0"; - case 35: - return "TQ2_0"; - case 39: - return "MXFP4"; - case 40: - return "NVFP4"; - case 41: - return "Q1_0"; - case 42: - return "Q2_0"; - default: - return "?"; - } -} - -// Block geometry: (elements per block, bytes per block). Q2_0 is 64/18 - proven from this artifact's -// own offset brackets in P0.S6 and recorded in docs/q2_0-contract.md. -inline bool block_geometry(uint32_t t, int& elems, int& bytes) { - switch (t) { - case 0: - elems = 1; - bytes = 4; - return true; - case 1: - case 30: - elems = 1; - bytes = 2; - return true; - case 2: - elems = 32; - bytes = 18; - return true; - case 3: - elems = 32; - bytes = 20; - return true; - case 6: - elems = 32; - bytes = 22; - return true; - case 7: - elems = 32; - bytes = 24; - return true; - case 8: - elems = 32; - bytes = 34; - return true; - case 9: - elems = 32; - bytes = 36; - return true; - case 10: - elems = 256; - bytes = 84; - return true; - case 11: - elems = 256; - bytes = 110; - return true; - case 12: - elems = 256; - bytes = 144; - return true; - case 13: - elems = 256; - bytes = 176; - return true; - case 14: - elems = 256; - bytes = 210; - return true; - case 16: - elems = 256; - bytes = 66; - return true; - case 17: - elems = 256; - bytes = 74; - return true; - case 18: - elems = 256; - bytes = 98; - return true; - case 20: - elems = 32; - bytes = 18; - return true; - case 21: // IQ3_S - elems = 256; - bytes = 110; - return true; - case 22: // IQ2_S - elems = 256; - bytes = 82; - return true; - case 23: - elems = 256; - bytes = 136; - return true; - case 29: // IQ1_M - elems = 256; - bytes = 56; - return true; - case 24: // I8: raw bytes (the FP8 PLE table of tools/ple_fp8_pack.py) - elems = 1; - bytes = 1; - return true; - case 42: - elems = 64; - bytes = 18; - return true; - default: - return false; - } -} - -struct TensorInfo { - std::string name; - std::vector shape; // GGUF order: dim 0 varies fastest - uint32_t type = 0; - uint64_t offset = 0; - uint64_t elements() const { - uint64_t n = 1; - for (auto d : shape) n *= d; - return n; - } - const char* type_name() const { return ggml_type_name(type); } -}; - -// A bounds-checked cursor over the mmapped header region. Every read is checked, so a truncated or -// corrupt file produces a precise error rather than a segfault. -class Cursor { -public: - Cursor(const uint8_t* base, size_t size) : base_(base), size_(size) {} - void need(size_t n) const { - if (pos_ + n > size_) throw std::runtime_error("GGUF: unexpected end of file in header"); - } - template T read() { - need(sizeof(T)); - T v; - std::memcpy(&v, base_ + pos_, sizeof(T)); - pos_ += sizeof(T); - return v; - } - std::string str() { - const uint64_t n = read(); - need((size_t)n); - std::string s(reinterpret_cast(base_ + pos_), (size_t)n); - pos_ += (size_t)n; - return s; - } - size_t pos() const { return pos_; } - -private: - const uint8_t* base_; - size_t size_; - size_t pos_ = 0; -}; - -enum class MetaType : uint32_t { U8 = 0, I8, U16, I16, U32, I32, F32, BOOL, STRING, ARRAY, U64, I64, F64 }; - -struct MetaValue { - MetaType type = MetaType::U32; - uint64_t u = 0; // integer payloads - double f = 0; // float payloads - std::string s; // string payloads - MetaType elem = MetaType::U32; // arrays - uint64_t count = 0; - std::vector items; - bool is_num() const { return type != MetaType::STRING && type != MetaType::ARRAY; } - double num() const { return (type == MetaType::F32 || type == MetaType::F64) ? f : (double)u; } -}; - -inline MetaValue read_value(Cursor& c, MetaType t, int depth = 0) { - if (depth > 2) throw std::runtime_error("GGUF: array nesting too deep"); - MetaValue v; - v.type = t; - switch (t) { - case MetaType::U8: - v.u = c.read(); - break; - case MetaType::I8: - v.u = (uint64_t)(int64_t)c.read(); - break; - case MetaType::U16: - v.u = c.read(); - break; - case MetaType::I16: - v.u = (uint64_t)(int64_t)c.read(); - break; - case MetaType::U32: - v.u = c.read(); - break; - case MetaType::I32: - v.u = (uint64_t)(int64_t)c.read(); - break; - case MetaType::F32: { - float x = c.read(); - v.f = x; - v.u = 0; - break; - } - case MetaType::BOOL: - v.u = c.read() ? 1 : 0; - break; - case MetaType::STRING: - v.s = c.str(); - break; - case MetaType::U64: - v.u = c.read(); - break; - case MetaType::I64: - v.u = (uint64_t)c.read(); - break; - case MetaType::F64: - v.f = c.read(); - break; - case MetaType::ARRAY: { - v.elem = (MetaType)c.read(); - v.count = c.read(); - if (v.count > (1u << 24)) throw std::runtime_error("GGUF: implausible array length"); - v.items.reserve((size_t)std::min(v.count, 64)); - for (uint64_t i = 0; i < v.count; ++i) { - MetaValue e = read_value(c, v.elem, depth + 1); - if (i < 64) v.items.push_back(std::move(e)); // keep a sample; the count is what matters - } - break; - } - default: - throw std::runtime_error("GGUF: unknown metadata value type"); - } - return v; -} - -class GgufFile { -public: - explicit GgufFile(const std::string& path) : path_(path) { - try { open(); } - catch (...) { close(); throw; } - } - ~GgufFile() { close(); } - GgufFile(const GgufFile&) = delete; - GgufFile& operator=(const GgufFile&) = delete; - - const std::vector& tensors() const { return tensors_; } - const std::map& metadata() const { return meta_; } - uint32_t version() const { return version_; } - uint64_t data_start() const { return data_start_; } - uint64_t file_size() const { return size_; } - uint64_t alignment() const { return alignment_; } - const std::string& path() const { return path_; } - - const TensorInfo* find(const std::string& name) const { - for (const auto& t : tensors_) - if (t.name == name) return &t; - return nullptr; - } - uint64_t count_type(const char* tn) const { - uint64_t n = 0; - for (const auto& t : tensors_) - if (std::strcmp(t.type_name(), tn) == 0) ++n; - return n; - } - const MetaValue* get(const std::string& key) const { - auto it = meta_.find(key); - return it == meta_.end() ? nullptr : &it->second; - } - const uint8_t* tensor_data(const TensorInfo& t) const { return base_ + data_start_ + t.offset; } - -private: - void open() { -#ifdef _WIN32 - HANDLE h = CreateFileA(path_.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, nullptr); - if (h == INVALID_HANDLE_VALUE) throw std::runtime_error("cannot open " + path_); - LARGE_INTEGER li{}; - GetFileSizeEx(h, &li); - size_ = (uint64_t)li.QuadPart; - HANDLE m = CreateFileMappingA(h, nullptr, PAGE_READONLY, 0, 0, nullptr); - if (!m) { - CloseHandle(h); - throw std::runtime_error("CreateFileMapping failed"); - } - base_ = (const uint8_t*)MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0); - if (!base_) { - CloseHandle(m); - CloseHandle(h); - throw std::runtime_error("MapViewOfFile failed"); - } - map_ = m; - file_ = h; -#else - int fd = ::open(path_.c_str(), O_RDONLY); - if (fd < 0) throw std::runtime_error("cannot open " + path_); - fd_ = fd; - struct stat st{}; - if (fstat(fd, &st) != 0) throw std::runtime_error("fstat failed"); - size_ = (uint64_t)st.st_size; - void* p = mmap(nullptr, size_, PROT_READ, MAP_PRIVATE, fd, 0); - if (p == MAP_FAILED) throw std::runtime_error("mmap failed"); - base_ = (const uint8_t*)p; -#endif - parse(); - } - void close() { -#ifdef _WIN32 - if (base_) UnmapViewOfFile(base_); - if (map_) CloseHandle((HANDLE)map_); - if (file_) CloseHandle((HANDLE)file_); -#else - if (base_) munmap((void*)base_, size_); - if (fd_ >= 0) ::close(fd_); -#endif - } - - void parse() { - Cursor c(base_, size_); - const uint32_t magic = c.read(); - if (magic != 0x46554747u) throw std::runtime_error("not a GGUF file (bad magic)"); - version_ = c.read(); - if (version_ != 3) - throw std::runtime_error("GGUF v" + std::to_string(version_) + ", this reader handles v3"); - const uint64_t n_tensors = c.read(); - const uint64_t n_kv = c.read(); - - for (uint64_t i = 0; i < n_kv; ++i) { - std::string key = c.str(); - MetaType t = (MetaType)c.read(); - meta_.emplace(std::move(key), read_value(c, t)); - } - tensors_.reserve((size_t)n_tensors); - // GGUF has no index to arbitrate between two tensors of one name: find() is first-match, so a - // duplicate would silently win by position. Refuse the file at open instead, naming both. - std::set names; - for (uint64_t i = 0; i < n_tensors; ++i) { - TensorInfo t; - t.name = c.str(); - if (!names.insert(t.name).second) - throw std::runtime_error("GGUF: duplicate tensor name '" + t.name + "' in " + path_); - const uint32_t nd = c.read(); - if (nd == 0 || nd > 4) throw std::runtime_error("GGUF: bad n_dims for " + t.name); - t.shape.resize(nd); - for (uint32_t d = 0; d < nd; ++d) t.shape[d] = c.read(); - t.type = c.read(); - t.offset = c.read(); - tensors_.push_back(std::move(t)); - } - uint64_t align = 32; - if (const MetaValue* a = get("general.alignment")) - if (a->u) align = a->u; - alignment_ = align; - data_start_ = (c.pos() + align - 1) / align * align; - if (data_start_ > size_) throw std::runtime_error("GGUF: data section starts past EOF"); - } - - std::string path_; - const uint8_t* base_ = nullptr; - uint64_t size_ = 0, data_start_ = 0, alignment_ = 32; - uint32_t version_ = 0; -#ifdef _WIN32 - void* file_ = nullptr; - void* map_ = nullptr; -#else - int fd_ = -1; -#endif - std::vector tensors_; - std::map meta_; -}; - -// Bytes of a tensor's payload from its shape and block geometry; 0 when the type is unknown, a row is not whole -// blocks, or the count overflows. -inline uint64_t tensor_payload_bytes(const TensorInfo& t) { - int be = 0, bb = 0; - if (t.shape.empty() || !block_geometry(t.type, be, bb) || t.shape[0] % (uint64_t) be) return 0; - uint64_t elements = 1; - for (uint64_t d : t.shape) { - if (d == 0 || elements > (std::numeric_limits::max)() / d) return 0; - elements *= d; - } - const uint64_t blocks = elements / (uint64_t) be; - if (blocks > (std::numeric_limits::max)() / (uint64_t) bb) return 0; - return blocks * (uint64_t) bb; -} - -// The shards of one model (strata::gguf_split_paths), opened together; tensors are looked up across all of them. -// From eddoursul/Strata 8029fa9, with the split-key validation of #255 (gopinath87607) made a property of the -// model rather than of one loader: a split GGUF carries the model's metadata (general.architecture and the -// qwen4exp keys) in its FIRST shard only, and the later shards just declare split.count / split.no / -// split.tensors.count. Unsloth's UD-Q4_K_XL is the extreme case: shard 1 holds the metadata and no tensor at -// all, and output.weight, token_embd.weight and the PLE table live in shard 2. So the architecture is checked -// on `meta()` and a tensor is read from the shard that holds it. -// -// Refused at construction: a later shard whose split keys disagree with shard 1's (another model's shard, or a -// shard renamed into the family), a split model whose tensor directories do not add up to split.tensors.count, -// and a tensor name present in two shards (GGUF has no index to say which one is meant). -class GgufModel { -public: - explicit GgufModel(const std::vector& paths) { - if (paths.empty()) throw std::runtime_error("GGUF: a model needs at least one shard"); - for (const auto& p : paths) shards_.push_back(std::make_unique(p)); - validate_split(); - for (size_t i = 0; i < shards_.size(); ++i) - for (const auto& t : shards_[i]->tensors()) { - const auto ins = index_.emplace(t.name, std::make_pair(i, &t)); - if (!ins.second) - throw std::runtime_error("GGUF: tensor " + t.name + " is in two shards (" + - shards_[ins.first->second.first]->path() + " and " + - shards_[i]->path() + ")"); - } - } - /// Opens every shard of the model that `any_shard` belongs to (throws when one is missing). - static GgufModel open(const std::string& any_shard) { return GgufModel(gguf_split_paths(any_shard)); } - - size_t size() const { return shards_.size(); } - const GgufFile& shard(size_t i) const { return *shards_[i]; } - /// The metadata shard: general.architecture and the model's keys. - const GgufFile& meta() const { return *shards_[0]; } - /// The tensor named `name` (its shard index in `*shard`), or nullptr. - const TensorInfo* find(const std::string& name, size_t* shard = nullptr) const { - const auto it = index_.find(name); - if (it == index_.end()) return nullptr; - if (shard) *shard = it->second.first; - return it->second.second; - } - /// Whether `t` (a tensor of shard `s`) has a known byte count that lies inside its file. - bool in_bounds(const TensorInfo& t, size_t s) const { - const GgufFile& g = *shards_[s]; - const uint64_t bytes = tensor_payload_bytes(t); - const uint64_t payload = g.file_size() - g.data_start(); - return bytes != 0 && t.offset <= payload && bytes <= payload - t.offset; - } - -private: - void validate_split() const { - const size_t n = shards_.size(); - const MetaValue* count0 = shards_[0]->get("split.count"); - if (n == 1) { - if (count0 && count0->u > 1) - throw std::runtime_error("GGUF: " + shards_[0]->path() + " is shard 1 of " + std::to_string(count0->u) + - ", but it was opened as a whole model"); - return; - } - if (!shards_[0]->get("general.architecture")) - throw std::runtime_error("GGUF: " + shards_[0]->path() + " has no general.architecture; the first shard " - "of a split model carries the metadata"); - const MetaValue* total = shards_[0]->get("split.tensors.count"); - uint64_t tensors = 0; - for (size_t i = 0; i < n; ++i) { - const GgufFile& g = *shards_[i]; - const MetaValue* count = g.get("split.count"); - const MetaValue* no = g.get("split.no"); - const MetaValue* tc = g.get("split.tensors.count"); - if (!count || !no || count->u != n || no->u != i || (total && (!tc || tc->u != total->u))) - throw std::runtime_error("GGUF: " + g.path() + " does not declare itself shard " + std::to_string(i + 1) + - " of " + std::to_string(n) + " of this model (split.count / split.no / " - "split.tensors.count)"); - tensors += g.tensors().size(); - } - if (total && tensors != total->u) - throw std::runtime_error("GGUF: the " + std::to_string(n) + " shards hold " + std::to_string(tensors) + - " tensors, but split.tensors.count is " + std::to_string(total->u)); - } - - std::vector> shards_; - std::map> index_; -}; - -// ---- architecture guard (P1.S2). The engine is specialised to ONE family; anything else must be refused -// with a precise error rather than silently mis-run. Two architecture strings pass: `qwen4exp` (Qwen3.8-Flash-Next, -// the model the kernels were written for: its six keys are checked against the compiled-in values) and `qwen35moe` -// (Qwen3.6-35B-A3B, Phase 2 of docs/PLAN-qwen36-35b-a3b.md: the file is the authority on every size, so its keys -// are checked for PRESENCE only, and `strata::core::read_model_geometry` reads them). Passing this guard says the -// metadata is readable, not that the engine runs the model: the Qwen3.6 start stops at its own gate afterwards. -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 - // fewer experts than the canonical 512; the graph reads the true value -}; - -inline std::string check_architecture(const GgufFile& g, const Qwen4ExpGuard& want = {}) { - const MetaValue* arch = g.get("general.architecture"); - if (!arch) return "missing general.architecture"; - struct Req { - const char* key; - uint64_t want; - }; - if (arch->s == "qwen4exp") { - const Req reqs[] = { - {"qwen4exp.block_count", want.block_count}, - {"qwen4exp.embedding_length", want.hidden}, - {"qwen4exp.expert_count", want.experts}, - {"qwen4exp.expert_used_count", want.experts_used}, - {"qwen4exp.attention.head_count", want.head_count}, - {"qwen4exp.attention.head_count_kv", want.head_count_kv}, - }; - for (const auto& r : reqs) { - const MetaValue* v = g.get(r.key); - if (!v) return std::string("missing ") + r.key; - if (r.want && v->u != r.want) - return std::string(r.key) + " = " + std::to_string(v->u) + ", expected " + std::to_string(r.want); - } - return {}; // empty == ok - } - 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 diff --git a/include/strata/artifact/gguf_split.hpp b/include/strata/artifact/gguf_split.hpp deleted file mode 100644 index 0f01001..0000000 --- a/include/strata/artifact/gguf_split.hpp +++ /dev/null @@ -1,52 +0,0 @@ -// include/strata/artifact/gguf_split.hpp - the shards of a split model. Separate from gguf_reader.hpp, which -// includes , so any translation unit can resolve a model's shards. -// -// From eddoursul/Strata 8029fa9 (gguf_split_paths), with one change of contract: upstream's model_shards() -// skipped a shard it could not open and returned the rest, so a download that was still running (or a shard -// deleted by hand) produced a model with some layers missing and an error much later, or none. A missing shard -// is now an error that names it. -#pragma once - -#include -#include -#include -#include -#include - -namespace strata { - -// Split models: `-00001-of-0000N.gguf` ... `-0000N-of-0000N.gguf`, as llama.cpp's gguf-split names -// them. Given ANY shard's path, the shards in split order (the metadata shard, 00001, first); a file without that -// suffix is a model of one shard. Only the five digits of the shard number are rewritten, so the directory and -// the stem are the caller's own spelling (a symlinked Hugging Face snapshot keeps its split names). Throws when -// a shard is missing. -inline std::vector gguf_split_paths(const std::string& any) { - static const char tag[] = "-of-"; - const size_t at = any.rfind(tag); - // "...-NNNNN-of-MMMMM.gguf": five digits before the tag, five after it, then the extension - if (at == std::string::npos || at < 6 || any[at - 6] != '-' || any.size() != at + 4 + 5 + 5 || - any.compare(at + 9, 5, ".gguf") != 0) - return {any}; - int no = 0, n = 0; - for (size_t i = 0; i < 5; ++i) { - const char a = any[at - 5 + i], b = any[at + 4 + i]; - if (a < '0' || a > '9' || b < '0' || b > '9') return {any}; - no = no * 10 + (a - '0'); - n = n * 10 + (b - '0'); - } - if (n < 1 || no < 1 || no > n) return {any}; - std::vector out; - for (int i = 1; i <= n; ++i) { - char num[8]; - std::snprintf(num, sizeof num, "%05d", i); - std::string p = any; - p.replace(at - 5, 5, num); - if (!std::ifstream(p, std::ios::binary)) - throw std::runtime_error("missing model shard " + p + " (shard " + std::to_string(i) + " of " + - std::to_string(n) + "; is the download complete?)"); - out.push_back(std::move(p)); - } - return out; -} - -} // namespace strata diff --git a/include/strata/core/conversation_buffer.hpp b/include/strata/core/conversation_buffer.hpp deleted file mode 100644 index 1cb8af7..0000000 --- a/include/strata/core/conversation_buffer.hpp +++ /dev/null @@ -1,154 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -namespace strata::core { - -// Snapshot-owned host storage. Appending never relocates existing payloads; -// only the small segment directory can move. No sharing or copy-on-write is -// needed because a parked image and its retained active buffers have one owner. -class ConversationBuffer { -public: - static constexpr size_t segment_bytes = 16 * 1024 * 1024; - ConversationBuffer() = default; - ConversationBuffer(std::initializer_list values) { - resize(values.size()); - visit(0, size(), [&](uint8_t* p, size_t n, size_t at) { - std::memcpy(p, values.begin() + at, n); - return true; - }); - } - ConversationBuffer(const ConversationBuffer&) = default; - ConversationBuffer& operator=(const ConversationBuffer&) = default; - ConversationBuffer(ConversationBuffer&& other) noexcept - : segments_(std::move(other.segments_)), size_(std::exchange(other.size_, 0)) {} - ConversationBuffer& operator=(ConversationBuffer&& other) noexcept { - if (this == &other) return *this; - segments_ = std::move(other.segments_); - size_ = std::exchange(other.size_, 0); - return *this; - } - - size_t size() const { return size_; } - bool empty() const { return size_ == 0; } - size_t bytes() const { - size_t n = segments_.capacity() * sizeof(Segment); - for (const auto& segment : segments_) n += segment.capacity(); - return n; - } - // Includes the old directory while reserve allocates its replacement. - // Saturation makes an overflowing estimate fail admission before resize. - size_t allocation_peak(size_t n) const { - size_t total = bytes(); - if (n <= size_) return total; - const size_t spare = segments_.empty() ? 0 : segments_.back().capacity() - segments_.back().size(); - const size_t extra = n - size_ - std::min(n - size_, spare); - const size_t full = extra / segment_bytes, tail = extra % segment_bytes; - if (!add(total, full * segment_bytes)) return SIZE_MAX; - if (tail && !add(total, segment_capacity(tail, full ? segment_bytes : - segments_.empty() ? 0 : segments_.back().capacity(), size_ != 0))) return SIZE_MAX; - size_t count = segments_.size(); - if (!add(count, full + (tail != 0))) return SIZE_MAX; - if (count > segments_.capacity() && - (count > SIZE_MAX / sizeof(Segment) || !add(total, count * sizeof(Segment)))) return SIZE_MAX; - return total; - } - void resize(size_t n, uint8_t value = 0) { - if (n > size_) { - const bool growing = size_ != 0; - const size_t spare = segments_.empty() ? 0 : segments_.back().capacity() - segments_.back().size(); - const size_t extend = std::min(n - size_, spare); - const size_t extra = n - size_ - extend; - segments_.reserve(segments_.size() + extra / segment_bytes + (extra % segment_bytes != 0)); - if (extend) { - segments_.back().resize(segments_.back().size() + extend, value); - size_ += extend; - } - while (size_ < n) { - const size_t count = std::min(segment_bytes, n - size_); - const size_t previous = segments_.empty() ? 0 : segments_.back().capacity(); - Segment segment; - segment.reserve(segment_capacity(count, previous, growing)); - segment.resize(count, value); - segments_.push_back(std::move(segment)); - size_ += count; - } - } else { - while (!segments_.empty() && size_ - segments_.back().size() >= n) { - size_ -= segments_.back().size(); - segments_.pop_back(); - } - if (size_ > n) segments_.back().resize(segments_.back().size() - (size_ - n)); - size_ = n; - } - } - void pop_back() { resize(size_ - 1); } - - // fn(pointer, count, absolute_offset); false aborts a transfer immediately. - template bool visit(size_t offset, size_t count, Fn fn) { - return visit_impl(*this, offset, count, fn); - } - template bool visit(size_t offset, size_t count, Fn fn) const { - return visit_impl(*this, offset, count, fn); - } - bool read(void* target, size_t offset, size_t count) const { - return visit(offset, count, [&](const uint8_t* p, size_t n, size_t at) { - std::memcpy(static_cast(target) + at - offset, p, n); - return true; - }); - } - bool operator==(const ConversationBuffer& other) const { - if (size_ != other.size_) return false; - size_t a = 0, b = 0, x = 0, y = 0; - while (a < segments_.size() && b < other.segments_.size()) { - const auto& left = segments_[a]; - const auto& right = other.segments_[b]; - const size_t n = std::min(left.size() - x, right.size() - y); - if (std::memcmp(left.data() + x, right.data() + y, n)) return false; - x += n; y += n; - if (x == left.size()) { ++a; x = 0; } - if (y == right.size()) { ++b; y = 0; } - } - return true; - } - -private: - using Segment = std::vector; - // A fresh capture allocates exactly its payload. Later appends reserve - // geometrically growing segments, bounded by 16 MiB. Small chat turns then - // extend the final allocation instead of adding one transfer per turn. - static size_t segment_capacity(size_t count, size_t previous, bool growing) { - if (!growing) return count; - return std::max(count, std::min(segment_bytes, std::max(65536, std::min(previous, segment_bytes/2)*2))); - } - static bool add(size_t& n, size_t extra) { - if (extra > SIZE_MAX - n) return false; - n += extra; - return true; - } - template static bool visit_impl(Self& self, size_t offset, size_t count, Fn fn) { - if (offset > self.size_ || count > self.size_ - offset) return false; - size_t begin = 0; - for (auto& segment : self.segments_) { - if (!count) break; - const size_t end = begin + segment.size(); - if (offset < end) { - const size_t n = std::min(count, end - offset); - if (!fn(segment.data() + offset - begin, n, offset)) return false; - offset += n; count -= n; - } - begin = end; - } - return count == 0; - } - std::vector segments_; - size_t size_ = 0; -}; - -} // namespace strata::core diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp deleted file mode 100644 index b105deb..0000000 --- a/include/strata/core/conversation_cache.hpp +++ /dev/null @@ -1,283 +0,0 @@ -// CPU-only ownership and matching policy for --serve's parked conversations. -// Token equality, image identity, and steering mode are all required for reuse. -#pragma once - -#include "strata/core/conversation_buffer.hpp" - -#include -#include -#include -#include -#include -#include -#include - -namespace strata::core { - -struct ConversationImageKey { - int64_t start = 0; - uint64_t hash = 0; - bool operator==(const ConversationImageKey&) const = default; -}; - -struct ConversationCheckpoint { - std::vector ids; - std::vector imgs; - std::vector gdn, ple, tails, dead, block_pos; - uint64_t used = 0; // upstream root-pinned/LRU checkpoint retention - // Ordinary layer-split checkpoints retain each device's running state. - // Whole-session parking is currently single-GPU and rejects these parts. - std::vector stage_parts; - - size_t bytes() const { - size_t n = ids.capacity() * sizeof(int32_t) + imgs.capacity() * sizeof(ConversationImageKey) + - gdn.capacity() + ple.capacity() + tails.capacity() + dead.capacity() + block_pos.capacity() + - stage_parts.capacity() * sizeof(ConversationCheckpoint); - for (const auto& part : stage_parts) n += part.bytes(); - return n; - } -}; - -// Identity-layout K/V pages and completed indexer rows. For streamed layers the -// source is the authoritative host pool, NOT the replaceable VRAM slots. -struct ConversationKv { - int format = 0; - int64_t cells = 0, heads = 0, head_dim = 0, page_size = 0, pooled_rows = 0, idx_dim = 0; - ConversationBuffer k, v, k_scale, v_scale, pooled; - size_t bytes() const { - return k.bytes() + v.bytes() + k_scale.bytes() + v_scale.bytes() + pooled.bytes(); - } -}; - -struct ConversationKvReuse { - std::vector kv; - // Original image extent for validation, and the earliest subsequent rewrite. - int64_t captured_tokens = 0, unchanged_tokens = 0; - // With a layer split: the later stages' own retained K/V, one per stage, same extents (empty: none) - std::vector stages; - size_t bytes() const { - size_t n = kv.capacity() * sizeof(ConversationKv) + stages.capacity() * sizeof(ConversationKvReuse); - for (const auto& layer : kv) n += layer.bytes(); - for (const auto& s : stages) n += s.bytes(); - return n; - } -}; - -/// Layer-split parking: each running checkpoint holds the first stage's state and, in `stage_parts`, one part per -/// later stage; a parked conversation keeps them in one image per stage. `split` MOVES the checkpoints apart (no -/// running state is copied): the complete ones (a part for each of `stages` stages) into `stage0` and `parts[k]`, -/// every part carrying the checkpoint's ids / images / LRU stamp, the others aside; `merge` puts them back in their -/// original order. merge(split(x)) == x. -struct ConversationCheckpointSplit { - std::vector stage0; - std::vector> parts; ///< [stage][checkpoint] - std::vector rest; ///< not split (no complete set of stage parts) - std::vector complete; ///< per original position: in stage0/parts or in rest -}; - -inline ConversationCheckpointSplit conversation_checkpoints_split(std::vector&& checks, - size_t stages) { - ConversationCheckpointSplit out; - out.parts.resize(stages); - for (auto& c : checks) { - const bool whole = c.stage_parts.size() == stages; - out.complete.push_back(whole); - if (!whole) { out.rest.push_back(std::move(c)); continue; } - for (size_t k = 0; k < stages; ++k) { - ConversationCheckpoint part = std::move(c.stage_parts[k]); - part.ids = c.ids; part.imgs = c.imgs; part.used = c.used; part.stage_parts.clear(); - out.parts[k].push_back(std::move(part)); - } - c.stage_parts.clear(); - out.stage0.push_back(std::move(c)); - } - checks.clear(); - return out; -} - -/// false (and `out` empty) when the parts do not line up: a stage with another number of checkpoints, or a part -/// whose ids differ from its checkpoint's. -inline bool conversation_checkpoints_merge(ConversationCheckpointSplit&& split, std::vector& out) { - out.clear(); - for (const auto& p : split.parts) - if (p.size() != split.stage0.size()) return false; - size_t whole = 0, other = 0; - for (bool c : split.complete) (c ? whole : other) += 1; - if (!split.complete.empty() && (whole != split.stage0.size() || other != split.rest.size())) return false; - if (split.complete.empty()) split.complete.assign(split.stage0.size(), true); // a restored image: all whole - for (size_t j = 0; j < split.stage0.size(); ++j) - for (const auto& p : split.parts) - if (p[j].ids != split.stage0[j].ids) return false; - size_t w = 0, r = 0; - for (bool c : split.complete) { - if (!c) { out.push_back(std::move(split.rest[r++])); continue; } - ConversationCheckpoint cp = std::move(split.stage0[w]); - for (auto& p : split.parts) cp.stage_parts.push_back(std::move(p[w])); - ++w; - out.push_back(std::move(cp)); - } - return true; -} - -struct SavedConversation { - // Runtime compatibility only; NOT a model/weights identity or disk schema. - std::array geometry{}; - // The session's layer carve the image was captured from ([0, n_layers) on one GPU); restore requires the same. - int64_t layer_lo = 0, layer_hi = 0; - ConversationCheckpoint live; - std::vector checkpoints; - std::vector kv; // main layers followed by the draft layer - bool cvec = true; - // with a layer split, the later stages' own images, one per stage, in stage order - std::vector stage_images; - - size_t bytes() const { - size_t n = live.bytes() + checkpoints.capacity() * sizeof(ConversationCheckpoint) + - kv.capacity() * sizeof(ConversationKv); - for (const auto& s : stage_images) n += s.bytes(); - for (const auto& c : checkpoints) n += c.bytes(); - for (const auto& k : kv) n += k.bytes(); - return n; - } -}; - -template -int64_t conversation_prefix(const ConversationCheckpoint& c, const std::vector& prompt, - const std::vector& images) { - const size_t n = c.ids.size(); - // The last prompt token always starts the next verify window. - if (n == 0 || n >= prompt.size() || !std::equal(c.ids.begin(), c.ids.end(), prompt.begin())) return 0; - size_t j = 0; - for (const auto& image : images) { - if (image.start >= (int64_t) n) continue; - if (j == c.imgs.size() || !(c.imgs[j++] == image)) return 0; - } - if (j != c.imgs.size()) return 0; - return (int64_t) n; -} - -class ConversationCache { -public: - struct Match { - size_t index = 0; - int64_t tokens = 0; - bool live = false; - }; - - ConversationCache(size_t budget, size_t slots) : budget_(budget), slots_(slots) {} - bool enabled() const { return budget_ != 0 && slots_ != 0; } - size_t bytes() const { return bytes_ + reuse_.bytes(); } - size_t size() const { return entries_.size(); } - size_t evictions() const { return evictions_; } - - // Retain only the restored K/V buffers, not duplicate running checkpoints. - // This optimization never evicts a parked conversation to make itself fit. - // `stage_kv`: with a layer split, the later stages' restored K/V (one per stage), retained with the first's. - void retain(std::vector&& kv, int64_t tokens, - std::vector>&& stage_kv = {}) { - reuse_ = {}; - ConversationKvReuse candidate{std::move(kv), tokens, tokens, {}}; - for (auto& k : stage_kv) candidate.stages.push_back(ConversationKvReuse{std::move(k), tokens, tokens, {}}); - if (enabled() && candidate.bytes() <= budget_ - bytes_) reuse_ = std::move(candidate); - } - void limit_reuse(int64_t first_dirty) { - reuse_.unchanged_tokens = std::min(reuse_.unchanged_tokens, first_dirty); - for (auto& s : reuse_.stages) s.unchanged_tokens = std::min(s.unchanged_tokens, first_dirty); - if (reuse_.unchanged_tokens <= 0) reuse_ = {}; - } - ConversationKvReuse take_reuse() { return std::exchange(reuse_, {}); } - size_t retained_bytes() const { return reuse_.bytes(); } - bool can_fit(size_t incoming, size_t held = 0) const { - return enabled() && held <= budget_ && incoming <= budget_ - held && - entries_.size() < slots_ && bytes() <= budget_ - held - incoming; - } - - template - Match best(const std::vector& prompt, const std::vector& images, bool cvec) const { - Match best; - // Ties prefer the most recently parked branch. The caller prefers its - // already-active state when that offers the same prefix length. - for (size_t i = entries_.size(); i-- > 0;) { - const auto& e = entries_[i]; - if (e.cvec != cvec) continue; - auto consider = [&](const ConversationCheckpoint& c, bool live) { - const int64_t n = conversation_prefix(c, prompt, images); - if (n > best.tokens) best = {i, n, live}; - }; - consider(e.live, true); - for (const auto& c : e.checkpoints) consider(c, false); - } - return best; - } - - SavedConversation take(size_t index) { - SavedConversation out = std::move(entries_.at(index)); - bytes_ -= out.bytes(); - entries_.erase(entries_.begin() + (std::ptrdiff_t) index); - return out; - } - - // Reserve before allocating a snapshot. held is an incoming image removed - // with take() but still alive during the exchange; count it against RAM too. - bool make_room(size_t incoming, size_t held = 0) { - if (!enabled() || held > budget_ || incoming > budget_ - held) return false; - if (bytes() > budget_ - held - incoming) reuse_ = {}; - while (!entries_.empty() && (entries_.size() >= slots_ || bytes_ > budget_ - held - incoming)) { - bytes_ -= entries_.front().bytes(); - entries_.pop_front(); - ++evictions_; - } - return true; - } - - // #342: drop the parked entries an outgoing conversation (its live tokens and checkpoint chain) supersedes: - // the same conversation a turn back, whose DEEPEST checkpoint the outgoing chain still holds, so all it adds - // is the tail the client rewrote (the reply as it was generated, before the next request re-rendered it) and - // checkpoints older than that one. A subagent's successive turns parked one such copy each, and make_room's - // oldest-first eviction then pushed the parent conversation out after `slots` turns. An entry without - // checkpoints, or whose deepest checkpoint the outgoing chain does not hold (another conversation that only - // shares the system prompt's root with it), is kept. Returns how many were dropped. - size_t drop_superseded(const std::vector& ids, const std::vector& images, - const std::vector& checkpoints, bool cvec) { - auto held = [&](const ConversationCheckpoint& c) { - if (c.ids == ids && c.imgs == images) return true; - for (const auto& k : checkpoints) - if (k.ids == c.ids && k.imgs == c.imgs) return true; - return false; - }; - size_t dropped = 0; - for (size_t i = 0; i < entries_.size();) { - const auto& e = entries_[i]; - const ConversationCheckpoint* deepest = nullptr; - for (const auto& c : e.checkpoints) - if (!deepest || c.ids.size() > deepest->ids.size()) deepest = &c; - if (e.cvec == cvec && deepest && !deepest->ids.empty() && held(*deepest)) { - bytes_ -= e.bytes(); - entries_.erase(entries_.begin() + (std::ptrdiff_t) i); - ++dropped; - continue; - } - ++i; - } - superseded_ += dropped; - return dropped; - } - size_t superseded() const { return superseded_; } - - bool put(SavedConversation&& image, size_t held = 0) { - const size_t n = image.bytes(); - if (!enabled() || held > budget_ || n > budget_ - held) return false; // make_room's refusal, first - drop_superseded(image.live.ids, image.live.imgs, image.checkpoints, image.cvec); - if (!make_room(n, held)) return false; - entries_.push_back(std::move(image)); - bytes_ += n; - return true; - } - -private: - size_t budget_ = 0, slots_ = 0, bytes_ = 0, evictions_ = 0, superseded_ = 0; - std::deque entries_; // least recently active first - ConversationKvReuse reuse_; -}; - -} // namespace strata::core diff --git a/include/strata/core/conversation_memory.hpp b/include/strata/core/conversation_memory.hpp deleted file mode 100644 index 0e908b4..0000000 --- a/include/strata/core/conversation_memory.hpp +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace strata::core { - -// Host physical memory, not swap/commit or a container/job memory reservation. -// Unknown telemetry is deliberately distinct from a measured zero. -std::optional conversation_available_memory(); -std::optional conversation_mem_available(std::istream& meminfo); - -inline bool conversation_memory_admit(std::optional available, - uint64_t allocation, uint64_t floor) { - return available && *available >= floor && allocation <= *available - floor; -} - -} // namespace strata::core diff --git a/include/strata/core/conversation_snapshot.hpp b/include/strata/core/conversation_snapshot.hpp deleted file mode 100644 index 1a56680..0000000 --- a/include/strata/core/conversation_snapshot.hpp +++ /dev/null @@ -1,96 +0,0 @@ -#pragma once - -#include "strata/core/conversation_cache.hpp" -#include "strata/core/layer.hpp" -#include "strata/core/session.hpp" - -#include - -namespace strata::core { - -// Caller synchronizes the device before saving, and after restoring all layers. -// include_index is false for the draft layer (its attention has no indexer). -size_t conversation_kv_bytes(const QsaState& state, const ModelGeometry& g, int64_t upto, bool include_index); -// A nonzero unchanged_tokens is valid only for storage retained from an image -// actually restored into this session, bounded by every subsequent rewrite. -// Equal token IDs alone do not establish that its K/V bytes are unchanged. -bool conversation_kv_save(ConversationKv& image, const QsaState& state, const ModelGeometry& g, - int64_t upto, bool include_index, std::string& error, - int64_t unchanged_tokens = 0, size_t* reused_bytes = nullptr); -bool conversation_kv_capture_bytes(const ConversationKv& image, const QsaState& state, const ModelGeometry& g, - int64_t upto, bool include_index, size_t& bytes, std::string& error); -// No CUDA calls or destination writes. Used for whole-session prevalidation. -bool conversation_kv_validate(const ConversationKv& image, const QsaState& state, const ModelGeometry& g, - int64_t upto, bool include_index, std::string& error); -bool conversation_kv_restore(const ConversationKv& image, const QsaState& state, const ModelGeometry& g, - int64_t upto, bool include_index, std::string& error); -// Diagnostic read-back after a synchronized restore. Uses 64 KiB of stack -// workspace, compares authoritative bytes and resident draft-ring pages, and -// fingerprints the authoritative payload only. Never changes model state. -bool conversation_kv_verify(const ConversationKv& image, const QsaState& state, const ModelGeometry& g, - int64_t upto, bool include_index, uint64_t& fingerprint, std::string& error); - -struct ConversationStateSizes { - size_t gdn = 0, ple = 0, tail = 0, dead = 0, block_pos = 0; -}; -/// Whole-model sizes: `gdn` covers every GDN layer, the indexer sizes are per QSA layer. -bool conversation_state_sizes(const ModelGeometry& g, ConversationStateSizes& sizes, std::string& error); -/// The same for one session's layer carve (#216): `gdn` covers its `gdn_alloc` rows; the per-QSA-layer sizes -/// apply to each owned state [qsa_ord0, qsa_ord0 + qsa_alloc). Rejects an inconsistent carve. Checkpoints, -/// snapshots and their validation all use this: a session saves and restores only the state it owns. -bool conversation_session_sizes(const ModelGeometry& g, const SessionState& session, ConversationStateSizes& sizes, - std::string& error); -bool conversation_checkpoint_validate(const ConversationCheckpoint& checkpoint, const SessionState& session, - const ModelGeometry& g, std::string& error); -bool conversation_checkpoint_save(ConversationCheckpoint& checkpoint, const SessionState& session, - const ModelGeometry& g, std::string& error); -bool conversation_checkpoint_restore(const ConversationCheckpoint& checkpoint, SessionState& session, - const ModelGeometry& g, std::string& error); - -struct ConversationView { - const std::vector& ids; - const std::vector& images; - const std::vector& checkpoints; - bool cvec; -}; -bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& session, - const ModelGeometry& g, const QsaState& draft, size_t& bytes, std::string& error); -bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view, - const SessionState& session, const ModelGeometry& g, - const QsaState& draft, size_t& bytes, std::string& error); -// The capture estimate includes retained capacity and transient segment directories; -// only estimate - reuse.bytes() requires additional physical RAM. Capture consumes -// the uniquely owned reusable buffers, including on failure. -// Caller admits the estimate before invoking capture. Allocation failures propagate -// to the RAM policy; the active session is never modified by capture. -bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, - const SessionState& session, const ModelGeometry& g, - const QsaState& draft, std::string& error, - ConversationKvReuse reuse = {}, size_t* reused_bytes = nullptr); -bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& session, - const ModelGeometry& g, const QsaState& draft, std::string& error); -enum class ConversationRestore { restored, invalid, transfer_failed }; -// Invalid images are rejected before any CUDA call/write. Transfer failure may -// leave partial state: caller MUST NOT continue inference from that session. -ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& session, - const ModelGeometry& g, const QsaState& draft, - std::string& error); - -// The same with `draft == nullptr`: an image WITHOUT the draft layer's K/V (kv holds the session's own QSA layers -// only). A layer split's later stages park this way; the draft ring is saved once, with the first stage's image. -// An image is validated and restored with the same kind of call it was saved with (a K/V layer count mismatch is -// rejected as invalid). -bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& session, const ModelGeometry& g, - const QsaState* draft, size_t& bytes, std::string& error); -bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view, - const SessionState& session, const ModelGeometry& g, const QsaState* draft, - size_t& bytes, std::string& error); -bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, const SessionState& session, - const ModelGeometry& g, const QsaState* draft, std::string& error, - ConversationKvReuse reuse = {}, size_t* reused_bytes = nullptr); -bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& session, - const ModelGeometry& g, const QsaState* draft, std::string& error); -ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& session, - const ModelGeometry& g, const QsaState* draft, std::string& error); - -} // namespace strata::core diff --git a/include/strata/core/coupled_draft.hpp b/include/strata/core/coupled_draft.hpp deleted file mode 100644 index d095e3a..0000000 --- a/include/strata/core/coupled_draft.hpp +++ /dev/null @@ -1,90 +0,0 @@ -// include/strata/core/coupled_draft.hpp - COUPLED DRAFT SAMPLING (STRATA_SPEC_COUPLED=1, off by default). -// -// Under sampling the verify window samples row t of a window at position pos0 as Philox(seed, pos0 + t) over the -// sampler chain (penalties -> top_k -> top_p -> min_p -> temperature -> inverse-CDF pick; verify.cpp run(), -// sampler.cu), and a draft is kept only when it EQUALS that row's pick. The output is therefore a function of the -// seed alone, whatever the drafts are: drafts only decide how many tokens a window yields. -// -// The MTP draft layer used to propose its ARGMAX. In coupled mode it SAMPLES instead, with the target's own chain -// (the request's top_k / top_p / min_p / temperature and penalties over the same history) and the SAME uniform the -// target will draw for the row that verifies the draft. When the draft's distribution is close to the target's, -// the two inverse-CDF picks from one uniform agree far more often than an argmax agrees with a sample; the target's -// pick - and so the text - does not change, because verification is still exact-match against the target's sample. -// -// THE COUNTER ARITHMETIC (all positions are sequence indices; a window's row t holds the token at pos0 + t and its -// pick is the token at pos0 + t + 1, drawn with counter pos0 + t): -// * MTP cell c pairs the main model's residual at position c with the token at c + 1 and predicts the token at -// c + 2 (mtp.hpp). -// * After a window at p with a drafts accepted, the next window starts at p' = p + a + 1 (its row 0 is the token -// the window picked at row a). Chain step j (j = 0 ..) runs at cell p + a + j and predicts the token at -// p + a + j + 2 = p' + j + 1: row j + 1 of the next window, VERIFIED BY ROW j's pick, counter p' + j. -// * So a draft made at cell c is verified with counter c + 1 - whatever the window size T, the accepted count, a -// suffix-drafter window in between (its drafts are then simply not used), or `draft_first` (cell p - 1, a = 0 for -// a window at p). The kernel reads c from the step record the host already stages for the cell (device memory, -// so the captured graphs replay with each round's own counter), and the seed and chain from a device copy of the -// request's SamplerParams, refreshed at the start of every round graph. -// -// THE PENALTY HISTORY. The verify row j of the next window counts penalties over penalty_rows(consumed', window') -// row j: the last h of (consumed', x', drafts 0 .. j-1), where consumed' is what the session holds after the commit -// and x' the window's pick at row a. The drafter keeps a device RING of kCoupledHistCap + max_t slots: the host -// stages the base (the last h of consumed' + x', -1 padded in front) in [cap - h, cap) before the round, and draft j -// writes its token to cap + j - so draft j's window is [cap + j - h, cap + j), exactly the row the target will use. -#pragma once - -#include "strata/kernels/sampler.hpp" - -#include -#include -#include -#include - -#if defined(__CUDACC__) || defined(__HIPCC__) -#define STRATA_COUPLED_HD __host__ __device__ -#else -#define STRATA_COUPLED_HD -#endif - -namespace strata::core { - -/// The longest penalty window the coupled drafter mirrors (serve's kPenaltyWindowCap). -inline constexpr int kCoupledHistCap = 4096; - -inline bool& coupled_draft_state() { - static bool on = [] { - const char* e = std::getenv("STRATA_SPEC_COUPLED"); - return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0; - }(); - return on; -} - -/// Whether coupled draft sampling is enabled (via STRATA_SPEC_COUPLED=1 or --coupled-draft CLI flag). -inline bool coupled_draft_env() { - return coupled_draft_state(); -} - -inline void set_coupled_draft(bool on) { - coupled_draft_state() = on; -} - -/// The MTP cell of chain step j after a window at `p` with `a` drafts accepted (draft() runs step j there). -STRATA_COUPLED_HD inline int64_t coupled_draft_cell(int64_t p, int a, int j) { return p + a + j; } - -/// The Philox counter the verify window will draw for the row that checks the draft made at MTP cell `cell`. -STRATA_COUPLED_HD inline uint64_t coupled_draft_counter(int64_t cell) { return (uint64_t) (cell + 1); } - -/// The penalty window the draft layer and the target use: min(penalty_last_n, cap), 0 when penalties are off. -STRATA_COUPLED_HD inline int coupled_hist_len(int penalty_last_n, int cap) { - return penalty_last_n <= 0 ? 0 : (penalty_last_n < cap ? penalty_last_n : cap); -} - -/// Where draft j's penalty window starts in the ring (base in [cap - h, cap), draft i at cap + i). -STRATA_COUPLED_HD inline int coupled_hist_start(int cap, int j, int h) { return cap + j - h; } - -/// The ring's base on the host: the last `h` tokens of (tail[0..n_tail), next), -1 padded in front, into -/// out[0..h) - row 0 of `penalty_rows` for the one-token window [next]. -inline void coupled_hist_base(const int32_t* tail, int64_t n_tail, int32_t next, int h, int32_t* out) { - if (h <= 0) return; - strata::kernels::penalty_rows(tail, n_tail, &next, 1, h, out); -} - -} // namespace strata::core diff --git a/include/strata/core/device.hpp b/include/strata/core/device.hpp deleted file mode 100644 index 091dff1..0000000 --- a/include/strata/core/device.hpp +++ /dev/null @@ -1,95 +0,0 @@ -// include/strata/core/device.hpp - P2.S1: the device arena and the runtime's device facts. -// -// `DeviceArena` is ONE cudaMalloc per planner region with bump sub-allocation below it and no frees. That is -// not a simplification for the first version: the memory plan from P1.S9 is fixed at startup, so the set of -// regions and their sizes is known before anything is allocated, and an allocator that can free would be -// solving a problem the engine does not have while adding fragmentation and failure modes it does. -// -// The reason to get this in early is that the VRAM budget is the binding constraint of the whole design -// (5.95 GB pooled between KV and the expert cache, 33.97 GB of experts in DRAM). A runtime that discovers at -// token 4000 that it has overcommitted has already lost; the plan is printed against `cudaMemGetInfo` at -// startup so the discrepancy is visible immediately. -#pragma once - -#include -#include -#include -#include - -namespace strata::core { - -struct DeviceInfo { - int ordinal = -1; - std::string name; - int cc_major = 0, cc_minor = 0; - uint64_t total_bytes = 0; // as reported by cudaMemGetInfo at query time - uint64_t free_bytes = 0; - int driver_version = 0, runtime_version = 0; - int multi_processor_count = 0; - std::string arch; // HIP: gcnArchName without its feature suffix ("gfx1201"); empty on CUDA -}; - -// HIP builds: whether GPU `ordinal` can run this binary - its architecture must be one the binary was COMPILED -// for (STRATA_HIP_ARCHS, set by cmake/hip_backend.cmake) and it must run wave32. "" when it can (or when there -// is no such device: the caller's own device errors apply), else the reason in a sentence. A binary carried to -// another card would otherwise fail later with "invalid device function". CUDA builds: always "". -std::string gpu_arch_problem(int ordinal); - -// The GPU architectures this binary was compiled for ("gfx1100,gfx1201"); "" on CUDA builds. -const char* compiled_gpu_archs(); - -// How many devices the runtime enumerates, numbered as HIP_VISIBLE_DEVICES / CUDA_VISIBLE_DEVICES number them; 0 when -// there is none (or no usable runtime). `device_info` throws on a card this binary cannot run, so a caller that LISTS -// every card - the ones it has no code for included (`strata-device --list-devices`) - counts them with this first. -int device_count(); - -// One line per device for `strata-device --list-devices`, without the arch check that `device_info` applies: -// "arch gfx1201, 15.9 GiB" (HIP) or "compute capability 12.0, 11.9 GiB" (CUDA), plus the device's name. false when -// the runtime cannot describe it. -bool device_summary(int ordinal, std::string& name, std::string& detail); - -// Throws when there is no CUDA device. The engine targets sm_120 specifically and must say so rather than -// run slowly on something else: `CMakeLists.txt` already refuses to COMPILE for another architecture, and -// this is the matching check at run time (a binary can be carried to a different machine). -DeviceInfo device_info(int ordinal = 0); - -/// "" when this build has device code for the current device, else CUDA's error: a build for other GPUs would -/// otherwise fail at its first kernel launch, with nothing that names the cause. -std::string device_code_error(); - -class CudaError : public std::runtime_error { -public: - CudaError(const std::string& what, int code) : std::runtime_error(what), code_(code) {} - int code() const { return code_; } - -private: - int code_; -}; - -// One cudaMalloc, bump-allocated below. `poison` fills new allocations with a NaN-ish pattern in a debug -// build so that reading uninitialised VRAM gives a NaN rather than a plausible number - the same reasoning as -// the harness work in Phase 1: a wrong value that looks right is the expensive kind. -class DeviceArena { -public: - explicit DeviceArena(uint64_t bytes, int ordinal = 0, bool poison = false); - ~DeviceArena(); - DeviceArena(const DeviceArena&) = delete; - DeviceArena& operator=(const DeviceArena&) = delete; - - // `align` must be a power of two; 256 keeps every sub-allocation at a sector boundary. - void* alloc(uint64_t bytes, uint64_t align = 256); - - uint64_t capacity() const { return capacity_; } - uint64_t used() const { return used_; } - uint64_t peak() const { return used_; } // no frees, so used IS the peak - int ordinal() const { return ordinal_; } - void* base() const { return base_; } - -private: - void* base_ = nullptr; - uint64_t capacity_ = 0, used_ = 0; - int ordinal_ = 0; - bool poison_ = false; -}; - -} // namespace strata::core diff --git a/include/strata/core/emulate.hpp b/include/strata/core/emulate.hpp deleted file mode 100644 index 6f28b97..0000000 --- a/include/strata/core/emulate.hpp +++ /dev/null @@ -1,36 +0,0 @@ -// strata/core/emulate.hpp - STRATA_EMULATE_CC: another GPU generation's code paths, run on this card (tests only). -// -// A build whose device code is PTX for an older architecture (CMAKE_CUDA_ARCHITECTURES=86-virtual) runs on a newer -// card through the driver's JIT, and every kernel then sees __CUDA_ARCH__ = 860. What the host decides from the -// device must agree with that, or it picks paths and shared-memory sizes the device code was not built for: -// STRATA_EMULATE_CC=75|80|86|89 makes each such query (compute capability, shared memory per block) answer as that -// card would. Speed under it says nothing about the real card; results do - the kernels are the real card's. -#pragma once - -#include - -namespace strata { - -/// the emulated compute capability as 10 * major + minor, or 0 (off) -inline int emulated_cc() { - static const int cc = [] { - const char* e = std::getenv("STRATA_EMULATE_CC"); - const int v = e ? std::atoi(e) : 0; - return v >= 75 && v < 120 ? v : 0; - }(); - return cc; -} -inline int cc_major_of(int real_major) { return emulated_cc() ? emulated_cc() / 10 : real_major; } -inline int cc_minor_of(int real_minor) { return emulated_cc() ? emulated_cc() % 10 : real_minor; } -/// cudaDevAttrMaxSharedMemoryPerBlockOptin as the emulated card reports it: 64 KB on Turing, 163 KB on the A100, -/// 99 KB on the other Ampere and Ada cards -inline int smem_optin_of(int real) { - switch (emulated_cc()) { - case 0: return real; - case 75: return 65536; - case 80: return 166912; - default: return real < 101376 ? real : 101376; - } -} - -} // namespace strata diff --git a/include/strata/core/expert_cache.hpp b/include/strata/core/expert_cache.hpp deleted file mode 100644 index 8c031ff..0000000 --- a/include/strata/core/expert_cache.hpp +++ /dev/null @@ -1,227 +0,0 @@ -// include/strata/core/expert_cache.hpp - R4: the VRAM-resident expert tier. -// -// **WHY THIS EXISTS, IN ONE PARAGRAPH.** The CPU expert pool is the engine's largest single cost: measured, -// **663.6 MB of expert bytes per token at ~40 GB/s = 16.2 ms**, on a token of ~53 ms, and `test_expert_pool` -// says the pipeline hides **1.055 ms of 19.035** - the CPU work is 96% exposed because the residual chain is -// strictly serial. The only way past it is to stop reading those bytes: put some of the 48 x 512 experts in -// VRAM and let the GPU compute them, so the CPU reads only the misses. -// -// **THE DESIGN IS SIZED AGAINST MEASUREMENTS, NOT AGAINST THE PLAN'S ASSUMPTIONS.** -// -// * `h_expert` at 4,105 slots, **ten-fold leave-one-out: 0.6447 [0.6110, 0.6750]** (`tools/routing_kfold.py`). -// The 0.6573 the README published is in-sample and 0.4720 measured a single-prompt CORPUS, not the metric. -// * VRAM, measured on a live run rather than at startup: **6414 MiB free** with the engine at steady state, -// against **5413 MiB** for 4,105 slots. It fits, with ~1 GB spare. `strata-device`'s planner agrees and says -// FITS, but the planner runs before the dense arena exists, so the live figure is the one that counts. -// * `h_layer` held-out is **0.0456** - only 4.6% of (layer, token) pairs have all ten experts resident - so -// this cannot be a per-layer grouped kernel and the three-way split is not an optimisation. -// -// **WHAT THIS FILE IS.** The SLOT STORAGE and the RESIDENCY TABLE: it allocates the VRAM, fills it from the host -// arena, and answers `(layer, expert) -> slot or -1`. It computes nothing itself: the GPU computes the experts it -// holds in the verify window's grouped kernels and the prompt path (the hit/miss split), and the CPU pool the rest. -// (Written when nothing consumed the slots yet and `--expert-cache` defaulted to 0; setup's configs use `auto`.) -#pragma once - -#include -#include -#include -#include - -namespace strata::core { - -/// Where one expert's VRAM lives, or -1. `int32_t` and not a bool because the slot index is what the kernel -/// needs, and a table that has to be re-derived from a bitmask is a table that will be re-derived differently -/// in the two places that use it. -inline constexpr int32_t kNotResident = -1; - -/// **THE STATIC RESIDENCY PLAN, READ BACK FROM THE FILE `tools/make_profile.py` WROTE.** -/// -/// `profile.bin` is `STRP`, then `version, n_layers, n_expert, slots, n_ranked`, then `n_ranked` `(layer, -/// expert)` pairs ranked by descending routing frequency, then a `n_layers x n_expert` frequency table. -/// -/// **WHY A PROFILE AND NOT THE COMPULSORY-MISS POLICY THIS ENGINE ALREADY HAD.** Compulsory-miss fills with -/// the first `S` DISTINCT experts the run happens to route, which on this workload is whatever the prompt -/// touched first - it measured `h = 0.4864`. A profile ranked by frequency over a whole trace is what the -/// plan's `0.6447` refers to, and the CPU's half of the drain is linear in `h`, so the gap is worth about -/// 4 ms of drain. The point of reading it from a file is that a profile built on ONE prompt can be scored on -/// ANOTHER, which is the only way to know whether it transfers. -/// -/// The frequency table is not returned: it is the profile's own working, and the engine measures `h` by -/// running rather than by re-deriving what the file claims. -bool read_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert, - std::vector>& ranked, int64_t& slots, std::string& err); - -/// #477 (--expert-profile-save): what the adaptive tier learned, as a profile ranking EVERY (layer, expert) pair - -/// the experts resident in VRAM now first (where the swaps left the cache), then the rest; within each, by `heat` -/// (the routing the adaptive tier counted since the start, descending), then by `prior` (the profile the engine -/// started from: an expert this run never routed keeps its old place), then by index. A start from it begins -/// where this one ended; one with more slots adds the hottest of the rest, one with fewer keeps the hottest. -/// `resident` and `heat`: n_layers x n_expert entries (`heat` may be empty: no counts, the prior decides). -std::vector> rank_learned_profile(int64_t n_layers, int64_t n_expert, - const std::vector& resident, - const std::vector& heat, - const std::vector>& prior); - -/// #477: writes `ranked` in tools/make_profile.py's format, byte for byte: `STRP`, `1, n_layers, n_expert, -/// n_ranked, n_ranked` (uint32), the pairs (uint16 layer, uint16 expert), then the n_layers x n_expert int32 table -/// of each pair's rank (-1: not ranked). Atomically: a `.tmp` beside it, renamed over `path` once complete, -/// so a reader (the next start) never sees half a file. False with `err` when it could not be written. -bool write_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert, - const std::vector>& ranked, std::string& err); - -class ExpertCache { -public: - ExpertCache() = default; - ~ExpertCache(); - ExpertCache(const ExpertCache&) = delete; - ExpertCache& operator=(const ExpertCache&) = delete; - - /// Allocates `n_slots * blob_bytes` of DEVICE memory and a `n_layers * n_expert` residency table, and - /// **CHECKS THE ALLOCATION AGAINST WHAT THE CARD ACTUALLY HAS** rather than assuming the planner was right. - /// A cache that silently allocates less than it was asked for would report a hit rate for slots it does - /// not have, which is the shape of error this project keeps paying for. - bool open(int64_t n_slots, int64_t n_layers, int64_t n_expert, int64_t blob_bytes, std::string& err); - /// Plan v0.3 P6: slots of the given sizes, back to back (a native pack's blobs differ per layer, and a - /// profile-filled tier never moves an expert to another layer's slot, so each slot keeps its first size). - bool open_sized(const std::vector& slot_bytes, int64_t n_layers, int64_t n_expert, std::string& err); - /// Byte offset of each slot in the arena (null for uniform slots). - const uint64_t* slot_offsets() const { return off_.empty() ? nullptr : off_.data(); } - void close(); - - bool valid() const { return base_ != nullptr; } - /// The slots usable now: all of them, unless `shrink` gave the tail's VRAM back (#533) - then the ones wholly - /// inside the VRAM still backed, always a prefix. The prompt path's loan (the last slots) and every report - /// follow this; `full_slots()` is what `open` allocated. - int64_t slots() const { return live_slots_; } - int64_t full_slots() const { return slots_; } - /// Slots actually claimed. Not the same as `slots()` - the cache does not evict, so a run that routes - /// fewer distinct experts than there are slots leaves the rest empty. - int64_t resident() const { return per_layer_ ? admitted_ : next_free_; } - /// The bytes of `slots()` (all of the arena unless shrunk); `full_bytes()`: of every slot. - int64_t bytes() const { return slot_end(live_slots_); } - int64_t full_bytes() const { return slot_end(slots_); } - double gib() const { return (double) bytes() / 1073741824.0; } - - /// **#533: HOT VRAM RESIZE, OPT-IN (--vram-elastic).** With a segment size set before `open`/`open_sized`, the - /// arena is one reserved address range backed by physical segments of that size (CUDA virtual memory - /// management) instead of one cudaMalloc, so `shrink` can give the tail's VRAM back to the driver - for another - /// program - and `grow` can take it again, while every slot keeps its address (the captured graphs, the verify - /// plan's pointers and the prompt path's loan all hold addresses into it). 0 (the default): one cudaMalloc, as - /// always. CUDA only: a HIP build refuses it at open. The slots past `slots()` after a shrink must hold no - /// resident expert and no loan: the CALLER evicts them first (they become CPU misses). - void set_segment_bytes(int64_t seg_bytes) { seg_req_ = seg_bytes > 0 ? seg_bytes : 0; } - bool segmented() const { return !segs_.empty(); } - int64_t segment_bytes() const { return seg_; } - /// Bytes of the arena backed by VRAM now (a whole number of segments; the arena when not segmented). - int64_t mapped_bytes() const; - /// Unmaps every segment past the first `keep_bytes` (rounded UP to a segment boundary): `slots()` becomes the - /// slots wholly inside what stays. Waits for the device first. False with `err` when not segmented or a driver - /// call failed. - bool shrink(int64_t keep_bytes, std::string& err); - /// Maps segments again up to `want_bytes` (rounded DOWN to a segment, at most the arena; the last, shorter - /// segment only when `want_bytes` covers the arena). Stops at the first segment the driver cannot back (false, - /// `err`: what was mapped by then stays). The new slots are empty until the caller fills them. - bool grow(int64_t want_bytes, std::string& err); - /// The number of leading slots that fit wholly inside the first `bytes` bytes. - int64_t slots_within(int64_t bytes) const; - /// The bytes the first `n` slots span. - int64_t bytes_of(int64_t n) const { return slot_end(n < 0 ? 0 : n > slots_ ? slots_ : n); } - - /// `(layer, expert)` -> slot index, or `kNotResident`. Bounds-checked: a bad layer or expert returns - /// `kNotResident` rather than reading whatever is adjacent in the table. - int32_t slot_of(int64_t layer, int64_t expert) const; - /// Claims the next free slot for `(layer, expert)`. Returns the slot, or `kNotResident` when the cache is - /// full - **it never evicts**, because eviction policy is a measured question (`R4.1`'s LFU-decay vs LRU - /// sweep) and a placeholder policy would set the hit rate that everything downstream is then sized against. - int32_t admit(int64_t layer, int64_t expert); - - /// Publish a same-layer replacement after its slot copy has completed. - void replace(int64_t layer, int32_t old_expert, int32_t new_expert) { - auto& old = residency_[(size_t) layer * n_expert_ + old_expert]; - residency_[(size_t) layer * n_expert_ + new_expert] = old; - old = kNotResident; - } - - /// **R4.2g: GIVE EACH LAYER ITS OWN SLOTS. ROUND 328 MEASURED WHY THE GLOBAL FORM CANNOT WORK.** - /// - /// `admit`'s original policy hands out slots in ARRIVAL ORDER from one counter shared by every layer - /// (`if (next_free_ >= slots_) return kNotResident;`). A position looks at 10 experts in each of 48 - /// layers, so the first `n_slots` distinct (layer, expert) pairs are **about 26 layers of POSITION 0** - - /// the cache fills entirely inside the first position it ever sees and never changes again, so hits are - /// confined to those few layers for the rest of the run. - /// - /// Measured, `--expert-cache 256`: **1781 of 60000 = 2.97%**. `Memory/cache_allocation.py` scores the - /// same run's routing and says **8 slots per layer is worth 21.4%** and 64 is worth **70.4%**. The cache - /// was never short of capacity - it was handing all of it to two layers. - /// - /// With this on, layer `l` may only use slots `[l*q, (l+1)*q)` where `q = slots()/n_layers`, the last - /// layer taking the remainder. **EVICTION IS STILL ABSENT** - the property the comment above calls - /// deliberate is preserved exactly; only WHICH slot a layer may take changes. Default off, so every - /// caller that predates this flag is bit-for-bit unaffected. - void set_per_layer_admission(bool on) { per_layer_ = on; } - bool per_layer_admission() const { return per_layer_; } - /// The slot range layer `l` may admit into under per-layer admission. Exposed so a test can check it. - void layer_slot_range(int64_t layer, int64_t& lo, int64_t& hi) const; - - /// The device address of one slot. - uint8_t* device_slot(int32_t slot); - const uint8_t* device_slot(int32_t slot) const; - - /// Copies `(layer, expert)`'s blob from `host_blob` into `slot` on `stream`. Asynchronous: the caller - /// orders it. Returns false if the indices are out of range rather than reading past the arena. - /// `bytes` (plan v0.3 P6): the blob's own size when it is smaller than the slot (a native pack); 0 = the slot. - bool fill_slot(int32_t slot, const uint8_t* host_blob, void* stream, std::string& err, int64_t bytes = 0); - - /// **THE SAME COPY, BUT BLOCKING, AND THE PROFILE FILL NEEDS IT.** `fill_slot` is asynchronous because on - /// the token path the fill and the kernel that reads it are ordered by one stream and waiting would be a - /// synchronisation per layer. At STARTUP there is no such ordering to lean on: the source is pageable host - /// memory, `verify_slot` reads the slot back on the LEGACY stream, and a legacy-stream copy is not ordered - /// against a `cudaStreamNonBlocking` one. The first version used the async form and `verify_slot` refused - /// the whole run with "slot 0 differs from the arena at byte 0" - which is the check doing its job. - bool fill_slot_blocking(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes = 0); - /// perf-review D-4: `fill_slot_blocking`'s copy on the same (legacy) stream, but queued: many slots are refilled - /// with one `sync_queued` at the end instead of a wait per slot. Same ordering against earlier work, same bytes. - bool fill_slot_queued(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes = 0); - bool sync_queued(std::string& err); - - /// Reads `slot` back to the host and compares it to `host_blob`, byte for byte. **THE ONLY THING THAT SAYS - /// THE CACHE HOLDS THE EXPERT IT CLAIMS TO.** A slot table that is right about indices and wrong about - /// bytes produces a plausible token, which is exactly the failure this project has paid for most often. - bool verify_slot(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes = 0); - - /// Slots filled so far, for the startup report. - int64_t fills() const { return fills_; } - -private: -#if defined(STRATA_USE_HIP) - bool ensure_blocking_staging(std::size_t bytes, std::string& err); - uint8_t* blocking_staging_ = nullptr; - std::size_t blocking_staging_bytes_ = 0; -#endif - int64_t slot_end(int64_t n) const { return off_.empty() ? n * blob_ : (int64_t) off_[(size_t) n]; } - bool open_segmented(uint64_t want, std::string& err); - void release_segmented(); - uint8_t* base_ = nullptr; - int64_t live_slots_ = 0; ///< #533: slots() - all of them unless shrunk - int64_t seg_req_ = 0; ///< #533: the segment size asked for (0: one cudaMalloc) - int64_t seg_ = 0; ///< #533: the segment size used (a multiple of the driver's granularity) - uint64_t reserved_ = 0; ///< #533: the reserved address range's size - std::vector segs_; ///< #533: each segment's physical handle (0: unmapped) - std::vector seg_size_; ///< #533: each segment's size (the last one may be shorter) - int64_t mapped_segs_ = 0; ///< #533: segments [0, mapped_segs_) are backed - std::vector residency_; ///< [n_layers * n_expert] -> slot or kNotResident - int64_t slots_ = 0; - int64_t n_layers_ = 0; - int64_t n_expert_ = 0; - int64_t blob_ = 0; - int64_t next_free_ = 0; - int64_t fills_ = 0; - /// R4.2g. `per_layer_` off (the default) leaves `next_free_` as the only admission counter, so the - /// pre-existing path is untouched. - bool per_layer_ = false; - std::vector layer_next_; ///< [n_layers] -> that layer's next free slot - std::vector off_; ///< plan v0.3 P6: slot offsets (slots + 1 entries) when sized - int64_t admitted_ = 0; -}; - -} // namespace strata::core diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp deleted file mode 100644 index de9ccc0..0000000 --- a/include/strata/core/expert_source.hpp +++ /dev/null @@ -1,727 +0,0 @@ -// include/strata/core/expert_source.hpp - P2.S3/P2.S5: the expert pool's adapter to the host loop. -// -// `session_loop` publishes, per layer, the NORMED activation `x_f`, the ten routed expert ids and their router -// weights, and expects `k x n_embd` floats back. This is the piece that turns those four things into an -// `ExpertPool::run` call. Nothing here is clever, and that is the point: the pool, the kernel and the loop are -// each already verified, so this file has exactly one job - get the CONTRACT between them right. -// -// THE CONTRACT, and each clause is a way to be wrong: -// -// 1. **`x_f` IS THE SAME PINNED BUFFER EVERY LAYER.** Its ADDRESS never changes, so the `ActQ` cannot be -// cached by pointer - a cache keyed on `x_f` would quantize layer 0 and reuse it for all 47 remaining -// layers, which is a finite, plausible, completely wrong token. There is no cache here at all: the -// conversion is one 2560-element pass against a 0.3 ms/layer budget, and a correct answer is worth more -// than the microseconds. -// 2. **THE POOL DOES NOT APPLY THE ROUTER WEIGHT.** `moe_combine` (`src/core/layer.cpp:479`) sums -// `w[i] * parts[i]` on the device. `ExpertJob::weight` is a diagnostic field; setting it here would -// apply the weight twice, which is invisible in a single layer and compounds over 48. -// 3. **THE KERNEL'S GEOMETRY IS FIXED BY THE ARTIFACT** (`H = 2560`, `FF = 640`, `BLOB = 1,382,400`). A -// different `n_embd` or a different expert width is REFUSED rather than mis-indexed, because the blob's -// internal offsets are compile-time constants and reading a 640-wide expert as a 2560-wide one walks off -// the end into the next expert's bytes without faulting. -#pragma once - -#include "strata/core/expert_cache.hpp" -#include "strata/core/hit_hook.hpp" -#include "strata/kernels/cpu/pool.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace strata::kernels::cpu { -struct ExpertLayout; -} - -namespace strata::core { - -class PeerExperts; // multi-GPU: the second GPU's expert tier (peer_experts.hpp) -class RemoteExperts; -struct LoadStats; - -namespace detail { - -/// Sentinel used by the pure complement planner for a blob that remains in the mmap fallback. -inline constexpr uint64_t kNoCacheComplement = ~uint64_t{0}; - -/// Required cgroup-v2 usage counters for the conservative cache-reclaim allowance. -struct CgroupMemoryStat { - uint64_t current = 0; - uint64_t inactive_file = 0; - uint64_t file_dirty = 0; - uint64_t file_writeback = 0; - bool valid = false; -}; - -/// Calculate additional bytes under a finite cgroup limit after reclaiming only clean inactive file cache. -/// Returns false when the required memory.stat counters were unavailable. -bool cgroup_available_bytes(uint64_t limit, const CgroupMemoryStat& stat, uint64_t& bytes); - -/// #633: the RAM this process can get. `available`: MemAvailable (Windows: the available physical memory), lowered -/// to the room under the tightest cgroup limit; `cgroup_limit`: that tightest limit itself (v2 memory.max of the group -/// and its ancestors, or v1 memory.limit_in_bytes), ~0 when there is none - what a container can never exceed. -struct HostMemory { - uint64_t available = 0; - uint64_t cgroup_limit = ~uint64_t{0}; -}; - -/// Linux reads `meminfo`, `self_cgroup` and the cgroup tree under `cgroup_root` (the parameters are for tests; the -/// defaults are the real files). cgroup v2 as before (an unreadable limit of a group that has one fails); cgroup v1's -/// memory controller (`/memory/`: memory.limit_in_bytes - memory.usage_in_bytes); no cgroup line at all is -/// MemAvailable alone. False when the RAM cannot be determined. -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. -bool make_cache_complement_plan( - int64_t n_layers, int64_t n_expert, const std::vector& layer_blob_bytes, - const std::vector>& primary_gpu_pairs, - const std::vector>& additional_gpu_pairs, - std::vector& offsets, uint64_t& bytes, std::string& err); - -/// Resolve one blob through the compact copy when present, otherwise preserve its exact mapped-file fallback. -const uint8_t* cache_complement_blob_or_fallback( - size_t index, const std::vector& offsets, const uint8_t* complement_host, - const uint8_t* mapped_fallback); - -/// The resident RAM mode: which GPU-cache slots' experts are kept in RAM too. The prompt path lends the cache's -/// LAST slots (from `lend_from` on; a short prompt lends only the last few), and a lent slot's expert is streamed -/// from RAM during the prompt and copied back into its slot after it. `base_bytes` (every expert no slot holds) -/// must fit `budget`; slots are then added from the end down to `lend_from` while they still fit. Returns the -/// first slot kept in RAM (`slot_bytes.size()` = none), or -1 when `base_bytes` alone exceeds `budget`. -int64_t choose_resident_keep_from(const std::vector& slot_bytes, uint64_t base_bytes, uint64_t budget, - int64_t lend_from); - -/// The adaptive tier swapped `in` into a GPU slot and `out` out of it: `out` takes `in`'s place in the compact copy -/// (the caller copies out's bytes there). False, and nothing changed, unless `in` is in the copy and `out` is not. -bool exchange_cache_complement(std::vector& offsets, size_t in, size_t out); - -} // namespace detail - - - -/// Where one routed expert's bytes come from. -/// -/// Phase 2 has NO cache (`phase-2-correct-engine.md`: hit rate `h = 0`), so the only implementation is a -/// file-backed reader. The interface exists anyway because Phase 3 replaces exactly this object with the VRAM -/// cache, and because a test can supply an in-memory source without a 34 GB artifact. -class ExpertSource { -public: - virtual ~ExpertSource() = default; - - /// The expert-layout blob for `(layer, expert)`, or nullptr if it cannot be produced. - /// - /// The pointer only has to stay valid until the next `blob()` call: with `h = 0` every expert is computed - /// immediately and nothing is retained. A CACHING source must return pointers into the cache, not into a - /// reused staging buffer - otherwise the pool would read the next expert's bytes while computing this one. - virtual const uint8_t* blob(int64_t layer, int64_t expert) = 0; - - /// Blobs touched, for the driver to report. A source that does not count returns 0. - virtual int64_t reads() const { return 0; } - - /// Plan v0.3 P5: whether `blob(layer, expert)` lies in page-locked, CUDA-registered memory, so an - /// asynchronous host-to-device copy can DMA it directly (no staging copy on the CPU). - virtual bool pinned(int64_t layer, int64_t expert) const { (void) layer; (void) expert; return false; } - - /// Called once before the first expert of a layer. A source that reads from disk wants to start the read - /// here so it overlaps the quantisation, and a prefetching source in Phase 3 wants the ids. - virtual void begin_layer(int64_t layer, const int32_t* ids, int64_t k) { (void) layer; (void) ids; (void) k; } - /// Plan v0.3 P6: the DEVICE address of a pinned, mapped blob (the GPU can read it over PCIe), or null. - virtual const uint8_t* device_alias(int64_t layer, int64_t expert) const { (void) layer; (void) expert; return nullptr; } - /// A file-backed source: start reading this expert's pages now (it will be needed by the CPU); no-op elsewhere. - virtual void prefetch(int64_t layer, int64_t expert) { (void) layer; (void) expert; } - /// A file-backed source: this expert lives in VRAM, so its pages need not stay in RAM - hand them back to the - /// kernel (a later read re-reads the file; no result depends on it). Returns the bytes released; 0 elsewhere. - virtual uint64_t release(int64_t layer, int64_t expert) { (void) layer; (void) expert; return 0; } - /// Whether the verify window may give the GPU a PCIe share of this layer's misses at all (each expert is still - /// checked with `pinned`). The arena answers per layer through its expert 0; the resident RAM mode's compact - /// copy has no expert 0 when the GPU cache holds it, so it answers for the whole copy. - virtual bool pcie_layer(int64_t layer) const { return device_alias(layer, 0) != nullptr; } - - /// CS-T: whether `blob(layer, expert)` would be assembled into a short-lived buffer (a native pack read from its - /// GGUF shards in place, where an expert's gate, up and down rows are three separate slices). Such a pointer - /// stays valid for the layer it was asked in and the next one or two; a consumer that keeps a blob longer (the - /// prompt path's stager queues a whole chunk) copies it with `copy_blob` instead. - virtual bool transient(int64_t layer, int64_t expert) const { (void) layer; (void) expert; return false; } - /// The blob's bytes into `dst` (blob_bytes(layer) of them). Safe from several threads for a source whose - /// `transient` can be true. - virtual bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst); - /// The `n` experts of `layer` the CPU is about to ask `blob` for, all at once: a source that reads a file may - /// fetch them in parallel. The bytes `blob` then returns are the same. Default: nothing. - virtual void prefetch(int64_t layer, const int64_t* experts, int64_t n) { (void) layer; (void) experts; (void) n; } - /// CS-T: the experts of `layer` a predictor expects next - a source that reads a file may start reading their - /// pages now, in the background. Only warms: what `blob` returns is unchanged. Default: nothing. - virtual void warm(int64_t layer, const int64_t* experts, int64_t n) { (void) layer; (void) experts; (void) n; } - /// Whether `warm` does anything (the predictor is not run otherwise). - virtual bool warms() const { return false; } -}; - -/// CS-T, routing-aware prefetch of the file tier: when the CPU pool starts layer `l`, a worker thread applies layer -/// l+1's router (BF16, host copy) to layer l's MoE input - the residual stream changes little from one layer to the -/// next - takes each token's top `k` experts, drops the ones the GPU cache or the RAM copy holds, and asks the -/// source to `warm` the rest, so their pages are on the way while layer l computes. A prediction only warms pages: -/// it never changes which experts are computed or how. -class RouterLookahead { -public: - RouterLookahead() = default; - ~RouterLookahead(); - RouterLookahead(const RouterLookahead&) = delete; - RouterLookahead& operator=(const RouterLookahead&) = delete; - /// `routers[l]`: layer l's ffn_gate_inp as BF16 bits, n_expert rows of n_embd. - bool start(std::vector> routers, int64_t n_embd, int64_t n_expert, int k, ExpertSource* src, - std::string& err); - /// Layer `layer`'s MoE input for `n_tok` tokens (host floats): predict and warm layer + 1. Never waits: a - /// prediction still running for an earlier layer makes this one skip. - void submit(int64_t layer, const float* x, int64_t n_tok, const int32_t* host_res); - int64_t predicted() const { return predicted_.load(std::memory_order_relaxed); } - int64_t skipped() const { return skipped_.load(std::memory_order_relaxed); } - double busy_ms() const { return (double) busy_us_.load(std::memory_order_relaxed) / 1000.0; } - -private: - void run(); - std::vector> routers_; - int64_t n_embd_ = 0, n_expert_ = 0; - int k_ = 10; - ExpertSource* src_ = nullptr; - std::thread thread_; - std::mutex mu_; - std::condition_variable cv_; - bool quit_ = false, pending_ = false, busy_ = false; - int64_t layer_ = -1, n_tok_ = 0; - const int32_t* host_res_ = nullptr; - std::vector x_; - std::atomic predicted_{0}, skipped_{0}; - std::atomic busy_us_{0}; -}; - -/// Plan v0.3 P6: what the GPU computes in a verify window's layer, written by the pool (mapped host memory) right -/// after the ring and published before the CPU starts its own share. Groups of entries that share a blob; the -/// blob is a VRAM slot or a pinned host blob read over PCIe. -struct GpuPlanSink { - int32_t* counts = nullptr; ///< [0] groups, [1] entries - int32_t* start = nullptr; ///< cap + 1 - int32_t* dst = nullptr; ///< cap: the entry's row of parts (token * k + j) - int32_t* tok = nullptr; ///< cap: the entry's token - unsigned long long* ptr = nullptr; ///< cap: the group's blob, device address - /// Plan v0.3 P6 (DMA): the PCIe share is a second list of groups - `ptr2[q]` is staging slot q, `start2` indexes - /// the same dst/tok entries - computed by the GPU after `fetch` has copied their blobs into staging with the - /// copy engine. counts[0] = VRAM groups, counts[1] = all entries, counts[2] = PCIe groups. - unsigned long long* ptr2 = nullptr; - int32_t* start2 = nullptr; - unsigned long long staging = 0; - int64_t staging_cap = 0; - int64_t cap = 0; - void (*publish)(void* ctx) = nullptr; - /// Starts the DMA copies of `n` host blobs (pinned) into staging slots 0..n-1 and signals the GPU when they land. - void (*fetch)(void* ctx, const uint8_t* const* src, int n, size_t bytes) = nullptr; - void* ctx = nullptr; - /// Plan v0.3 P6: how a PCIe group reaches the GPU. 0 = the copy engine stages it (DMA, `fetch`); 1 = the grouped - /// kernel reads the mapped arena directly; 2 = a copy kernel stages it inside the graph. For 1 and 2 `ptr2` - /// holds the arena's device alias. - int pcie_mode = 0; -}; - -/// The adapter's own state. One per session, reused every layer so the token path allocates nothing (P2.T10). -struct ExpertDispatch { - strata::kernels::cpu::ExpertPool* pool = nullptr; - ExpertSource* src = nullptr; - RouterLookahead* lookahead = nullptr; ///< CS-T: warms the next layer's predicted file-tier experts - RemoteExperts* remote[3] = {}; ///< optional CUDA1..3 tiers for otherwise CPU-served rows - int remote_count = 0; - int64_t n_expert = strata::kernels::cpu::NE; - - /// Counters, for the driver to report rather than for control flow. - int64_t layers = 0; - int64_t experts = 0; - int64_t missing = 0; - - // ================================ R4: THE VRAM TIER, MEASURED BEFORE IT IS USED ================================ - // - // **THE CACHE IS CONSULTED AND FILLED HERE, AND NOTHING IS COMPUTED FROM IT YET.** That is deliberate and - // it is `R4-design-note.md` §7 step 2: the *dispatch* is measured on its own before any kernel is written, - // because a hit rate measured after the kernel exists cannot say whether a disappointing result was the - // policy, the split or the kernel. - // - // So every expert is still computed by the CPU, exactly as before, and the run is numerically identical - // with the cache on or off. What changes is that the engine now reports **h on its own routing, on a real - // workload** - which is the number `R4.1` asks for and which until now existed only from offline traces. - // - // The policy is compulsory-miss: the first time `(layer, expert)` is routed, if a slot is free it is - // admitted and filled from the arena. No eviction, because eviction policy is the measured question - // (`R4.1`'s LFU-decay vs LRU sweep) and a placeholder would set the hit rate everything is sized against. - ExpertCache* cache = nullptr; - int64_t cache_hits = 0; ///< lookups already resident - int64_t cache_admitted = 0; ///< lookups that took a slot - int64_t cache_refused = 0; ///< lookups with no slot free (the cache is full) - void* cache_stream = nullptr; - const char* cache_fail = nullptr; - - // ================================ R4.2c: THE HITS GO TO THE GPU ================================ - // - // **THE SPLIT IS BY ROUTER INDEX, AND THAT IS THE WHOLE TRICK.** A layer routes ten experts; the resident - // ones are computed on the GPU and the rest on the CPU, and both answers have to end up in `parts` at the - // index the ROUTER gave them, because that is the order `moe_combine` weights against. So the CPU's `out` - // rows are zeroed for the hits, and each hit carries its routed index to the kernel as `dst`. - // - // Everything below is per-session state rather than per-call, so the token path allocates nothing (P2.T10). - const uint8_t* cache_base = nullptr; ///< the slot arena on the DEVICE - int64_t cache_blob = 0; ///< bytes per slot - const uint64_t* cache_slot_off = nullptr; ///< plan v0.3 P6: per-slot offsets when the slots differ in size - void* hit_scratch = nullptr; ///< `moe_hit_grouped_scratch_bytes(K, ...)` - float* parts_out = nullptr; ///< the graph's `parts` buffer, on the device - /// Where the GPU's hits land, `K x n_embd`, DEVICE and separate from `parts_out` on purpose: see - /// `HitPhase`. Zeroed by the hit path each layer before the kernel writes it. - float* hit_out = nullptr; - int64_t parts_elems = 0; ///< `K * n_embd`, the length of both buffers - const float* mixed = nullptr; ///< the layer's normed activation, for the hit kernel's Q8_0 - uint8_t* x_q8_0_hit = nullptr; ///< `(n_embd/32) * 34` bytes, its own buffer - /// **R4.2h: THE CPU's fp32 ACTIVATION SCALES, `(n_embd/32)` FLOATS.** Without them the GPU's hits are - /// computed with the `block_q8_0`'s fp16 `d` while the CPU's misses use the fp32 `ActQ::scale` - /// (`cpu/expert.cpp:92`) - **4.761e-04 relative on 80 of 80 chunks**, measured with both real - /// implementations linked in `bench/micro/act_quant_parity.cu`. That disagreement is why turning the - /// cache on changed the generated tokens. Required whenever the hit path runs. - float* x_q8_0_hit_scale = nullptr; - int32_t* d_slot = nullptr; ///< device, K entries - int32_t* d_dst = nullptr; ///< device, K entries - std::vector h_slot, h_dst; ///< host staging, sized at session setup - /// **PER ROUTER INDEX, DECIDED IN `Launch` AND CONSUMED BY THE POOL.** The two callbacks share it - /// so the decision is made exactly once, on this layer's ids, and neither side can re-decide it. - std::vector is_hit; - bool decided = false; - /// Plan v0.3 P4 token graph: the STATIC residency table (`n_layers x n_expert`, slot or -1), the host's copy - /// of what the device hit path reads. When set, the pool leaves a resident expert's row at zero (the GPU - /// computes it) without any `Launch` callback. - const int32_t* host_res = nullptr; - /// Plan v0.3 P4: split every expert by rows across the pool's threads (default on; A/B `--no-split-rows`). - bool split_rows = true; - - // ================================ R4.2d: DID THE GPU ACTUALLY START? ================================ - // - // **THE HIT PATH IS 0.91 ms SLOWER AND THE ONLY EXPLANATION LEFT IS THAT IT NEVER OVERLAPS.** The kernel - // is 159 GB/s against the CPU's 35, the CPU's half of the drain falls 6 ms, and none of it reaches the - // token - which is what it would look like if the enqueued hit kernels did not BEGIN until the host next - // entered the driver, i.e. after `pool()` returned. That is the third sighting of this driver behaving - // that way (rounds 195/287 on the doorbell, round 36 on the head and sampler) and it decides whether R4 can - // pay at all, so it gets measured rather than argued. - // - // `hit_done` is recorded on the stream straight after the hit kernel. `Combine` - which runs after the - // pool - queries it: SUCCESS means the GPU finished while the CPU was working, NOT-READY means it had not. - // Same shape as the doorbell's `rings_mid_graph`, and for the same reason. - void* hit_done = nullptr; ///< cudaEvent_t, created at session setup - int64_t hit_ready = 0; ///< layers where the hit work was DONE by the time the pool returned - int64_t hit_late = 0; ///< layers where it was not - /// The candidate fix, as an A/B arm: enter the driver once right after the hit launch. If submission is - /// lazy, this starts the GPU work before the pool instead of after it. - bool hit_poke = false; - bool hit_cpu_order = false; ///< experimental CPU-order GPU expert arithmetic; opt-in only - int64_t n_hits = 0; ///< this layer's hits - /// Set by `Launch` and consumed by `Combine`, so a `Combine` with no `Launch` in front of it cannot - /// add a stale buffer into `parts`. - bool hit_pending = false; - const char* hit_fail = nullptr; - - /// Whether the hit path is wired up. All of it or none of it: a half-configured hit path would compute - /// some experts twice and others not at all, which is a wrong token rather than an error. - bool hits_ready() const { - return cache != nullptr && cache_base != nullptr && parts_out != nullptr && hit_out != nullptr && - mixed != nullptr && - hit_scratch != nullptr && x_q8_0_hit != nullptr && x_q8_0_hit_scale != nullptr && d_slot != nullptr && d_dst != nullptr; - } - - std::vector jobs; - strata::kernels::cpu::ActQ act; - /// Plan v0.3 P6 verify window: one quantized activation per token, the multi-token jobs, and the expert -> - /// job map (reset after every layer). - std::vector act_multi; - /// Plan v0.3 P6: a native pack's per-token activations (MAXT x kNativeActBytes). - std::vector nact_multi; - std::vector jobs_multi; - std::vector job_of; - /// Plan v0.3 P6: the verify window's GPU plan (VRAM hits + the PCIe share of the misses); `pcie_num`/256 of - /// each layer's distinct missed experts (the last ones in routing order) are read by the GPU over PCIe. - GpuPlanSink* plan = nullptr; - int pcie_num = 0; - int64_t pcie_experts = 0; ///< distinct experts the GPU read over PCIe in verify windows - /// #588: routed (token, expert) entries the GPU computed from outside its cache in verify windows: read over PCIe - /// (--pcie-frac, kind 1) or on another GPU (kind 2). In neither cache_hits nor cache_refused. - int64_t offload_entries = 0; - double ms_plan = 0, ms_actq = 0, ms_jobs = 0, ms_run = 0; ///< verify-window dispatch sections - /// Plan v0.3 P6: decayed routing counts per (layer, expert) during decode (sized by the caller; empty = off), - /// which the driver uses to swap the most-routed missing experts into the VRAM tier between rounds. - std::vector usage; - int64_t multi_misses = 0; ///< distinct (layer, expert) pairs the CPU computed in verify windows - int64_t multi_entries = 0; ///< routed (token, expert) entries the CPU served in verify windows - /// Multi-GPU: the second GPU's tier. Its experts are computed there instead of on the CPU (kind 2). - PeerExperts* peer = nullptr; - int64_t peer_entries = 0; ///< routed entries the peer served in verify windows - /// Set when `dispatch` could not produce an answer. The loop itself has no error channel, so this is - /// where a source failure surfaces: the driver checks it after `session_loop` returns rather than the - /// engine computing from a half-filled `parts`. - /// - /// **`failed` LATCHES AND `fail` IS ONLY THE MESSAGE.** Clearing the message must not re-arm the adapter: - /// a session that failed at layer 5 has already fed `moe_combine` whatever `parts` held, so every layer - /// after it is built on a hole - and resuming into a plausible-looking token is the exact outcome this - /// whole mechanism exists to prevent. `failed` is what the short-circuit reads. - bool failed = false; - const char* fail = nullptr; - int64_t fail_layer = -1; - int64_t fail_expert = -1; -}; - -/// `strata::core::PoolFn`, exactly. Silent on failure BY SIGNATURE - see `ExpertDispatch::fail`. -void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, const float* weights, int64_t n_embd, - int64_t k, float* out); - -/// Plan v0.3 P6: the pool for a verify window of `n_tok` tokens. `x_f` is (n_tok, n_embd), `ids` (n_tok, k) and -/// `out` (n_tok * k, n_embd). Each distinct missed expert is computed once for all the tokens routed to it; -/// resident experts' rows are zeroed (the GPU adds them). Requires `host_res` (the token-graph residency). -void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k, - float* out); - -/// **THE HITS, LAUNCHED AFTER THE MISSES ARE STAGED AND BEFORE `post[l]`.** Same shape as `PoolFn` and for the -/// same reason: `session_loop` owns the ORDER and this owns the work, so the loop needs to know nothing about -/// expert caches. Returns immediately when there are no hits, which is every layer until the cache is warm. -/// -/// It must run AFTER the host has copied the misses into `parts_dev` (it writes into the same buffer, on rows -/// the CPU zeroed) and BEFORE `post[l]` (which reads it). Both are stream-ordered on the loop's own stream. -void expert_hit_run(void* user, void* stream, HitPhase phase, const int32_t* ids, int64_t k); -/// The pool half of the same decision; see `ExpertDispatch::is_hit`. - -/// **PHASE 2'S ONLY SOURCE: `experts.bin`, memory-mapped, no cache.** -/// -/// `experts.bin` is 33,973,862,400 B and `BLOB` is 1,382,400, so it holds exactly `48 x 512 = 24,576` blobs and -/// the index is `layer * 512 + expert` with NO padding. A mapping is therefore the whole implementation: the -/// blob pointer is base plus a multiply, and the page fault that follows is the read. -/// -/// **AND THAT IS NOT AS SLOW AS IT SOUNDS, WHICH IS THE POINT.** The expert set is 34 GB and this machine has -/// 64 GB of DDR5, so a warm OS page cache holds ALL of it - the second token onward is a DRAM read at the -/// measured 44.14 GB/s, not a disk read. The first token's 663.6 MB comes off the disk and is the cold-path -/// number; `benches` should report the two separately rather than blending them. -/// -/// IT IS NOT AN LRU, AN LFU OR A PREFETCHER. Phase 3 replaces this object with those. Phase 2 is hit rate -/// `h = 0` on purpose, so that the CPU path and the host round trip are exercised on every layer of every -/// token - which is the only way they get debugged before speed matters. -class FileExpertSource : public ExpertSource { -public: - FileExpertSource() = default; - ~FileExpertSource() override; - FileExpertSource(const FileExpertSource&) = delete; - FileExpertSource& operator=(const FileExpertSource&) = delete; - - /// Maps `/experts.bin` and checks its size against the loaded expert layout. Canonical packs use - /// `n_layers * n_expert * BLOB`; native packs use their variable per-layer blob sizes and offsets. - /// - /// The size check is not a formality: a short file would fault at the END of a long sequence, and an - /// over-long one means the pack is not the one the geometry came from. Refuses with the two numbers. - /// - /// CS-T: a native pack WITHOUT experts.bin, after `set_gguf`, maps the model's GGUF shards instead (every file - /// native_experts.txt names, after `check_experts_gguf`), and assembles a blob from its three role slices when - /// it is asked for: the SSD tier, read in place through the OS file cache, with no 30-77 GB experts.bin copy. - /// With experts.bin present nothing changes. - bool open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err); - /// CS-T: the --native shard (native_experts.txt names the other files beside it); see `open`. - void set_gguf(const std::string& native) { gguf_ = native; } - /// Whether the experts are read from the GGUF shards in place (no experts.bin). - bool gguf_mode() const { return !role_ptr_.empty(); } - /// Pin a compact host mirror of experts absent from a fully filled static GPU cache. The mmap remains open - /// as a fallback for later cache reloads. This is opt-in because the complement may still be a large allocation. - /// - /// The resident RAM mode (`--resident-experts`, `--resident-cpu-experts`): - /// - `pin`: page-locked and mapped (`cudaHostAlloc`), so the prompt path copies it by DMA and the verify - /// window may read a share of the misses over PCIe; when the driver refuses, ordinary memory locked in the - /// working set instead. `pin = false` is ordinary pageable memory (the ROCm arm: large pinned allocations - /// can fail there, and it is what the HIP measurements used). - /// - `lend_from_slot` >= 0: the GPU-cache slots from there to the end are the prompt path's lend region; their - /// experts are kept in RAM too, from the last slot down, as far as `available RAM - headroom_bytes` allows - /// (a lent slot's expert is streamed during the prompt and copied back after it). - /// - the rest (the experts no slot holds) must fit that budget, or nothing is allocated and this returns false. - /// - /// CS-T, `budget_bytes` > 0 (`--resident-budget-gib`): only as many of those experts as fit `budget_bytes`, taken - /// in `rank` order (the expert profile: the hottest after the GPU cache's), are copied; the rest stay on the - /// mapped files (the SSD tier). No lend region then (a lent slot's expert is read from the files). - /// #467: `budget_bytes` = `kResidentWhatFits` is that path sized by the RAM alone (available minus the headroom - /// and the #403 margin) - the soft --resident-experts mode's second try when the whole complement does not fit; - /// false when not even one expert fits. On Windows the mapped experts leave the working set before any reading. - static constexpr uint64_t kResidentWhatFits = ~0ull; - bool pin_cache_complement( - const ExpertCache& cache, std::string& err, bool pin = true, - const std::vector>& additional_gpu_pairs = {}, int64_t lend_from_slot = -1, - uint64_t headroom_bytes = 8ull << 30, uint64_t budget_bytes = 0, - const std::vector>* rank = nullptr); - void close(); - - bool mapped() const { return base_ != nullptr; } - int64_t blobs() const { return blobs_; } - uint64_t pinned_bytes() const { return complement_pinned_ ? complement_pin_limit_ : 0; } - 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_; } - - // ---- the resident RAM mode and the adaptive tier. A swap puts `in` (held here) into a GPU slot and evicts - // `out` (held only by that slot). Before the slot is overwritten the caller copies it back into an exchange - // buffer and calls `stage_exchange`: `out` is then read from that buffer, and `in` still from here (the CPU - // computes both until the swap lands). Once the slot copy has landed, `commit_exchanges` moves `out` into - // `in`'s place, so the copy keeps holding exactly the experts the GPU does not - with no read of the file. - /// Whether the compact copy holds `(layer, expert)`. - bool has_resident(int64_t layer, int64_t expert) const; - /// Host room for `n` evicted blobs (page-locked when possible). Idempotent for the same or a smaller `n`. - bool reserve_exchanges(int64_t n, std::string& err); - int64_t exchange_capacity() const { return xstage_cap_; } - uint8_t* exchange_buffer(int64_t q) const; - /// Requires `has_resident(layer, in)`, `!has_resident(layer, out)` and `exchange_buffer(q)` holding out's blob. - bool stage_exchange(int64_t layer, int64_t in, int64_t out, int64_t q); - /// After the GPU copies of every staged swap have landed. Returns how many exchanges were applied. - int64_t commit_exchanges(); - int64_t exchanges() const { return exchanges_; } - /// With the compact copy ready: blobs read from the mapped file since (what the plain mmap mode may read from - /// the SSD). 0 in a steady resident mode; lend-region experts that did not fit the RAM count here. - int64_t file_reads() const { return file_reads_.load(std::memory_order_relaxed); } - /// CS-T per-tier counters: blobs served from the RAM copy, and the bytes read from the mapped files (the blobs - /// `file_reads` counts, plus the prompt path's copies of them). - int64_t ram_reads() const { return ram_reads_.load(std::memory_order_relaxed); } - uint64_t file_read_bytes() const { return file_read_bytes_.load(std::memory_order_relaxed); } - /// Of those, the bytes `blob` read (decode windows, adaptive swaps; the rest are the prompt path's copies), and - /// the time spent reading the files, summed over threads. - uint64_t file_blob_bytes() const { return file_blob_bytes_.load(std::memory_order_relaxed); } - double file_ms() const { return (double) file_us_.load(std::memory_order_relaxed) / 1000.0; } - /// Threads `prefetch` reads the GGUF with (STRATA_FETCH_THREADS, default 8). - void set_fetch_threads(int n) { fetch_threads_ = n < 1 ? 1 : n; } - /// #286 (Windows): read the experts straight from the drive (FILE_FLAG_NO_BUFFERING, overlapped) instead of - /// through the mapped files - the GGUF in place, or a pack's experts.bin - when the file cache could not keep them - /// beside `ram_bytes` (the RAM budget), cached now or not (their mapped pages would land in the working set); see - /// experts_unbuffered. The mapped reads' page faults are one small request each, and the pages they bring in - /// take the RAM the budget was sized for. `why` says what decided. - /// #577: `ram_bytes` counts up to every expert, and only the experts outside it are what the cache must keep. - bool set_unbuffered(uint64_t ram_bytes, std::string& why); - /// #577: the same decision once the RAM copy is built (pin_cache_complement), from the RAM it really holds and the - /// expert bytes outside it; switches either way (startup only, nothing reading). Returns whether unbuffered. - bool recheck_unbuffered(std::string& why); - bool unbuffered() const { return !direct_.empty(); } - /// Every expert's bytes (n_layers x n_expert blobs). - uint64_t expert_bytes() const; - /// #286, unbuffered: assembles the blobs of these pairs ahead of the `blob` calls that will ask for them (the - /// GPU cache's fill from the profile) - one batch of reads instead of one blob at a time. At most 64 pairs. - void prefetch_pairs(const std::pair* pairs, int64_t n); - - const uint8_t* blob(int64_t layer, int64_t expert) override; - bool pinned(int64_t layer, int64_t expert) const override; - const uint8_t* device_alias(int64_t layer, int64_t expert) const override; - bool pcie_layer(int64_t layer) const override; - bool transient(int64_t layer, int64_t expert) const override; - bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst) override; - /// CS-T: advances the assembled blobs' age (see staged_blob). - void begin_layer(int64_t layer, const int32_t* ids, int64_t k) override; - /// CS-T: the GGUF in place assembles the missed experts on `fetch_threads_` threads. - void prefetch(int64_t layer, const int64_t* experts, int64_t n) override; - /// CS-T: the GGUF in place asks the OS for the predicted experts' pages (PrefetchVirtualMemory on Windows, - /// madvise(WILLNEED) elsewhere), skipping the RAM copy's. - void warm(int64_t layer, const int64_t* experts, int64_t n) override; - /// Not when the reads are unbuffered: the warmed pages would be read through the file cache, a second time. - bool warms() const override { return !role_ptr_.empty() && direct_.empty(); } - /// Of the blobs the file tier read for the decode, how many had been warmed for their layer beforehand. - int64_t warmed_hits() const { return warm_hits_.load(std::memory_order_relaxed); } - int64_t warmed() const { return warm_count_.load(std::memory_order_relaxed); } - - /// Blobs touched, for the driver to report. With `h = 0` this is `48 * k` per token and the number is only - /// interesting once Phase 3 makes it not so. - int64_t reads() const override { return reads_; } - -private: - const uint8_t* mapped_blob(int64_t layer, int64_t expert) const; - /// The blob's bytes from the mapped file(s) - experts.bin, or the three GGUF role slices - into `dst`. - bool copy_from_files(int64_t layer, int64_t expert, uint8_t* dst) const; - bool open_gguf(std::string& err); - const uint8_t* staged_blob(int64_t layer, int64_t expert); - bool claim_stage(int64_t key, size_t& v, bool& fill); - bool fill_stage(size_t v, int64_t layer, int64_t expert, uint8_t* dst); - void publish_stage(size_t v, int64_t layer, bool ok, double us); - struct Fill { size_t v; int64_t layer, e; uint8_t* dst; }; - /// The claimed buffers' blobs: one overlapped batch when unbuffered, else the fetch threads' mapped copies. - void fill_many(const std::vector& todo); - /// #286: the blobs from the drive, unbuffered: every role's 4 KiB-aligned window is read at once (overlapped) - /// into this thread's aligned buffer, then copied into place. False when a read fails. - bool read_direct(const Fill* fills, size_t n) const; - bool open_direct(std::string& why); - std::vector paths_; ///< the mapped files, as maps_ - std::vector direct_; ///< #286: per file, an unbuffered overlapped handle (Windows) - std::vector role_file_; ///< 3 x n_layers: index into maps_ / direct_ - /// blobs assembled in the stage buffers (`blob` hands those out): the GGUF in place, or any unbuffered source - bool staged() const { return !role_ptr_.empty() || !direct_.empty(); } - static constexpr uint64_t kNoComplement = detail::kNoCacheComplement; - // ---- CS-T: the GGUF shards in place - std::string gguf_; - struct Map { - const uint8_t* base = nullptr; - uint64_t bytes = 0; -#if defined(_WIN32) - void* file = nullptr; - void* mapping = nullptr; -#else - int fd = -1; -#endif - }; - std::vector maps_; - std::vector role_ptr_; ///< 3 x n_layers: gate / up / down of the layer's expert 0 - std::vector role_bytes_; ///< 3 x n_layers: bytes per expert of that role - // the blobs assembled for `blob()`: a small pool of buffers, one per recent (layer, expert). A buffer is - // reused only once `kStageAge` layer changes have passed since its blob was last asked for, so a pointer holds - // through the layer it was asked in and the next ones (the pool computes a layer's misses before the next). - static constexpr uint64_t kStageAge = 3; - std::mutex stage_mu_; - std::vector> stage_buf_; - std::vector stage_key_; - std::vector stage_epoch_, stage_used_; - std::vector stage_busy_; ///< being filled (outside stage_mu_): never a victim - std::condition_variable stage_cv_; - int fetch_threads_ = 8; - std::atomic file_blob_bytes_{0}, file_us_{0}; - std::unique_ptr[]> warm_stamp_; ///< per (layer, expert): epoch_ + 1 when warmed - std::atomic warm_hits_{0}, warm_count_{0}; - std::unordered_map stage_of_; - uint64_t stage_blob_ = 0; - uint64_t stage_seq_ = 0; - uint64_t epoch_ = 0; - int64_t last_layer_ = -1; - bool stage_grew_ = false; - std::atomic ram_reads_{0}; - std::atomic file_read_bytes_{0}; - const uint8_t* base_ = nullptr; - int64_t blobs_ = 0; - int64_t n_layers_ = 0; - int64_t n_expert_ = 0; - uint64_t mapped_bytes_ = 0; - std::vector layer_offsets_, layer_blob_bytes_; - void* complement_arena_ = nullptr; - const uint8_t* complement_host_ = nullptr; - const uint8_t* complement_device_ = nullptr; - uint64_t complement_bytes_ = 0; - std::vector 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; - uint64_t complement_lock_off_ = 0; ///< the working-set lock covers [lock_off, lock_off + locked) - bool complement_ready_ = false; - uint64_t complement_locked_ = 0; ///< bytes held in the working set (pin refused) - int64_t complement_lent_slots_ = 0; - std::vector override_; ///< staged exchanges: an evicted expert read from its exchange buffer - struct Exchange { size_t in, out; int64_t q; uint64_t bytes; }; - std::vector staged_; - uint8_t* xstage_ = nullptr; ///< exchange buffers, `xstage_cap_ x xstage_blob_` - bool xstage_pinned_ = false; - int64_t xstage_cap_ = 0; - uint64_t xstage_blob_ = 0; - int64_t exchanges_ = 0; - std::atomic file_reads_{0}; - int64_t reads_ = 0; -#if defined(_WIN32) - void* file_ = nullptr; - void* mapping_ = nullptr; -#else - int fd_ = -1; -#endif -}; - -// ================================ THE RESIDENT ARENA (R2.1) ================================ -// -// **THE MMAP ABOVE IS THE REVIEW'S FINDING C1 AND IT IS WORTH 2.2x.** Read the comment on `FileExpertSource` -// about the page cache holding all 34 GB: that is true of the expert file ALONE, and it is not what this engine -// does. The PLE/n-gram shard is a 26.8 GB file that the engine also maps, so 34 GB of experts plus 26.8 GB of -// n-gram is 60.8 GB of mapped, file-backed pages on a 63 GB machine - and file-backed pages are exactly the ones -// the OS drops from the standby list when it wants memory. The expert stream then re-faults from disk. -// -// Measured, this round: the pool runs at **~19 GB/s in the engine against 42.8 GB/s in `bench/micro/cpu_s2.cpp` -// on the same machine, reading the same 34 GB**. The micro does `std::fread` into a heap arena and reads -// ordinary (anonymous, resident) memory; the engine reads `MapViewOfFile`. That is the whole difference, and it -// is why this class exists. -// -// It reads `experts.bin` into a `PinnedArena` once at startup, so the expert stream comes from anonymous memory -// the OS has no cheaper reason to evict. `PinnedArena` also tries `cudaHostRegister`, which the GPU needs for -// Phase 3's cache fills and the CPU/PCIe miss split - but registration is best-effort and reported, not assumed. -class ArenaExpertSource : public ExpertSource { -public: - ArenaExpertSource() = default; - ~ArenaExpertSource() override; - ArenaExpertSource(const ArenaExpertSource&) = delete; - ArenaExpertSource& operator=(const ArenaExpertSource&) = delete; - - /// Allocates and loads `/experts.bin`. Prints nothing; the caller reports `note()` and the load - /// rate, because those are the two numbers that say whether the arena is the one that was asked for. - bool open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int threads, std::string& err, - uint64_t max_pinned_bytes = 0, const std::string& shared_arena_file = {}); - /// Plan v0.3 P6: a native pack without experts.bin takes its experts from the model's GGUF: `native` is the - /// --native shard, and native_experts.txt names the other shards beside it (per layer, or per role in v4). - void set_gguf(const std::string& native) { gguf_ = native; } - void close(); - - bool mapped() const { return base_ != nullptr; } - int64_t blobs() const { return blobs_; } - const uint8_t* blob(int64_t layer, int64_t expert) override; - int64_t reads() const { return reads_; } - bool pinned(int64_t layer, int64_t expert) const override; - const uint8_t* device_alias(int64_t layer, int64_t expert) const override; - void prefetch(int64_t layer, int64_t expert) override; - uint64_t release(int64_t layer, int64_t expert) override; - - /// What backing was obtained and why, for the startup print. "The engine adapts to the machine it is on" is - /// only true if the engine says what it got. - const std::string& note() const { return note_; } - /// #633: set by `open` when the RAM available is less than the arena needs (a recommendation; it still loads) - const std::string& ram_warning() const { return ram_warning_; } - double load_gib_per_second() const { return gib_per_s_; } - // Loader fix: the load, split. `load_seconds()` is the wall clock of the load loop; the other two are - // sums over the reader threads (see LoadStats), so on their own they say how much of that wall was spent - // waiting for the disk and how much in memcpy + FNV-1a. - double load_seconds() const { return load_seconds_; } - double load_read_seconds() const { return load_read_s_; } - double load_copy_seconds() const { return load_copy_s_; } - -private: - void* arena_ = nullptr; ///< the PinnedArena, owned - void* map_ = nullptr; ///< STRATA_ARENA_MMAP: the arena file, mapped read-only (not the PinnedArena) - uint64_t map_bytes_ = 0; - std::vector dev_slice_; ///< device alias of each registered slice (or of the whole range) - uint64_t slice_bytes_ = 0; - const uint8_t* base_ = nullptr; - int64_t blobs_ = 0; - int64_t n_expert_ = 0; - int64_t reads_ = 0; - std::string note_; - std::string ram_warning_; - double gib_per_s_ = 0.0; - double load_seconds_ = 0.0; - double load_read_s_ = 0.0; - double load_copy_s_ = 0.0; - uint64_t pinned_bytes_ = 0; - std::string gguf_; -}; - -/// Plan v0.3 P6: checks native_experts.txt's GGUF spans against the files, before anything is read: each layer's -/// gate/up/down at its recorded (file, offset) must be that tensor (`blk.L.ffn__exps.weight`), of the -/// layout's type and dimensions, and inside the file. `native` is the --native shard (see set_gguf). -bool check_experts_gguf(const std::string& native, const strata::kernels::cpu::ExpertLayout& lay, std::string& err); -/// Fills `dst` (lay.total bytes, the experts.bin layout) from the GGUF files, one role at a time. -/// `unbuffered`: each chunk read past the file cache (Windows). -LoadStats load_experts_gguf(const std::string& native, uint8_t* dst, const strata::kernels::cpu::ExpertLayout& lay, - int threads, bool unbuffered = false); - -} // namespace strata::core diff --git a/include/strata/core/graph.hpp b/include/strata/core/graph.hpp deleted file mode 100644 index 369bfe3..0000000 --- a/include/strata/core/graph.hpp +++ /dev/null @@ -1,117 +0,0 @@ -// include/strata/core/graph.hpp - P2.S5: the GraphRegistry. -// -// `GraphRegistry`: capture/replay wrappers keyed by `(layer_type, n_tokens)`, with static input/output -// buffers at fixed addresses. -// -// THREE THINGS ARE BAKED INTO THIS INTERFACE, and each one is a measurement rather than a preference. All -// three come from `bench/micro/graph_capture.cu`, which was written to answer the phase's own instruction - -// "verify on the installed CUDA version with a minimal test before building on it". -// -// 1. **THE WAIT MUST POLL THE DRIVER, NOT MEMORY.** The phase's host loop says "spin on -// doorbell_seq == expected ... no cudaStreamSynchronize anywhere". A spin that only reads memory NEVER -// RUNS THE KERNEL: 5,907,703 spins over 500 ms, and the datum flips to 1 the instant anything calls into -// the driver and never before. On Windows the display driver model BATCHES command submission, and a -// thread that only reads memory gives it no reason to flush. Hence `wait_ms`, which polls an event - -// a QUERY and not a blocking sync, so P2.X3's "zero synchronization calls in the layer loop" still holds, -// and it costs 0.021 ms. -// -// 2. **A GRAPH RE-READS ITS INPUT BUFFERS AT REPLAY, BUT NOT ITS KERNEL ARGUMENTS.** Verified: eight -// replays with a different pinned input each time all tracked correctly, so the data path is live; but a -// kernel argument is copied into the node at capture and is never re-read. **Anything that changes per -// step - a position, a page-table base, a token id - must be DATA in a device buffer, never an argument.** -// This is the phase's "graph capture with pointers that change between steps silently replays stale -// addresses" hazard, and it now has a measurement behind it. -// -// 3. **FIXED ADDRESSES ARE THE CALLER'S OBLIGATION.** The registry cannot check them. Every buffer a -// captured body touches must be allocated before `record` and never reallocated; the registry holds the -// graph, not the memory. -// -// What the registry is FOR: a layer's ops are the same every token, so recording them once and replaying -// removes the per-call host cost of submitting them individually. Measured, that cost is 10-22 us PER CALL -// into the driver on this machine, and a layer with 8 submissions is ~0.1 ms of round trip. -#pragma once - -#include -#include -#include -#include -#include -#include - -#include - -namespace strata::core { - -/// The two attention families. `docs/semantics.md`: 36 GDN layers and 12 QSA, at indices 3, 7, ... 47. -enum class LayerType : int { GDN = 0, QSA = 1 }; -inline const char* to_string(LayerType t) { return t == LayerType::GDN ? "GDN" : "QSA"; } - -/// One recorded graph. Move-only: it owns a `cudaGraphExec_t` and an event, and two owners would -/// double-destroy. -class CapturedGraph { -public: - CapturedGraph() = default; - ~CapturedGraph() { reset(); } - CapturedGraph(const CapturedGraph&) = delete; - CapturedGraph& operator=(const CapturedGraph&) = delete; - CapturedGraph(CapturedGraph&& o) noexcept { *this = std::move(o); } - CapturedGraph& operator=(CapturedGraph&& o) noexcept; - - /// Start recording everything the caller launches into `stream`. - bool begin(void* stream, std::string& err); - - /// Stop recording, instantiate, and record the completion event. A capture that produced ZERO nodes is - /// reported as an error: it means the body did nothing, which is a wiring mistake and NOT an empty graph - /// to be replayed happily forever. - bool end(void* stream, std::string& err); - - /// Replay. Does not synchronise. - bool launch(void* stream, std::string& err) const; - - /// The host loop's wait: poll `done_` until it completes or `timeout_ms` elapses. Returns false on - /// timeout, which the caller must treat as a hang and not as "probably fine". See NOTE 1 above for why - /// this exists instead of a memory spin. - bool wait_ms(int timeout_ms) const; - - size_t nodes() const { return nodes_; } - bool valid() const { return exec_ != nullptr; } - -private: - void reset(); - cudaGraph_t graph_ = nullptr; - cudaGraphExec_t exec_ = nullptr; - cudaEvent_t done_ = nullptr; - size_t nodes_ = 0; -}; - -/// Capture-once, replay-many, keyed by `(layer_type, n_tokens)`. -/// -/// `record` is given a CALLABLE that launches the layer's ops. On the first call for a key it captures; -/// afterwards it returns the cached graph and does NOT run the callable - so a caller that mutates state -/// inside the body will be surprised, which is why the body must only launch. -class GraphRegistry { -public: - explicit GraphRegistry(void* stream) : stream_(stream) {} - - /// Capture `body` for `key` if it is not already recorded. Returns false and fills `err` on failure. - /// Recording the same key twice is a no-op and is NOT an error - that is the point of a registry, and a - /// regression test asserts that the body runs exactly once across many calls. - bool record(LayerType type, int n_tokens, const std::function& body, std::string& err); - - const CapturedGraph* find(LayerType type, int n_tokens) const; - - /// Launch and wait, in that order, the two things the host loop does per layer. - bool launch(LayerType type, int n_tokens, int timeout_ms, std::string& err) const; - - size_t size() const { return graphs_.size(); } - /// How many times a BODY was actually captured. With a working cache this equals `size()`. - size_t captures() const { return captures_; } - -private: - using Key = std::pair; - void* stream_ = nullptr; - std::map graphs_; - size_t captures_ = 0; -}; - -} // namespace strata::core diff --git a/include/strata/core/hit_hook.hpp b/include/strata/core/hit_hook.hpp deleted file mode 100644 index 8c21035..0000000 --- a/include/strata/core/hit_hook.hpp +++ /dev/null @@ -1,41 +0,0 @@ -// include/strata/core/hit_hook.hpp - R4.2c: the seam between the host loop and the VRAM expert tier. -// -// **IT IS ITS OWN HEADER BECAUSE BOTH SIDES NEED IT AND NEITHER SHOULD OWN IT.** `session.hpp` declares the -// loop that calls the hook; `expert_source.hpp` declares the implementation that answers it. Putting the type -// in either one makes the other include a header it has no other use for, and the loop knowing what an expert -// cache is (or the adapter knowing what a graph is) is exactly the coupling this seam exists to avoid. -#pragma once - -#include - -namespace strata::core { - -/// **TWO PHASES, AND THE SPLIT IS THE WHOLE POINT.** `Launch` runs BEFORE the CPU pool and `Combine` runs -/// AFTER the misses have been copied into `parts`. That ordering is what lets the GPU's resident experts run -/// at the same time as the CPU's misses instead of after them: -/// -/// ring -> hits(Launch) [GPU: quantize + grouped experts into `hit_out`] -/// -> pool() [CPU: the misses, CONCURRENT with the GPU] -/// -> H2D misses into `parts` -/// -> hits(Combine) [GPU: parts += hit_out] -/// -> post[l] -/// -/// **MEASURED, AND WHY IT IS NOT THE OBVIOUS ORDER.** The first version called the hit path once, after the -/// pool, writing straight into `parts`. The drain duly fell **18.2 -> 10.2 ms** - the CPU really was doing -/// half the experts - and **the token did not move at all**, because the GPU's half had simply been moved onto -/// the critical path behind the CPU's instead of beside it. A second buffer and one `add_inplace` buy the -/// overlap back. -enum class HitPhase { Launch, Combine }; - -/// `ids` AND `k` ARE THE ROUTER'S OWN OUTPUT, AND THEY ARE WHY THIS HOOK TAKES ARGUMENTS AT ALL. -/// -/// The first version took only `(user, stream, phase)` and left the hit/miss decision inside the pool -/// callback - which runs AFTER `Launch`. So `Launch` read the hit list from the PREVIOUS layer and computed -/// the previous layer's experts into the current layer's rows. It produced a token, the timings looked -/// plausible, and **C1 moved from mean KL 9.69e-02 to 1.03e+00 and top-1 from 0.867 to 0.333.** The decision -/// has to happen in `Launch`, on the ids the doorbell published for THIS layer, and the pool then consumes it. -/// -/// A null `HitFn` means "no VRAM tier" - the default, and what every caller had before R4. -using HitFn = void (*)(void* user, void* stream, HitPhase phase, const int32_t* ids, int64_t k); - -} // namespace strata::core diff --git a/include/strata/core/layer.hpp b/include/strata/core/layer.hpp deleted file mode 100644 index 575c908..0000000 --- a/include/strata/core/layer.hpp +++ /dev/null @@ -1,658 +0,0 @@ -// include/strata/core/layer.hpp - one GDN LAYER, composed. P2.S5's mixer. -// -// This is the first place in the engine where the kernels are COMPOSED rather than tested individually, so -// the thing it has to get right is the ORDER and the buffers, not the arithmetic. Every kernel it calls is -// parity-tested on its own; what can go wrong here is a buffer sized for the wrong shape, a step done in the -// wrong order, or a value that should have been converted and was not. -// -// `ref/gdn.py::gdn_decode` is the specification, and the order below is its docstring verbatim: -// -// qkv = wqkv @ x (10240 = q|k|v, each a contiguous run of 128-wide heads) -// conv -> SiLU (SiLU is applied to the WHOLE conv output before the split) -// q,k = l2_norm (v is NOT normalised) -// beta = sigmoid(wbeta @ x) -// gate = softplus(walpha @ x + dt) * ssm_a -// recurrent step -// y = rms_norm(o, ssm_norm) * sigmoid(z) <- SIGMOID for qwen4exp; qwen3.5 used SiLU -// out = ssm_out @ y -// -// FOUR THINGS IN THAT ORDER ARE EASY TO READ PAST, and each produces a plausible number: -// -// * **SiLU is applied BEFORE the split**, to the whole 10240-wide conv output. Applying it only to q and -// k, or after the reshape, is the same arithmetic on different data. -// * **v is NOT normalised.** `l2_norm` applies to q and k only - two rows of 16 heads, not the 48 of v. -// * **the `/hc`-style scale on q is `1/sqrt(S)`**, applied by the CALLER because `ref/gdn.py` says the two -// llama.cpp paths apply it in different places. It goes on AFTER the norm. -// * **the state is transposed** relative to the reference: (S, h_v, S) here, (S, S, h_v) there. That is -// `gdn.hpp`'s choice and it is the reason `gdn_step`'s arguments are laid out as they are. -// -// THE ACTIVATIONS FOLLOW THE CONTRACT, which is why three different GEMVs appear below: `attn_qkv`, -// `attn_gate` and `ssm_out` are K-quants (Q8_K), while `ssm_alpha` and `ssm_beta` are BF16 (bf16). Using one -// activation format for all five would be a 0.66-1.41% error on the three that matter - measured, in -// `s_gemv_q8k_parity` and `bf16_gemv_parity`. -#pragma once - -#include "strata/core/layout.hpp" -#include "strata/core/weights.hpp" - -#include "strata/kernels/gr.hpp" -#include "strata/kernels/kv_stream.hpp" -#include "strata/kernels/ngram.hpp" -#include "strata/kernels/ple.hpp" - -#include -#include -#include -#include - -namespace strata::core { - -/// Select pinned CUDA BF16/F32 projections for SSM gates, routing and the sparse indexer. -/// Configure before session capture; captured graphs retain the selected implementation. -/// Does not change GR, PLE or the shared expert's scalar gate. -void layer_set_native_bf16(bool enabled); -// Diagnostic vector-attention adapter; configure before capture, context <=256. -void layer_set_native_flash_attn_short(bool enabled); - -/// Every buffer one GDN layer needs, carved from an arena ONCE. Sizes are functions of `ModelGeometry`, and -/// `gdn_buffers_bytes` returns the total so a caller can size the arena before committing. -struct GdnBuffers { - // the activation, in the formats the contract asks for. BOTH quantized images are produced for every - // layer, because WHICH ONE A WEIGHT WANTS IS A PROPERTY OF THE WEIGHT and the pack mixes them by layer - - // `attn_qkv` alone is IQ4_XS on 13 layers, Q3_K on 18, Q4_K on 4 and S2 on 1. - uint8_t* x_q8k = nullptr; ///< n_embd, block_q8_K - uint8_t* x_q8_0 = nullptr; ///< n_embd, block_q8_0 - uint16_t* x_bf16 = nullptr; ///< n_embd, bf16 bits - - // the qkv path - float* qkv = nullptr; ///< conv_channels - float* conv_out = nullptr; ///< conv_channels - float* h = nullptr; ///< conv_channels = silu(conv_out), and it IS q|k|v in place - - // the per-head scalars and the recurrence - float* alpha = nullptr; ///< h_v - float* beta = nullptr; ///< h_v - float* gate = nullptr; ///< h_v - float* o = nullptr; ///< h_v * S - float* z = nullptr; ///< value_dim - float* y = nullptr; ///< value_dim - uint8_t* y_q8k = nullptr; ///< value_dim, block_q8_K - uint8_t* y_q8_0 = nullptr; ///< value_dim, block_q8_0 - - // the recurrent state, which outlives the call - float* state = nullptr; ///< S * h_v * S - float* conv_state = nullptr; ///< conv_channels * (d_conv-1) -}; - -/// Bytes needed for `b`, 16-byte aligned between regions. -uint64_t gdn_buffers_bytes(const ModelGeometry& g); -/// Carves `base` (which must be DEVICE memory) into `b`. Returns the bytes used. -uint64_t gdn_buffers_init(const ModelGeometry& g, void* base, GdnBuffers& b); -/// Zeroes the recurrent and conv state, so a fresh sequence starts from the reference's own `zeros()`. -void gdn_buffers_zero_state(const GdnBuffers& b, const ModelGeometry& g, void* stream); - -/// `Mixed` (n_embd f32) through one GDN layer to `out` (n_embd f32). `state` and `conv_state` are updated. -/// -/// `layer` selects the weights; `tables` must outlive the call. Returns false and fills `err` if a tensor is -/// missing - which is a wiring mistake here rather than a shape problem, because `check_layer` already -/// asserted the shapes at load time. -bool gdn_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, const GdnBuffers& b, - const float* mixed, float* out, void* stream, std::string& err); - -// ================================ the MoE block ================================ - -struct Doorbell; // defined with the rest of the handoff, below; only a pointer is needed here - -/// Buffers for the MoE block, on EVERY layer. -struct MoEBuffers { - uint16_t* x_bf16 = nullptr; ///< n_embd, for the ROUTER's weight, which is BF16 - uint16_t* x_f16 = nullptr; ///< n_embd, for the SHARED EXPERT's weights (see the note in `moe_layer`) - float* logits = nullptr; ///< n_expert - int* ids = nullptr; ///< k - float* weights = nullptr; ///< k - float* shared = nullptr; ///< n_embd - float* sh_scratch = nullptr; ///< shared_expert_scratch_bytes(n_ff): the shared expert's own scratch - uint8_t* x_q8_0 = nullptr; ///< n_embd, block_q8_0 - the shared expert's weights want Q8_0 on the layers - ///< whose types are Q2_0/Q4_0/Q5_0/Q8_0/IQ4_NL, which is most of them - uint8_t* x_q8k = nullptr; ///< n_embd, block_q8_K - and Q8_K on the K-quant ones -}; - -uint64_t moe_buffers_bytes(const ModelGeometry& g, int64_t k); -uint64_t moe_buffers_init(const ModelGeometry& g, int64_t k, void* base, MoEBuffers& b); - -/// The MoE block: router -> (the caller's expert outputs) -> combine. -/// -/// `parts` is (k, n_embd) device f32 and is **filled by the CALLER** - by the CPU pool and the VRAM-resident -/// experts. That split is the architecture's, not a shortcut: the routed experts are the only part of the -/// model that does not fit in VRAM, and every design decision in this engine exists to keep them out of the -/// graph. This function therefore owns the two ends - which experts, and how their outputs are combined - -/// and deliberately not the middle. -/// -/// TWO ACTIVATION FORMATS AGAIN, and the router's is the one that matters most: -/// -/// * `ffn_gate_inp.weight` is BF16, so the router sees a BF16 activation. `ref/moe.py` L88-92 calls this -/// "the highest-consequence rounding in the model": the logits were measured **8.100e-03** off without it, -/// which is enough to FLIP a top-10 selection - and a flipped selection is not a small numeric error, it -/// is a different expert reading a different weight. -/// * the shared expert's weights are Q3_K/IQ4_XS/Q5_0 IQ-quants whose contract is Q8_K, which -/// `shared_expert` does not implement; it takes fp16. That is the known gap its own header documents and -/// `docs/activation-contract.md` names as outstanding. -bool moe_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, - const float* x, const float* parts, float* out, void* stream, std::string& err, - const Doorbell* db = nullptr); - -// ================================ THE MOE, SPLIT AT THE ROUTER ================================ -// -// **THE SPLIT EXISTS BECAUSE THE ONE-LAYER DELAY WAS NOT A TIMING CHANGE.** `moe_layer` is -// `route -> publish -> shared expert -> combine`, and `combine` multiplies `parts` by THIS layer's -// `b.weights`. So `parts` must be THIS layer's expert outputs. A host loop that hands layer `l`'s pool -// result to layer `l+1` computes `sum_j w_{l+1}[j] * expert_{ids_l,j}(x_l)` while the model is -// `sum_j w_l[j] * expert_{ids_l,j}(x_l)` - **both the expert selection and the input one layer stale while the -// weights are current** - and `session.hpp` states the contract it violates: the doorbell is "a change to WHEN -// the host runs, not to what this function computes". -// -// The one-layer delay was introduced for a real reason - it is the only way to overlap a CPU pool with a GPU -// that has already queued the combine - and the fix is to split the GRAPH, not to delay the answer: -// -// block_layer_pre[l] attn -> mixer -> gr_write -> ffn gr_read -> moe_route [rings the doorbell] -// ... the host runs the pool here, on the ids `moe_route` just published ... -// block_layer_post[l] moe_finish -> gr_write -// -// `post[l]` is launched AFTER the pool returns, so it sees layer `l`'s experts with layer `l`'s weights, and it -// is still a captured graph. What it costs is the overlap: the window is now whatever GPU work follows the -// ring inside `pre[l]` - the shared expert and nothing else, because everything after the combine depends on -// `parts`. **A per-layer CPU pool cannot be hidden behind a strictly serial residual chain**, which is why -// Phase 3's VRAM expert cache is the answer to the CPU term and the doorbell is not. - -/// The routing half: bf16 activation, the router GEMV, top-k, and the doorbell publish. Ends with the ring -/// rung, so a host that sees it knows `h_x_f`/`h_ids`/`h_weights` are in place. -bool moe_route(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, - const float* x, void* stream, std::string& err, const Doorbell* db = nullptr); -/// The verify window's n tokens routed at once (see layer.cpp); bitwise per token what `moe_route` gives. -bool moe_route_window(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, - const float* x, float* logits, int32_t* ids, float* weights, int n, void* stream, std::string& err); - -/// The finishing half: the shared expert and the combination. -/// -/// **`parts` MUST BE THE EXPERTS THIS LAYER'S OWN ROUTER SELECTED.** It is combined with `b.weights`, which -/// `moe_route` wrote for THIS layer. Passing the previous layer's vectors is the L100 bug: it produces a -/// finite, fluent, deterministic token that is not the model's. -bool moe_finish(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, - const float* x, const float* parts, float* out, void* stream, std::string& err); - -/// Plan v0.3 P3: the two parts of `moe_finish` separately. `moe_shared` computes the shared expert into -/// `b.shared` and needs only `x`; `moe_combine_parts` combines `parts` with `b.weights` and `b.shared`. -/// `moe_finish` is exactly `moe_shared` followed by `moe_combine_parts`. -bool moe_shared(const WeightTable& tables, const ModelGeometry& g, int64_t layer, const MoEBuffers& b, - const float* x, void* stream, std::string& err); -bool moe_combine_parts(const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, const float* parts, - float* out, void* stream, std::string& err); - -/// Plan v0.3 P3 (default ON): the shared expert runs at the END OF `pre[l]`, after the doorbell has rung, so -/// the GPU computes it while the host runs the CPU pool; `post[l]` then only combines. Same kernels on the -/// same inputs in the same stream order relative to their consumers, so the result is bitwise unchanged. -/// Must be set before capture. `false` restores the shared expert inside `post[l]` (A/B arm). -void layer_set_shared_early(bool enabled); -bool layer_shared_early(); - -// ================================ the QSA mixer ================================ - -/// THE PERSISTENT STATE OF ONE QSA LAYER FOR ONE SEQUENCE: the KV cache, the indexer's pooled keys, the rope -/// tables, and the per-token step buffer. None of it is scratch - it survives every token. -/// -/// `max_cells` is the sequence capacity the arena was sized for, and it fixes the rope table's length: a table -/// shorter than the sequence would have `rope_neox_apply` read past it, which is a wrong rotation rather than a -/// fault. -struct QsaState { - uint16_t* k_pool = nullptr; ///< [page][kv_head][page_size][head_dim] fp16 (null in INT8 mode) - uint16_t* v_pool = nullptr; - /// Plan v0.3 P7: INT8 KV (qsa_set_kv_int8). Codes [page][kv_head][page_size][head_dim], one FP16 scale per 64. - bool kv_int8 = false; - int8_t* k_q = nullptr; - int8_t* v_q = nullptr; - uint16_t* k_scale = nullptr; - uint16_t* v_scale = nullptr; - /// PR #21: Q4_0 KV with Walsh-Hadamard rotation (qsa_set_kv_q4, kv_q4.hpp): 144 B per cell and head - bool kv_q4 = false; - uint8_t* k_q4 = nullptr; - uint8_t* v_q4 = nullptr; - /// Hybrid K8V4: K in INT8 (unrotated - the scores stay exact), V in rotated Q4_0 (kv_q4.hpp): 816 B per cell. - /// Uses k_q/k_scale + v_q4. Mode 0 only (no KV streaming, no ring); under this setting the MTP drafter's - /// ring state stays plain INT8, so the block movers never see the hybrid layout. - bool kv_hybrid = false; - /// K and V go through kv_q4.hpp's Walsh-Hadamard rotation before they are stored, the queries too, the output - /// back: always for Q4_0, for INT8 by qsa_set_kv_int8_rotate (spreads outlier channels over the scale groups) - bool kv_rot = false; - int32_t* page_table = nullptr; ///< (n_pages,) logical page -> physical page (-1: not resident, streamed) - int64_t n_pages = 0; - int64_t max_cells = 0; - - /// KV STREAMING (docs/kv-streaming-design.md, `kv_stream.hpp`). `kv_mode` 0: every page in VRAM, identity - /// table (n_slots == n_pages, no host copy). 1: streamed - the authoritative K/V in `host`, `n_slots` pages - /// in VRAM, `map` resolves the selection's blocks on device. 2: a ring (the MTP drafter's window) - `n_slots` - /// pages at `block % n_slots`, with the host copy for a resume. The pool pointers above point at the slots. - int kv_mode = 0; - int64_t n_slots = 0; - strata::kernels::KvHostPools host; - strata::kernels::KvStreamMap map; - int64_t idx_pooled_rows = 0; ///< rows of `idx_pooled` (a ring, which has no indexer, keeps 2) - - float* idx_tail = nullptr; ///< (idx_block - 1, idx_dim): the raw tail of the block being filled - float* idx_dead = nullptr; ///< (idx_dim,): the spare slot's key, CONSTANT for the sequence - float* idx_pooled = nullptr; ///< (max_cells/idx_block + 2, idx_dim) - int32_t* idx_block_pos = nullptr; - - float* cos_tab = nullptr; ///< (max_cells, n_rot/2), built on the HOST in float64 - bool owns_rope = false; ///< built the table above (not borrowed with share_rope): it releases it - float* sin_tab = nullptr; - - /// THE PER-TOKEN COUNTS, IN DEVICE MEMORY - the whole reason this layer can be a graph. `qsa_step_fill` - /// computes all four from the position, so one H2D per token updates every count every kernel needs. - int32_t* step = nullptr; - int32_t* attention_status = nullptr; ///< per-layer device status, captured D2H to host_step[kStepCount] - /// The rope positions, (n_head,) int32, all equal to the current position. `rope_neox_apply` reads its - /// positions from the DEVICE, so a host scalar here would be an illegal access (and uncapturable). - int32_t* pos_dev = nullptr; - - /// PINNED HOST STAGING AT FIXED ADDRESSES, and they are not an optimisation. The uploads in `qsa_layer` - /// copy FROM these, so a CUDA graph captures the SOURCE POINTER - and the first version of the layer filled - /// a stack array and a local `std::vector` instead. Those addresses are dead by the time the graph is - /// replayed, which is this project's own recorded pitfall ("graph inputs live at fixed addresses") walked - /// straight into: the replay would read whatever the stack held, and the step counts would be wrong in a way - /// that looks like a working token. - /// - /// Pinned as well as fixed, because a pageable source would make `cudaMemcpyAsync` a synchronous staged - /// copy and give back the overlap the doorbell protocol exists for. - int32_t* host_step = nullptr; ///< (kStepCount + 1,) pinned; final element is attention status - int32_t* host_pos = nullptr; ///< (n_head,) pinned -}; - -/// Plan v0.3 P7: the RoPE cos/sin table (max_cells x n_rot/2 x 2 floats, 64 MiB at 262K) is identical in every -/// QSA layer. `with_rope = false` sizes a state that borrows it; `share_rope` points `st` at another state's table -/// instead of building a copy (the session builds it once, in the first QSA layer). -uint64_t qsa_state_bytes(const ModelGeometry& g, int64_t max_cells, bool with_rope = true, int64_t ring_cells = 0); -/// KV streaming: keep `cells` cells of each QSA layer in VRAM and the rest in pinned host memory (0: all in VRAM, -/// the default). Set before sizing and initializing the session; a context that fits in `cells` is not streamed. -/// Also puts the MTP drafter's K/V in a ring of its window (`ring_cells` of qsa_state_bytes/init; -1 forces a fully -/// 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(); -/// Pinned host bytes the streamed states hold (their host copies). -uint64_t qsa_kv_host_bytes(); -/// Plan v0.3 P7: store K/V as INT8 with FP16 scales per 64 values (half the VRAM of FP16). Set before sizing and -/// initializing the session; default off until gate G-C accepts it. -void qsa_set_kv_int8(bool enabled); -/// INT8 K/V through the Hadamard rotation (off by default: STRATA_KV_ROT=1) -void qsa_set_kv_int8_rotate(bool enabled); -bool qsa_kv_int8(); -/// PR #21: store K/V as Q4_0 after a Hadamard rotation (`--kv q4_0`): 576 B per cell, vs 1,056 in INT8. -void qsa_set_kv_q4(bool enabled); -bool qsa_kv_q4(); -/// Hybrid K8V4 (`--kv k8v4`): K in INT8, V in rotated Q4_0 - 816 B per cell. Not with --kv-resident. -void qsa_set_kv_hybrid(bool enabled); -bool qsa_kv_hybrid(); -/// The state's KV format for the block-moving functions of kv_stream.hpp (kKvF16 / kKvInt8 / kKvQ4). -inline int qsa_kv_format(const QsaState& st) { - // A hybrid K8V4 state is mode 0 only and never reaches the block movers; refuse rather than let it - // fall through to kKvF16 - a wrong layout silently applied is worse than a hard stop (PR review). - if (st.kv_hybrid) { - std::fprintf(stderr, "strata: qsa_kv_format: a hybrid K8V4 state must never reach the block movers\n"); - std::exit(1); // the kernels' own "unsupported geometry" convention (kv_q8.cu, qsa_decode_attn.cu) - } - return st.kv_q4 ? strata::kernels::kKvQ4 : st.kv_int8 ? strata::kernels::kKvInt8 : strata::kernels::kKvF16; -} -uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaState& st, - const QsaState* share_rope = nullptr, int64_t ring_cells = 0); -/// KV streaming: the pools a reader sees (the VRAM slots) and, when streamed, make the selection's blocks resident. -strata::kernels::QsaAttnPools qsa_attn_pools(const QsaState& st); -void qsa_kv_resolve(const QsaState& st, const ModelGeometry& g, const int32_t* ids, const int32_t* steps, int64_t n_q, - int64_t cap, void* stream); -/// Zeroes the pools AND the indexer, so a fresh sequence matches the reference's own `zeros()`. The KV pool -/// matters even for cells that are never attended, because `kv_gather` reads whatever the selection names. -void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream); - -// ================================ PER-STAGE TIMING, DEBUG ONLY ================================ -// -// Event pairs around the pieces of `block_layer_pre`/`_post`, recorded per (layer, stage) and read once at the -// end so that **NOTHING IS SYNCHRONISED DURING THE RUN** - a per-stage sync would serialise the pipeline and -// report the serialised time. **CAPTURED GRAPHS CANNOT USE IT**: an event record inside a stream capture is -// silently dropped, so this is for the `--no-capture` path only. -// -// It exists because the engine spends ~1.047 ms per layer with the experts off while every cost model in -// `bench/` predicts less than half that, and the gap has to be attributed before it can be attacked. -// slot 0 gr_read(attn) 1 the attention block 2 gr_write(attn) 3 gr_read(ffn) 4 router -// slot 5 moe_finish 6 gr_write(ffn) -bool stage_timing_enable(); -void stage_timing_name(int slot, const char* name); -void stage_timing_report(int64_t n_layers); -/// The same event pairs, reachable from `session.cpp`, for marks that sit OUTSIDE the captured graphs - the -/// two `cudaGraphLaunch` calls per layer. Those are ordinary stream operations, so an event around them is -/// legal and is not captured, which is what lets the captured path's 1.047 ms/layer be split into the two -/// graphs' execution and the gap the host spends between them. Slots 16 and 17 are reserved for it; slots -/// 0-15 are the in-layer marks and are only meaningful with `--no-capture`. -void stage_mark_begin(int64_t layer, int slot, void* stream); -void stage_mark_end(int64_t layer, int slot, void* stream); - -/// Scratch for one QSA layer. Every buffer here is overwritten by every token. -struct QsaBuffers { - uint8_t* x_q8_0 = nullptr; ///< n_embd, block_q8_0 - `attn_q` is Q2_0, whose vec_dot_type is Q8_0 - uint8_t* x_q8k = nullptr; ///< n_embd, block_q8_K - the three K-quant projections - uint16_t* x_bf16 = nullptr; ///< n_embd - the two BF16 indexer projections - float* q_full = nullptr; ///< n_head * 2 * head_dim: the raw `attn_q` output, q | gate per head - float* qcur = nullptr; ///< n_head * head_dim: the FIRST half of each head, contiguously - float* kcur = nullptr; ///< n_head_kv * head_dim - float* vcur = nullptr; ///< n_head_kv * head_dim - float* idx_raw = nullptr; ///< idx_key_dim: NEVER normed and NEVER rotated - float* q_idx = nullptr; ///< idx_q_heads * idx_key_dim - float* cell_scores = nullptr; ///< max_cells - int32_t* ids = nullptr; ///< cap = qsa_selection_width(kTopkMaxCells, s) - uint16_t* k_scratch = nullptr; ///< cap * n_head_kv * head_dim - uint16_t* v_scratch = nullptr; - float* attn = nullptr; ///< n_head * head_dim - uint16_t* attn16 = nullptr; ///< n_head * head_dim, for a fp16-activation consumer - /// `attn * sigmoid(gate)` in f32 and then in Q8_K - what `attn_output` ACTUALLY wants. Its weights are - /// Q4_K/Q5_K/Q6_K, whose `vec_dot_type` is Q8_K, and the fp16 path is worth 0.66-1.41% against the - /// reference. `docs/activation-contract.md`. - float* attn32 = nullptr; - uint8_t* attn_q8k = nullptr; - float* attn_scratch = nullptr; ///< plan v0.3 P3: split-K decode attention partials -}; - -uint64_t qsa_buffers_bytes(const ModelGeometry& g, int64_t max_cells); -uint64_t qsa_buffers_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaBuffers& b); - -/// `x` (n_embd f32) through one QSA layer to `out` (n_embd f32) at sequence position `pos`. -/// -/// `pos_base` is the sequence's FIRST cell's position, which the indexer needs and cannot derive - equating a -/// cell's position with its index is only right for a sequence starting at 0. -/// -/// THE OP ORDER IS `ref/model.py::_qsa`, and two things in it are easy to read past: -/// -/// * the indexer's raw key is appended BEFORE any norm or rotation, and it is the raw `indexer.k_proj` -/// output that is pooled and rotated LATER, once per block and at the block's FIRST cell; -/// * `q_full` is split into q and gate by HALVES of each head's 2*head_dim block, contiguous, not -/// interleaved - `qsa_gate_apply` reads the second half and `qcur` is copied out of the first. -/// -/// THE THREE ACTIVATION FORMATS FOLLOW `docs/activation-contract.md`, and they are not interchangeable: -/// `attn_q` is Q2_0 (Q8_0 activation), `attn_k`/`attn_v`/`attn_output` are K-quants (Q8_K), and the two -/// indexer projections are BF16 (bf16). -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 = nullptr); - -// ================================ THE DOORBELL ================================ - -/// THE HANDOFF: `x_f` and the miss list reach the CPU WHILE THE LAYER IS STILL RUNNING. -/// -/// Everything about the shape of this struct comes from two measurements, and neither was a guess: -/// -/// * **THE WAIT MUST POLL THE DRIVER.** Round 195: a host spin that only reads a memory location never runs -/// the kernel - 5,907,703 spins over 500 ms and the datum flips the instant `cudaStreamSynchronize` is -/// called and never before, because on Windows the driver BATCHES command submission and a memory-only -/// spin gives it no reason to flush. So `h_seq` is read AND `cudaEventQuery` is called, which is a query -/// and not a blocking sync - P2.X3's "zero synchronization calls in the layer loop" still holds. -/// * **THE WRITE MUST BE CAPTURABLE, AND A KERNEL IS.** Round 199: `cudaEventRecord` inside a capture is -/// SILENTLY DROPPED - 2 nodes for two kernels plus an event record, and the event never completed across a -/// 41 ms graph. A mid-graph doorbell KERNEL is captured normally, and round 209 measured the host seeing a -/// pinned handoff **0.050 ms** into a 39.8 ms graph. -/// -/// The memory is MAPPED PINNED, so it has one address for the device and another for the host and both refer -/// to the same bytes. Pinned as well as mapped, because a pageable destination would turn the device's write -/// into a staged copy and give back the overlap this exists for. -struct Doorbell { - int64_t n_embd = 0; - int64_t k = 0; - // the HOST's view - float* h_x_f = nullptr; ///< n_embd - int32_t* h_ids = nullptr; ///< k - float* h_weights = nullptr; ///< k - uint32_t* h_seq = nullptr; ///< 1 - /// Plan v0.3 P3 token graph: the HOST's answer. The host writes the ring value it has served (after the - /// pool's output is in place); the device's `doorbell_wait` spins until the flag equals the ring. - uint32_t* h_flag = nullptr; ///< 1 - // the DEVICE's view of the same bytes - float* d_x_f = nullptr; - int32_t* d_ids = nullptr; - float* d_weights = nullptr; - uint32_t* d_seq = nullptr; - uint32_t* d_flag = nullptr; -}; - -/// Allocates the four mapped-pinned regions. Returns the bytes, or 0 on failure. -uint64_t doorbell_init(const ModelGeometry& g, int64_t k, Doorbell& db); -void doorbell_free(Doorbell& db); -/// Zeroes `h_seq` (and `h_flag`), so a caller can wait for it to become `expected` from a known state. -void doorbell_reset(const Doorbell& db); - -// ================================ ONE WHOLE BLOCK ================================ - -/// The gated-residual stack plus the two buffers the halves hand to each other. -/// -/// `R` is (hc, n_embd) and is BOTH the input and the output: `hc` residual streams, each n_embd wide, which is -/// what `gr_read`/`gr_write` exist for. It is not one vector with a gate. -struct BlockBuffers { - float* R = nullptr; ///< (hc, n_embd) - float* mixed = nullptr; ///< n_embd: what the mixer consumes - float* block_out = nullptr; ///< n_embd: what a half produces - float* inject = nullptr; ///< hc: `gr_read`'s per-stream injection, reused per half - /// Plan v0.3 P3 fused GR: the FFN half's injection lives here (the attention half's stays in `inject`), - /// because the fused read of one half reads the other half's injection while writing its own. - float* inject2 = nullptr; ///< hc - float* gr_rs = nullptr; ///< hc: the fused read's per-stream 1/rms - uint8_t* head_q8k = nullptr; ///< `q8k_bytes(n_embd)`: the head's Q8_K activation image - strata::kernels::GrWorkspace gr; ///< `gr_read`'s scratch - - /// THE HALF-LEVEL C1 ORACLE, and it is a HOST buffer of `(2 * n_embd + 2 * hc + n_head * head_dim)` floats - /// PER LAYER: `[0, n_embd)` the attention half's `block_out`, `[n_embd, 2*n_embd)` the MoE half's, the two - /// `hc`-vectors of `inject`, and finally the QSA layers' PRE-GATE attention (`n_head * head_dim`, unused by - /// GDN). The residual ladder (`session_loop`'s `dump_layers`) says WHICH LAYER diverges; this says which - /// stage, and it is the only way to separate the reference's `linear_attn_out-` from its `ffn_out-` - /// without re-deriving one of them. The copies are issued from inside `block_layer_pre`/`_post`, so they - /// are recorded as nodes of the per-layer captured graph and replay with the layer they belong to. Null - /// means no dumping, which is the default and costs nothing. - float* dump = nullptr; -}; - -uint64_t block_buffers_bytes(const ModelGeometry& g); - -/// Plan v0.3 P3: the hyper-connection read as two fused kernels with the previous half's write folded in -/// (`strata/kernels/fused_gr.hpp`). Requires the native MMVF contract (FP32 activations). The residual `R` -/// then lags by one pending write between halves; it is materialised before the layer-1 PLE and after the last -/// layer. Set before capture; not for the per-stage or dump measurements. -void layer_set_fused_gr(bool enabled); -bool layer_fused_gr(); - -/// Plan v0.3 P3/P7: QSA attention by the split-K kernel reading the KV pools directly (default ON; `false` keeps -/// the gather + one-block-per-head kernel). Set before capture. -void layer_set_fast_attn(bool enabled); -/// Plan v0.3 P3: doorbell payload + ring as one kernel, QSA step staging read by a kernel from mapped memory -/// (default ON; `false` keeps the memcpy nodes). Set before capture. -void layer_set_publish_kernel(bool enabled); -/// Plan v0.3 P3: GDN step + output norm as one coalesced kernel under the native contract (default ON). -void layer_set_fused_gdn(bool enabled); -/// Plan v0.3 P7: QSA block scores in FP32 and a radix top-k over blocks (default ON; `false` = the FP64 row scores -/// and the bit-serial cell top-k). Set before capture. -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. -/// -/// `token_embd.weight` is `[n_embd, n_vocab]`, so `out[i] = W[i][token]` - one column, `n_embd` values. Running -/// `output`-style arithmetic on a one-hot activation would produce the same numbers with 248320x the work. -/// -/// **THE DECODE IS TRANSCRIBED FROM `s_gemv_q8k_split` AND MUST STAY BIT-IDENTICAL TO IT**: the code is the -/// `CODE_BITS`-wide field, least-significant first, at bit `(i % PER_BYTE) * CODE_BITS` of byte `i / PER_BYTE`; -/// the value is `(code + code_bias) * scales[i / group_elems] + offsets[i / group_elems]`; and the column's -/// planes start at `token * n_in / PER_BYTE` and `token * n_in / group_elems`. A second decoder that drifts -/// from the kernel's would make the prompt embed differently from the tokens generated after it. -bool embed_row(const WeightTable& tables, const ModelGeometry& g, int64_t token, float* out_dev, void* stream, - std::string& err); - -/// `ref/model.py` L520: `fin = GR.gr_read(R, output_hc_*..., inject=None, rms_eps); logits = output @ fin`. -/// -/// `R` is read from `bb.R` and the result goes to `logits`, which the caller sizes at `output.weight`'s `ne1` -/// (the vocabulary). `bb.head_q8k` and `bb.mixed` are scratch. -bool lm_head(const WeightTable& tables, const ModelGeometry& g, const BlockBuffers& bb, float* logits, - void* stream, std::string& err); - -/// Compute the final residual mix in bb.mixed, before the output projection. This is shared by the -/// canonical and experimental native head so only the projection's arithmetic changes in their A/B test. -bool lm_head_mix(const WeightTable& tables, const ModelGeometry& g, const BlockBuffers& bb, - void* stream, std::string& err); - -/// THE PER-LAYER OP ORDER of `phases/phase-2-correct-engine.md` P2.S5, architecture §6.1, for ONE layer: -/// -/// gr_read (attn) -> mixer -> gr_write (attn) -/// gr_read (ffn) -> MoE -> gr_write (ffn) -/// -/// `layer` picks the mixer: `is_qsa_layer` selects `qsa_layer`, otherwise `gdn_layer`. `pos`/`pos_base` reach -/// the QSA layer and are ignored by GDN, which has no position argument at all - its whole per-token input is -/// `x` and what advances between tokens is its recurrent state. -/// -/// **`parts` IS THE CALLER'S**, and that is the architecture's split rather than an omission: the routed experts -/// are the only part of the model that does not fit in VRAM, so the CPU pool and the VRAM-resident experts fill -/// `parts` and this function owns the two ends. In P2.S5 everything is a miss, so a caller passes whatever the -/// pool produced; the doorbell protocol is what lets it be produced DURING this layer rather than before it. -// ================================ THE PLE (LAYER 1'S PER-LAYER EMBEDDING) ================================ -// -// **THIS MODULE EXISTED, WAS PARITY-TESTED, AND WAS NEVER CALLED - WHICH IS WHY GATE C1 FAILED.** Layer 1 is -// the only layer with `blk.1.ple_*` tensors (six of them) and `block_layer` ran GDN/QSA + GR + MoE without it, -// so the engine computed a different model. `ple_parity` verifies all three pieces against things that are -// not this project's code - the hash against `ref/ngram.py` with the artifact's own constants, the IQ4_NL row -// read against numpy over the original GGUF, and the block against ggml's own graph - and none of that helps -// if nothing calls it. -// -// THE TABLE IS NOT IN THE PACK. `per_layer_token_embd.weight` is 51.2e9 elements (28.8 GB) of IQ4_NL in the -// ORIGINAL second GGUF shard, and it is the only tensor this engine reads from the GGUF rather than from the -// canonical pack. It is also why the PLE is cheap: sixteen 90-byte rows per token is 1440 bytes of traffic, -// against the experts' 664 MB. -struct PleRun { - /// Null when the PLE is not wired (no table, or a pack without `blk.1.ple_*`). Then `block_layer_pre` - /// SKIPS the module entirely, which is what every measurement before this change did. - strata::kernels::PleTable* table = nullptr; - strata::kernels::PleWeights w; - /// The session's PLE state, by pointer so `block_layer_pre` needs no `SessionState`. - const int32_t* token = nullptr; ///< the token being decoded - const int32_t* prev = nullptr; ///< (2,) predecessors, OLDEST FIRST, `-1` where there is none - float* hist = nullptr; ///< NG_HIST x hc_dim NORMALIZED history, row-fastest - /// The gathered 2560-wide row vector on the DEVICE, and the host staging it is copied from: `gather` - /// writes HOST memory (the table is a host mapping) and the block wants the device. - float* emb_dev = nullptr; - float* emb_host = nullptr; - /// Internal workspace plus a disjoint normalized export for the next history row. - /// Allocate ple_run_scratch_bytes(), not merely the lower-level ple_block_scratch_bytes(). - float* scratch = nullptr; - strata::kernels::PleConsts consts; - bool ready() const { - return table != nullptr && table->is_open() && hist != nullptr && emb_dev != nullptr && - emb_host != nullptr && scratch != nullptr && token != nullptr && prev != nullptr && - ((w.key_codes != nullptr && w.key_scales != nullptr) || w.key_bf16 != nullptr || - w.key_native_data != nullptr) && - w.value_bf16 != nullptr && - w.norm_key != nullptr && w.norm_query != nullptr && w.norm_conv != nullptr && - w.conv1d_f16 != nullptr; - } -}; - -/// **CALLED ONCE PER TOKEN, FROM THE DRIVER, *OUTSIDE* ANY CAPTURE.** The n-gram hash and the table gather -/// are host operations, and `block_layer_pre` is captured - so doing them there would run them once, at capture -/// time, and replay the same rows for every token forever. This is the doorbell's cloned-literal bug in a -/// different coat: silent, finite, and stable. -bool ple_stage_token(const PleRun& p, void* stream, std::string& err); - -/// Plan v0.3 P2: `ple_stage_token` in two halves, so the SSD reads overlap other host work. -/// `ple_issue_token` hashes the token and starts its 16 row reads; `ple_finish_token` waits for them, -/// dequantizes and queues the upload. Both are driver-side, outside any capture, like `ple_stage_token`. -bool ple_issue_token(const PleRun& p, std::string& err); -bool ple_finish_token(const PleRun& p, void* stream, std::string& err); - -/// Internal PLE workspace plus one separate hc_dim normalized row for advancing history. -uint64_t ple_run_scratch_bytes(); - -/// `ple` is the layer-1 PLE, or null to skip it (which is what every measurement before LEDGER L123 did). -/// It is applied INSIDE `pre[1]`, before layer 1's own `gr_read`, because the block's output is -/// `hidden + gated + silu(conv)` on the residual itself - it is a residual UPDATE, and the architecture puts -/// the gathered rows in place "before layer 2". -bool block_layer(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, const float* parts, void* stream, std::string& err, - const Doorbell* db = nullptr, const PleRun* ple = nullptr); - -/// **THE BLOCK, SPLIT AT THE ROUTER, SO A HOST LOOP CAN PUT THE CPU POOL IN THE MIDDLE.** -/// -/// pre[l] gr_read(attn) -> mixer -> gr_write(attn) -> gr_read(ffn) -> moe_route [rings the doorbell] -/// post[l] moe_finish -> gr_write(ffn) -/// -/// `parts` reaches only `post`, and it must be THIS layer's experts. The two calls are NOT independent: `post` -/// reads `bb.mixed` and `bb.inject` exactly as `pre` left them, so nothing may run between them that touches the -/// block buffers - and in particular `pre[l+1]` may NOT be launched between them, because its own `gr_read` -/// overwrites both. That constraint is why the doorbell's window is the shared expert and nothing more, and -/// why the CPU expert term is answered by Phase 3's VRAM cache rather than by this pipeline. -/// -/// **`half` EXISTS SO THE CAPTURED GRAPH CAN BE SPLIT FOR MEASUREMENT, AND IT IS THE ONLY REASON.** -/// -/// The plan's R3 items - GR, GDN, the router - are each worth several milliseconds and there has never been a -/// per-stage breakdown of the CAPTURED graph to choose between them. The `--no-capture` table cannot supply -/// one: round 312 showed its `moe_finish` figure was a host-gap artefact, four times the captured cost of the -/// same work. An event recorded BETWEEN two `cudaGraphLaunch` calls IS valid, so the answer is to capture the -/// layer as more than one graph and time them from outside. -/// -/// `half` selects a prefix of the stages, and the seam is the one this file already documents: -/// -/// 1 = stages 0..2 gr_read -> attention -> gr_write the MIXER -/// 2 = stages 3..4 gr_read -> moe_route the FFN front and the ROUTER -/// 0 = both, which is what every caller before this used and what `session_loop` still uses -/// -/// **A half is not a free-standing call.** `2` reads what `1` left in `bb.mixed`/`bb.inject`, exactly as -/// `block_layer_post` does; the two are only meaningful replayed in order on one stream, which is what -/// `session_replay_stages` does. -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 = nullptr, const PleRun* ple = nullptr, int half = 0, - int stage_prefix = 0); - -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); - -} // namespace strata::core diff --git a/include/strata/core/layout.hpp b/include/strata/core/layout.hpp deleted file mode 100644 index 0273178..0000000 --- a/include/strata/core/layout.hpp +++ /dev/null @@ -1,139 +0,0 @@ -// include/strata/core/layout.hpp - the pack's LAYOUT, resolved by name and checked against the kernels. -// -// `WeightTable` answers "where are the bytes". This answers "is this the tensor I think it is", and it is -// the layer where a pack and a kernel disagree - which is the failure this project keeps paying for. Two -// examples, both real: -// -// * round 194 sized the indexer key store from `indexer.head_count = 4`, which counts QUERY heads. The -// cached key is ONE shared head of 128 (`indexer.k_proj` is [2560, 128]), so the term was 4x too big and -// the error survived a round because it moved in the direction that TIGHTENS the budget. -// * `docs/semantics.md` and the tensor manifest agree on every dimension here, but nothing CHECKED that a -// named tensor had the shape the kernel reading it assumes. -// -// So this header does two things: it names the tensors per layer type, and it asserts every shape the -// kernels depend on. A mismatch is reported with the tensor name, the shape found and the shape required, -// at LOAD time - not as a wrong number inside a GEMV at token 4000. -#pragma once - -#include "strata/core/weights.hpp" -#include "strata/kernels/gdn.hpp" - -#include -#include - -namespace strata::core { - -/// Which architecture the model file declares. The engine was written for ONE model (Qwen3.8-Flash-Next, -/// `qwen4exp`); Qwen3.6-35B-A3B (`qwen35moe`) is the same family one generation earlier with the hyper-connection -/// residual, the sparse-attention indexer and the PLE table removed. The string decides what the file cannot say: -/// `hc`, the indexer and the PLE (docs/QWEN36-35B-A3B.md section 3.8). -enum class ModelArch { Qwen4Exp, Qwen35Moe }; - -inline const char* model_arch_name(ModelArch a) { return a == ModelArch::Qwen4Exp ? "qwen4exp" : "qwen35moe"; } - -/// The model's geometry. Every field here is a number a kernel depends on, so a change is a change to a kernel -/// contract and not a tuning knob. The defaults are Qwen3.8-Flash-Next's (`docs/semantics.md`); a model file -/// overrides every one of them through `read_model_geometry` (strata/core/model_geometry.hpp), which reads the -/// `.*` 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; ///< 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 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 - - // 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. `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; ///< `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 -/// = 4` and an explicit `attention.compress_ratios` array - and this is the first of the two. -inline bool is_qsa_layer(const ModelGeometry& g, int64_t layer) { - return layer % g.qsa_interval == g.qsa_interval - 1; -} - -/// One layer's tensors, resolved by NAME. `get("attn_qkv.weight")` looks up `blk..attn_qkv.weight` -/// and returns null if the pack does not have it - a null is information, because a GDN layer has no -/// `attn_q` and a QSA layer has no `attn_qkv`. -/// -/// Holds a reference to the table; the table must outlive it. -class LayerView { -public: - LayerView(const WeightTable& table, int64_t layer) : table_(&table), layer_(layer) {} - - int64_t layer() const { return layer_; } - std::string name(const char* suffix) const; - const WeightRef* get(const char* suffix) const { return table_->find(name(suffix)); } - -private: - const WeightTable* table_; - int64_t layer_; -}; - -/// Every shape the kernels depend on, asserted for ONE layer. Returns false and fills `err` with the first -/// mismatch, naming the tensor, what it has and what is required. -/// -/// This is deliberately a separate function from `LayerView`: a caller that only wants the pointers should -/// not pay for the checks, and a caller that wants the checks should get ALL of them rather than the ones -/// its own call site happens to touch. -bool check_layer(const WeightTable& table, const ModelGeometry& g, int64_t layer, std::string& err); - -/// `check_layer` over every layer, plus the cross-layer properties: exactly 12 QSA layers at the right -/// indices, every GDN layer having the GDN set and no QSA tensor, and vice versa. Returns the first failure. -bool check_all(const WeightTable& table, const ModelGeometry& g, std::string& err); - -} // namespace strata::core diff --git a/include/strata/core/model_geometry.hpp b/include/strata/core/model_geometry.hpp deleted file mode 100644 index e04dae6..0000000 --- a/include/strata/core/model_geometry.hpp +++ /dev/null @@ -1,262 +0,0 @@ -// include/strata/core/model_geometry.hpp - `ModelGeometry` from the model file's own metadata. -// -// Until Phase 2 step 2 of docs/PLAN-qwen36-35b-a3b.md the geometry was a struct of Flash-Next defaults and only -// `expert_count`, `expert_used_count` and the rope keys were read, under the `qwen4exp.` prefix and only with -// `--native` (docs/qwen36-port/geometry-inventory.md rows 7 to 10). This header reads every field from the -// `.*` 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 -#include -#include - -namespace strata::core { - -namespace detail { - -/// One integer key: `.`. `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 diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp deleted file mode 100644 index e7a06f1..0000000 --- a/include/strata/core/mtp.hpp +++ /dev/null @@ -1,228 +0,0 @@ -// include/strata/core/mtp.hpp - plan v0.3 P6: the MTP draft layer on the GPU. -// -// The model ships one multi-token-prediction layer (vLLM 0.30.0 `qwen4_exp` MTP; transcribed and validated in -// `tools/mtp_probe.py`, where it accepts 0.89 / 0.86 / 0.85 of greedy drafts at steps 1-3). Cell i of its -// sequence pairs the main model's final multi-stream residual at position i with the token at position i+1, at -// rope position i (vLLM's convention); its output predicts the token at position i+2, and its own residual feeds -// the next draft step. -// -// e = fc_embedding(rms(embed(tok)) * (1+w)) h = fc_hidden per stream(rms_10240(R) * (1+w)) -// R = h + e -> attention hyper-connection -> QSA attention (own K/V) -> MLP hyper-connection -> -// MoE (512 experts, top-10, shared expert) -> R += y * 2 sigmoid(inject / hc) -> final mixer -> head -// -// Runtime choices, each a trade of exactness for simplicity that only affects DRAFT quality, never the output -// (the verify window decides every emitted token): -// * the large projections run as Q8_0 through the multi-column MMVQ (`tools/mtp_rt.py` quantizes them); -// * the attention is DENSE over every cell the layer has seen - identical to the model's sparse selection -// below 2,051 cells - so speculative cells (draft steps, rejected window rows) never touch indexer state and -// are simply overwritten when their positions are processed again; -// * all 512 routed experts live in VRAM (708 MB) and run through the grouped hit kernels. -#pragma once - -#include "strata/core/layer.hpp" -#include "strata/core/session.hpp" -#include "strata/kernels/sampler.hpp" - -#include - -#include -#include -#include -#include - -namespace strata::core { - -class NativeHead; - -class MtpDrafter { -public: - MtpDrafter() = default; - ~MtpDrafter(); - MtpDrafter(const MtpDrafter&) = delete; - MtpDrafter& operator=(const MtpDrafter&) = delete; - - /// Loads `rt_dir` (from tools/mtp_rt.py) and allocates the layer's K/V and buffers for up to `max_t` rows. - /// Call before the VRAM expert tier is sized: this takes ~0.9 GB. - bool load(const std::string& rt_dir, const ModelGeometry& g, SessionState& ss, int max_t, std::string& err, - int64_t window = 32768); - /// The prompt's length: prefill() skips the cells the attention window can never reach again. - void set_prompt_len(int64_t n) { prompt_len_ = n; } - /// At most this many drafts per round (below max_t - 1): a window longer than the MTP's comes from elsewhere. - void set_max_drafts(int k) { max_drafts_ = k; } - uint64_t vram_bytes() const { return vram_; } - /// The draft layer's K/V state (read-only: --serve's STRATA_STATE_HASH check hashes it) - const QsaState& kv_state() const { return st_; } - /// KV streaming: refill the ring of the drafter's window from its host copy for a sequence that continues at - /// `upto` (a conversation-cache resume). No-op unless the drafter's K/V is a ring. - void kv_restore(int64_t upto); - /// The VRAM bind() will allocate for a native head of `head_row_bytes` per vocabulary row: the draft logits and - /// the draft head over rt/draft_vocab.bin's subset. The expert cache is sized before bind(), so it reserves this. - uint64_t bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const; - /// The main model's embedding and head, and the verify window's final residuals (T rows, hc*n_embd each). - bool bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err); - - /// Prompt cells [cell0, cell0 + n): residual rows `R_rows` (device, hc*n_embd each) and `next_tokens` (host, - /// the token at position cell+1). Runs in batches of up to max_t rows. - bool prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err); - - /// One round: catch-up over T cells from `p` (rows = the window's final residuals, `tokens` = the window's - /// argmaxes: row t pairs R_{p+t} with the token at p+t+1), then the draft chain from row `a` (the last - /// accepted row) for T-1 drafts at cells p+a+1 ... `drafts` gets T-1 tokens. - bool draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* drafts, std::string& err, - float* probs = nullptr, float min_p = 0.0f, int* n_drafts = nullptr); - - /// The first round: one cell (`cell`) from `R_row` (device) and `token` -> T-1 drafts. - bool draft_first(int T, const float* R_row, int32_t token, int64_t cell, int32_t* drafts, std::string& err, - float* probs = nullptr, float min_p = 0.0f, int* n_drafts = nullptr); - - /// COUPLED DRAFT SAMPLING (core/coupled_draft.hpp; STRATA_SPEC_COUPLED=1, set up by bind()): the request's - /// sampling. A sampled request (temperature > 0, not greedy) then drafts by SAMPLING with the target's chain and - /// the target's Philox draw for the verifying row, and `probs` is the draft's probability under that chain; a - /// greedy one keeps the argmax drafts and their graphs. A no-op when the switch is off. - void set_draft_sampling(const strata::kernels::SamplerParams& sp); - /// Coupled mode with penalties: the history the next draft() chain starts from - what the session holds after the - /// window's commit (`tail`) and the window's pick at its last accepted row (`next`, the next window's row 0). - void set_draft_history(const int32_t* tail, int64_t n_tail, int32_t next); - void set_ple_session(SessionState* s) { ple_ss_ = s; } - bool coupled() const { return coupled_active_; } - - double ms_draft = 0, ms_prefill = 0; - int64_t rounds = 0; - - /// E-9: the prompt path computes this layer's prompt K/V in batches (Prefill::draft_kv): its tensors, its K/V - /// state, the first cell a round can still read, its device, and a wait for its own stream. - 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; - 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_; } - bool idle(std::string& err) { - if (cs_ && cudaStreamSynchronize(cs_) != cudaSuccess) { err = "mtp: its stream failed"; return false; } - return true; - } - -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); - bool capture_step(int j, bool coupled, std::string& err); - cudaGraphExec_t step_exec_[9] = {}; - // coupled draft sampling: its own round/step graphs (the argmax ones stay as they were), the request's - // parameters and the penalty ring (mapped staging + device copies), the split scratch, token id -> subset index - bool setup_coupled(std::string& err); - cudaGraphExec_t round_exec_c_[9] = {}; - cudaGraphExec_t step_exec_c_[9] = {}; - bool coupled_ok_ = false, coupled_active_ = false; - bool coupled_rec_ = false; ///< record_forward: the full layer ends in the coupled sampler (draft coupled_j_) - int coupled_j_ = 0; - strata::kernels::SamplerParams *h_cparams_ = nullptr, *m_cparams_ = nullptr, *cparams_ = nullptr; - int32_t *h_chist_ = nullptr, *m_chist_ = nullptr, *cring_ = nullptr, *dinv_ = nullptr; - void* cscratch_ = nullptr; - const float* f32(const char* name) const; - const uint16_t* bf16(const char* name) const; - const void* q8(const char* name) const; - - const ModelGeometry* g_ = nullptr; - SessionState* ss_ = nullptr; - SessionState* ple_ss_ = nullptr; - const WeightTable* wt_ = nullptr; - const NativeHead* head_ = nullptr; - const float* window_R_ = nullptr; - int max_t_ = 0; - int device_ = -1; ///< the device `load` ran on: the public calls switch to it (layer split) - int max_drafts_ = 1 << 30; - int64_t n_vocab_ = 0; - uint64_t vram_ = 0; - cudaStream_t cs_ = nullptr; - cudaGraphExec_t prefill_exec_[9] = {}; - cudaGraphExec_t prefill_dev_exec_[9] = {}; - int32_t* pf_dev_ = nullptr; ///< E-4: a prompt's rows' token / step / position records, uploaded at once - int64_t pf_cap_ = 0; ///< its capacity in ints - cudaGraphExec_t round_exec_[9] = {}; - - struct Tensor { std::string name, kind; int64_t rows = 0, cols = 0; uint64_t off = 0, bytes = 0; int type = -1; }; - std::vector tensors_; - uint8_t* dense_ = nullptr; - uint8_t* experts_ = nullptr; - void* state_arena_ = nullptr; - QsaState st_; - void* arena_ = nullptr; - - // mapped staging: tokens, step records (2*max_t rows), positions per head (2*max_t rows), the selected row, - // the drafts out - int32_t *h_tok_ = nullptr, *m_tok_ = nullptr, *h_step_ = nullptr, *m_step_ = nullptr; - int32_t *h_pos_ = nullptr, *m_pos_ = nullptr, *h_row_ = nullptr, *m_row_ = nullptr; - int32_t *h_out_ = nullptr, *m_out_ = nullptr; - float *h_prob_ = nullptr, *m_prob_ = nullptr; // each draft's probability under the draft layer - // the draft head: the main head's rows for a token subset (rt/draft_vocab.bin), or the whole head - uint8_t* dhead_ = nullptr; - int32_t* dvocab_ = nullptr; - int64_t n_dvocab_ = 0; - std::string rt_dir_; - int64_t window_ = 0; // attention over the last window_ cells (0 = every cell) - int64_t prompt_len_ = 0; - float* probs_ = nullptr; - // device - int32_t *tok_ = nullptr, *step_ = nullptr, *pos_ = nullptr, *row_ = nullptr, *ident_ = nullptr; - float *Rin_ = nullptr, *R_ = nullptr, *emb_ = nullptr, *en_ = nullptr, *e2_ = nullptr, *hn_ = nullptr, *h2_ = nullptr; - float *mixed_ = nullptr, *inj_ = nullptr, *inj2_ = nullptr, *lo_ = nullptr, *rs_ = nullptr, *bo_ = nullptr; - float* xn_ = nullptr; - uint8_t* xq_ = nullptr; - float *qfull_ = nullptr, *qcur_ = nullptr, *kcur_ = nullptr, *vcur_ = nullptr, *attn_ = nullptr, *attn32_ = nullptr; - float* attn_scratch_ = nullptr; - float *logits_ = nullptr, *w_ = nullptr, *shared_ = nullptr, *parts_ = nullptr, *y_ = nullptr, *sample_ = nullptr; - int32_t *ids_ = nullptr, *hit_slot_ = nullptr, *hit_dst_ = nullptr, *hit_count_ = nullptr, *out_ids_ = nullptr; - uint8_t* hit_xq_ = nullptr; - unsigned long long* grp_ptr_ = nullptr; - int32_t *grp_start_ = nullptr, *grp_counts_ = nullptr; - float* hit_xs_ = nullptr; - void* hit_scratch_ = nullptr; - float* sh_scratch_ = nullptr; - uint16_t* x_bf16_ = nullptr; - float* head_logits_ = nullptr; - float* dummy_inj_ = nullptr; - int64_t cap_ = 0, attn_scratch_floats_ = 0; -}; - -} // namespace strata::core diff --git a/include/strata/core/native_dense.hpp b/include/strata/core/native_dense.hpp deleted file mode 100644 index 2d3cb94..0000000 --- a/include/strata/core/native_dense.hpp +++ /dev/null @@ -1,45 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace strata::core { -class WeightTable; - -// Experimental GDN/QSA/shared-expert projection overrides. Upload unchanged native GGUF -// blocks once, then attach them to the matching canonical WeightRef. Unsupported -// types retain their canonical paths. Owns one Q8_1 scratch vector shared by all -// these projections, so use one ordered session stream and keep this object -// alive until all graphs that reference it have been destroyed and synchronized. -class NativeDense { -public: - NativeDense() = default; - ~NativeDense(); - NativeDense(const NativeDense&) = delete; - NativeDense& operator=(const NativeDense&) = delete; - /// With layer_hi >= 0, only the `blk..` matrices with layer_lo <= l < layer_hi are uploaded (a layer - /// split's stage holds its own layers' projections, not the whole model's); the others keep data == nullptr. - bool load(const std::vector& shards, WeightTable& table, std::string& err, - bool include_ple_key = false, int64_t layer_lo = 0, int64_t layer_hi = -1); - /// Plan v0.3 P1: the canonical tensor names `load` would serve natively from these shards (eligible name, - /// supported type, 2-D), read from the GGUF headers only - so the canonical arena can skip them. - static bool served_names(const std::vector& shards, bool include_ple_key, - std::set& out, std::string& err); - /// Layer split: load only blocks [lb, le) (every other `blk.N.` projection belongs to another GPU's stage; the - /// PLE tensors are loaded everywhere). Process-wide, read by the next `load`; (-1, -1) = all layers. - static void set_layer_range(int lb, int le); - /// #326: a native pack whose `blk.1.ple_key.weight` row is unquantized (iq_pack --compat-bf16 of a GGUF key - /// the native kernel also reads, e.g. OrcaRouter's IQ3_XXS) serves the PLE from that row, so it is taken out - /// of `skip` and `load` does not upload the GGUF key over it. A quantized row leaves `skip` unchanged. - static bool keep_unquantized_ple_key(const std::string& pack_dir, std::set& skip, std::string& err); - uint64_t weight_bytes() const { return bytes_; } - size_t tensor_count() const { return weights_.size(); } - -private: - std::vector weights_; - void* scratch_ = nullptr; - uint64_t bytes_ = 0; -}; -} // namespace strata::core diff --git a/include/strata/core/native_head.hpp b/include/strata/core/native_head.hpp deleted file mode 100644 index ff45dd6..0000000 --- a/include/strata/core/native_head.hpp +++ /dev/null @@ -1,68 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace strata::core { - -/// Opt-in native output projection. Uploads unchanged GGUF blocks once at startup and owns its -/// activation scratch. The normal canonical head remains available for numerical A/B comparisons. -/// Plan v0.3 P6: any type the native MMVQ takes (Q5_K in the Q2_0 / IQ3_XXS files, IQ4_XS in IQ2_XS). -/// `load` takes the model's shards (strata::gguf_split_paths): the architecture is checked on the first, the -/// tensor is read from the shard that holds it. -class NativeHead { -public: - NativeHead() = default; - ~NativeHead(); - NativeHead(const NativeHead&) = delete; - NativeHead& operator=(const NativeHead&) = delete; - - bool load(const std::vector& shards, int64_t n_in, int64_t n_out, std::string& err); - bool run(const float* mixed, float* logits, void* stream, std::string& err) const; - uint64_t weight_bytes() const { return bytes_; } - bool loaded() const { return weights_ != nullptr; } - /// Plan v0.3 P6: the GGUF blocks, for the verify window's multi-column head. - const void* weights() const { return weights_; } - int type() const { return type_; } - /// Bytes of one vocabulary row. - size_t row_bytes() const { return n_out_ > 0 ? (size_t) (bytes_ / (uint64_t) n_out_) : 0; } - -private: - void* weights_ = nullptr; - void* scratch_ = nullptr; - uint64_t bytes_ = 0; - int n_in_ = 0, n_out_ = 0; - int type_ = -1; -}; - -/// Plan v0.3 P6: `token_embd.weight` in its GGUF form (the IQ model files), in mapped pinned host memory: a row -/// is read over PCIe per token, so the table costs no VRAM. `embed_row`, the verify window and the MTP drafter -/// use it instead of the canonical table when it is set (`set_native_embed`). -class NativeEmbed { -public: - NativeEmbed() = default; - ~NativeEmbed(); - NativeEmbed(const NativeEmbed&) = delete; - NativeEmbed& operator=(const NativeEmbed&) = delete; - bool load(const std::vector& shards, int64_t n_embd, int64_t n_vocab, std::string& err); - /// Rows for device token ids. - void gather_dev(const int32_t* tokens, int64_t n_tok, float* out, void* stream) const; - /// One row for a host token id. - void gather_one(int64_t token, float* out, void* stream) const; - uint64_t bytes() const { return bytes_; } - int type() const { return type_; } - -private: - void* host_ = nullptr; - const void* dev_ = nullptr; - uint64_t bytes_ = 0; - size_t row_ = 0; - int64_t n_embd_ = 0, n_vocab_ = 0; - int type_ = -1; -}; -void set_native_embed(const NativeEmbed* e); -const NativeEmbed* native_embed(); - -} // namespace strata::core diff --git a/include/strata/core/on_device.hpp b/include/strata/core/on_device.hpp deleted file mode 100644 index ed876f4..0000000 --- a/include/strata/core/on_device.hpp +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once -// Multi-GPU: make `device` current for a scope and restore the caller's device after it. An object that owns CUDA -// streams, graphs and buffers on one device (a verify stage, the drafter) wraps its public calls in this, so the -// caller's thread may be on any device. A negative device, or the device already current, does nothing. - -#include - -namespace strata::core { - -struct OnDevice { - int previous = -1; - explicit OnDevice(int device) { - int cur = 0; - if (device >= 0 && cudaGetDevice(&cur) == cudaSuccess && cur != device && cudaSetDevice(device) == cudaSuccess) - previous = cur; - } - ~OnDevice() { if (previous >= 0) cudaSetDevice(previous); } - OnDevice(const OnDevice&) = delete; - OnDevice& operator=(const OnDevice&) = delete; -}; - -} // namespace strata::core diff --git a/include/strata/core/peer_experts.hpp b/include/strata/core/peer_experts.hpp deleted file mode 100644 index a6e3766..0000000 --- a/include/strata/core/peer_experts.hpp +++ /dev/null @@ -1,106 +0,0 @@ -// include/strata/core/peer_experts.hpp - multi-GPU: a second expert tier on another GPU. -// -// The primary GPU (device 0) keeps everything it had: the dense weights, the KV cache, the MTP layer, its own -// adaptive expert tier and the captured verify graph. This class adds an expert tier on a SECOND card. From -// the verify graph's point of view nothing changes: for each layer the pool thread decides which routed experts -// the primary computes (its VRAM tier, the PCIe share), and every remaining expert is a "CPU row" the graph reads -// from mapped host memory after the pool raises its flag. The peer takes the rows whose experts it holds: the -// pool thread launches them on the peer right after publishing the primary's plan, the CPU computes the rest at -// the same time, and the peer's rows are written into the same mapped rows before the pool returns. -// -// The peer computes with the SAME kernels as the primary's hit path (q8_1 activations + native_expert_grouped), -// from the same activation values, so an expert gives bit-identical rows on either card. -// -// The tier follows the conversation like the primary's: `adapt` swaps the most-routed experts that neither card -// holds into the peer's least-used slots (per layer, so a slot keeps its layer's blob size). -#pragma once - -#include "strata/core/expert_cache.hpp" -#include "strata/core/expert_source.hpp" - -#include - -#include -#include -#include -#include - -namespace strata::core { - -/// multi-GPU: set once at startup when a peer device is configured (--peer-device N). The mapped host buffers -/// the peer card writes into are then allocated with cudaHostAllocPortable; without a peer the flag stays off. -void set_peer_portable(bool on); -bool peer_portable(); - -class PeerExperts { -public: - PeerExperts() = default; - ~PeerExperts(); - PeerExperts(const PeerExperts&) = delete; - PeerExperts& operator=(const PeerExperts&) = delete; - - /// Opens the tier on `device`: fills it with the first pairs of `ranked` that `primary` does not hold, as many - /// as fit in the card's free memory minus `reserve_mib` (`max_slots` > 0 caps the count). - bool open(int device, const std::vector>& ranked, const ExpertCache& primary, - ExpertSource& src, int64_t n_layers, int64_t n_expert, int reserve_mib, int64_t max_slots, - std::string& err); - void close(); - bool valid() const { return device_ >= 0; } - int device() const { return device_; } - - /// Whether the peer holds (layer, expert) right now. - bool has(int64_t layer, int64_t expert) const { return res_[(size_t) (layer * n_expert_ + expert)] >= 0; } - - /// The device address of (layer, expert)'s blob on the peer, or null when it is not resident. - const uint8_t* slot_ptr(int64_t layer, int64_t expert) { - const int32_t sl = res_[(size_t) (layer * n_expert_ + expert)]; - return sl >= 0 ? cache_.device_slot(sl) : nullptr; - } - /// Whether the primary (device 0) and the peer can read each other's memory directly (NVLink / PCIe P2P). - bool p2p() const { return p2p_; } - - /// Starts the peer's share of one layer: the entries i with kind[i] == 2 (x: n_tok rows of n_embd floats). - /// multi-GPU: with `out` (pinned, portable host rows) the peer writes its rows straight into - /// out[entry] with a scatter kernel (no D2H copy + host memcpy in finish); STRATA_PEER_DIRECT=0: the old way. - bool launch(int64_t layer, const float* x, const int32_t* ids, int64_t n_tok, int64_t k, const int32_t* kind, - std::string& err, float* out = nullptr); - /// Waits for the launched share and writes its rows into `out` (row i = entry i, n_embd floats). - bool finish(float* out, std::string& err); - - /// Adaptive tier: swap up to `max_swaps` experts routed at least twice that neither the primary (`res0`, slot - /// or -1) nor the peer holds into the peer's least-used slots. Copies run on the peer's refill stream; a - /// swapped-in expert becomes resident at `apply_pending`. Call only between verify windows. - bool adapt(const float* usage, const int32_t* res0, int max_swaps, std::string& err); - void apply_pending(bool wait); - - int64_t resident() const { return resident_; } - /// the last launch writes its rows into the host rows itself (the caller must not touch them) - bool launched_direct() const { return launched_direct_; } - double gib() const { return cache_.gib(); } - int64_t entries() const { return entries_; } ///< routed entries the peer computed - int64_t experts() const { return experts_; } ///< distinct (layer, expert) the peer computed - int64_t swaps() const { return swaps_; } - double ms_wait = 0; ///< host time spent in finish() waiting for the peer - -private: - int device_ = -1; - bool p2p_ = false; - int64_t n_layers_ = 0, n_expert_ = 0; - ExpertCache cache_; - ExpertSource* src_ = nullptr; - std::vector res_; ///< [n_layers * n_expert] -> peer slot or -1 - std::vector> pending_; ///< (residency index, slot) once the copies land - int64_t resident_ = 0, entries_ = 0, experts_ = 0, swaps_ = 0; - cudaStream_t stream_ = nullptr, refill_ = nullptr; - cudaEvent_t refill_ev_ = nullptr; - float* h_x_ = nullptr; float* d_x_ = nullptr; // n_tok x n_embd - float* h_out_ = nullptr; float* d_out_ = nullptr; // compact rows - void* h_meta_ = nullptr; void* d_meta_ = nullptr; // groups: ptr | start | dst | tok | count - uint8_t* d_q8_ = nullptr; - void* d_scratch_ = nullptr; - std::vector row_of_; ///< compact row -> original entry - int64_t launched_rows_ = 0; - bool launched_direct_ = false; -}; - -} // namespace strata::core diff --git a/include/strata/core/pinned.hpp b/include/strata/core/pinned.hpp deleted file mode 100644 index 28a6f98..0000000 --- a/include/strata/core/pinned.hpp +++ /dev/null @@ -1,152 +0,0 @@ -// include/strata/core/pinned.hpp - P2.S1: the host arena the expert weights live in. -// -// 33.97 GB of expert weights cannot fit in a 12 GB card, so they stay in host memory and are streamed. That -// makes this arena the engine's real working set: it must be PAGE-LOCKED for the copy engine to reach full -// bandwidth, and it must say which backing it got, because the two options differ by more than twice in TLB -// reach: -// -// * LARGE PAGES (2 MB) - `mmap(MAP_HUGETLB)` / hugetlbfs on Linux, `VirtualAlloc(MEM_LARGE_PAGES)` on -// Windows. 33.97 GB at 4 KB pages is 8.3 million TLB entries, which does not fit in any TLB, so every -// block of every expert matvec takes TLB misses. -// * NORMAL PAGES - the fallback. Correct, slower, and it must be REPORTED rather than silently accepted: -// "the engine adapts to the machine it is on" is only true if the engine says what it got. On Windows -// large pages additionally need SeLockMemoryPrivilege, which a normal user account does not have, so this -// fallback is the common case and not an error path. -#pragma once - -#include -#include -#include - -namespace strata::core { - -enum class PageBacking { LargePages, NormalPages, PinnedByCuda }; - -/// #243: STRATA_ARENA_PIN_GIB, the cap on the expert arena's CUDA registration in GiB. -1 when unset (the engine -/// decides, as in 0.1.30), 0 = no cap (the whole arena, or as many slices as the driver takes), N > 0 = at most N GiB, -/// -2 for "auto" (Windows: the sliced pin stays below the GPU's shared-memory budget). -int arena_pin_cap_gib(); - -struct PinnedArena { - void* base = nullptr; - uint64_t capacity = 0; - PageBacking backing = PageBacking::NormalPages; - std::string note; // why the backing is what it is, for the startup print - uint64_t locked_bytes = 0; // resident via the working-set lock when CUDA could not pin it - /// Plan v0.3 P5: when the whole arena cannot be registered, it is registered in `slice`-byte pieces from the - /// start; this is the pinned prefix (a copy that stays inside one slice can then DMA straight from the arena). - uint64_t registered_bytes = 0; - uint64_t slice_bytes = 0; - int registered_slices = 0; - - PinnedArena() = default; - /// `slice`: the piece size for the per-slice registration fallback (0 = none). - explicit PinnedArena(uint64_t bytes, uint64_t slice = 0); - /// Plan v0.3 P6: slices of different sizes (one per layer of a native pack), given as their start offsets - /// followed by the end of the last one. `slice_starts` holds the registered ones. - /// `max_pinned_bytes`: optional cap on CUDA registration. 0 preserves the normal unrestricted path. - /// `shared_file`: on Linux, use a file-backed MAP_SHARED mapping instead of anonymous memory. - /// `shared_pack_hash` identifies the pack that is allowed to populate that backing. The file carries a - /// small header and is refused when its stored hash does not match. Empty `shared_file` preserves the - /// existing allocation path. Population/coordination and backing-file lifetime remain the caller's job. - PinnedArena(uint64_t bytes, const std::vector& bounds, uint64_t max_pinned_bytes = 0, - const std::string& shared_file = {}, uint64_t shared_pack_hash = 0); - std::vector slice_starts; - void* mapping_base = nullptr; ///< actual mapping start; differs from base when a shared-file header exists - uint64_t mapping_bytes = 0; ///< bytes to release from mapping_base - ~PinnedArena(); - PinnedArena(const PinnedArena&) = delete; - PinnedArena& operator=(const PinnedArena&) = delete; - - bool valid() const { return base != nullptr; } - uint8_t* data() const { return (uint8_t*) base; } -}; - -struct LoadStats { - double seconds = 0.0; - // Loader fix: the two halves of `seconds`, both SUMMED OVER THE READER THREADS rather than wall clock, so - // either can exceed `seconds` when the threads overlap. They exist to separate the read from the copy and - // the hash: an 8 MiB chunk that reaches the disk as ~2048 4 KiB reads spends its time in the first one. - double read_seconds = 0.0; // inside the read call only: no seek, no copy, no hash - double copy_seconds = 0.0; // memcpy + FNV-1a - // A short read is not a slow load, it is a WRONG one: the caller must refuse the pack rather than run - // on an arena whose tail was never written. `seconds` alone cannot say that (it is -1.0 on failure, but - // the caller's own check is on the REQUESTED byte count, which a refused read does not change). - bool ok = true; // false: the load failed, see `error` - std::string error; // why it failed, for the caller's message - uint64_t bytes = 0; - uint64_t layers = 0; - std::vector layer_checksums; // one FNV-1a per layer - double gib_per_second() const { return seconds > 0 ? (double) bytes / (1024.0 * 1024 * 1024) / seconds : 0.0; } - // Aggregate rate of the readers WHILE THEY WERE INSIDE THE READ CALL: `bytes` over the mean per-thread - // read time. `gib_per_second()` above divides the same bytes by the wall clock of the whole loop, which - // also contains the copy and the hash, so the two differ by how much of the loop was not I/O. - double read_gib_per_second(int threads) const { - if (read_seconds <= 0.0 || threads < 1) return 0.0; - return (double) bytes / (1024.0 * 1024 * 1024) / (read_seconds / (double) threads); - } -}; - -// Load `layers` layers of the expert arena into `dst` with `threads` readers, `chunk` bytes at a time. -// Each thread opens its OWN handle and seeks, which is the portable form of parallel pread: a shared handle -// needs a lock around the seek and defeats the parallelism on Windows. -// -// The reads go through `fread()` on a per-thread `FILE*`, NOT through `std::ifstream`. MSVC's -// `basic_filebuf::xsgetn` splits every request larger than `_INTERNAL_BUFSIZ - 1` into 4095-byte `fread()` -// calls, so an 8 MiB `chunk` reached the disk as ~2048 4 KiB operations and the chunking did nothing at all -// (measured on a 42.9 GB pack: 1222 s, 4096 bytes per operation, 0.03 GiB/s). `fread()` hands a request -// larger than the stream buffer straight to `_read()`/`ReadFile()`, which is what `chunk` is for. The -// control flow, the copy, the per-layer FNV-1a and therefore the checksums are unchanged, so a pack loaded -// by the old and the new reader must produce identical `layer_checksums`. -LoadStats load_experts(const std::string& path, uint8_t* dst, uint64_t blob_bytes, uint64_t blobs_per_layer, - uint64_t layers, int threads, uint64_t chunk); -/// Plan v0.3 P6: the same with one byte range per layer (`layer_off[L]`, `layer_bytes[L]`). -LoadStats load_experts_ranges(const std::string& path, uint8_t* dst, const std::vector& layer_off, - const std::vector& layer_bytes, int threads, uint64_t chunk); - -/// The same ranges read UNBUFFERED straight into `dst` (Windows): no staging buffer and no file-cache copy - the -/// drive's DMA lands where the experts live. Every range, `dst` and `chunk` must be 4 KiB aligned; returns ok = -/// false with an empty `error` when they are not (or off Windows), and the caller falls back to load_experts_ranges. -LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std::vector& layer_off, - const std::vector& layer_bytes, int threads, uint64_t chunk); - -/// Whether the expert files are better read unbuffered (Windows; false elsewhere): a timed probe of random 64 KiB -/// reads says they are not in the OS file cache (a cached read takes ~10 us, the drive ~80), and the RAM left -/// beside the arena (`arena_bytes`) could not keep them cached for the next start either - so a warm restart after -/// an idle unload never gets slower, and only a start that reads the drive anyway skips the cache's copy. -/// STRATA_UNBUFFERED_LOAD=1 / 0 forces it. `why` says what decided. -/// `cache_counts` false (the file tier with a RAM budget): only whether the files could be kept decides - their mapped -/// pages land in the process's working set, so a partly cached file would still take the RAM the budget was sized for. -/// `read_bytes` (#577): the bytes the files are read for, when that is less than the files (the file tier reads only -/// the experts outside its RAM copy); `kAllFileBytes` = every byte of `files`. See platform::file_cache_keeps. -constexpr uint64_t kAllFileBytes = ~0ull; -bool experts_unbuffered(const std::vector& files, uint64_t arena_bytes, std::string& why, - bool cache_counts = true, uint64_t read_bytes = kAllFileBytes); - -// FNV-1a 64. Per layer, so a corrupt or short read names WHICH layer rather than just failing a whole-file -// comparison - the same reason the Phase 1 tools report the first differing element. -uint64_t fnv1a64(const uint8_t* p, uint64_t n, uint64_t seed = 1469598103934665603ull); - -// ---- the expert stream ----------------------------------------------------- -// -// THIS IS THE NUMBER THE OBJECTIVE DEPENDS ON. With one expert per stream, the design's own arithmetic is: -// -// per token: E = 663.6 MB of expert weights, of which only the MISSES cross the bus -// miss fraction (1 - h) x 663.6 MB / measured bandwidth = milliseconds per token -// -// So `h` (the VRAM hit rate, ~0.167 by design) is only worth anything if a per-expert transfer can actually -// reach the bus's bandwidth. A 1,382,400-byte copy is SMALL, and if small copies run at a fraction of large -// ones then the architecture's central constant is wrong and no kernel optimisation can fix it. That is what -// this measures: the same total bytes at several granularities, so the difference is visible. -struct StreamStats { - double seconds = 0.0; - uint64_t bytes = 0; - uint64_t chunk = 0; - double gib_per_second() const { return seconds > 0 ? (double) bytes / (1024.0 * 1024 * 1024) / seconds : 0.0; } -}; - -// Copy `bytes` from pinned host memory at `src` to a device buffer of `chunk` bytes, in `chunk`-sized -// transfers, `iters` times. The destination is REUSED, so this measures the bus and not allocation. -StreamStats stream_bandwidth(const uint8_t* src, uint64_t bytes, uint64_t chunk, int iters); - -} // namespace strata::core diff --git a/include/strata/core/progress.hpp b/include/strata/core/progress.hpp deleted file mode 100644 index 46c9378..0000000 --- a/include/strata/core/progress.hpp +++ /dev/null @@ -1,59 +0,0 @@ -// include/strata/core/progress.hpp - issue #29: whether a request is still moving, and where it is. -// -// The engine's host loop and the GPU wait on each other through flags; a protocol bug there does not crash, it -// spins forever (the GPU "100%", one CPU core busy, no tokens). `--serve` runs a watchdog thread over this: a -// request whose heartbeat stops for `STRATA_WATCHDOG_S` seconds (default 60; 0 = off) ends the engine with the -// stage it was stuck in, and the server starts it again instead of hanging. Tokens, prompt chunks and verify -// windows beat; the stage is two relaxed stores per layer, which the token path does not notice. -#pragma once - -#include -#include -#include -#include - -namespace strata::core { - -struct Progress { - std::atomic beats{0}; - std::atomic busy{false}; - std::atomic where{"idle"}; - std::atomic detail{-1}; - std::atomic chunk{-1}; ///< #251: the prompt chunk (its first position) a batched-read stage is in - std::atomic since_ms{0}; ///< when `where` was set (steady clock): how long a stage has lasted - std::atomic ticks{0}; ///< layers served: a window that still moves, slowly, against one that stopped -}; - -inline int64_t progress_now_ms() { - return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()) - .count(); -} - -/// What the watchdog prints about a part of the engine when it fires (the expert pool, the verify window). -using DiagFn = void (*)(std::FILE*); -inline std::atomic& diag_pool_fn() { static std::atomic f{nullptr}; return f; } -inline std::atomic& diag_verify_fn() { static std::atomic f{nullptr}; return f; } -/// #267: what a path that ends the engine runs first - it releases the GPU's spin waits on host flags (the verify -/// window's), so no kernel stays resident while the process goes away (on Windows that left the GPU "lost"). -inline std::atomic& release_gpu_fn() { static std::atomic f{nullptr}; return f; } -inline void release_gpu_waits(std::FILE* f) { - if (auto fn = release_gpu_fn().load()) fn(f); -} - -inline Progress& progress() { - static Progress p; - return p; -} - -inline void progress_at(const char* where, int64_t detail = -1, int64_t chunk = -1) { - Progress& p = progress(); - p.where.store(where, std::memory_order_relaxed); - p.detail.store(detail, std::memory_order_relaxed); - p.chunk.store(chunk, std::memory_order_relaxed); - p.since_ms.store(progress_now_ms(), std::memory_order_relaxed); -} - -inline void progress_beat() { progress().beats.fetch_add(1, std::memory_order_relaxed); } -inline void progress_tick() { progress().ticks.fetch_add(1, std::memory_order_relaxed); } - -} // namespace strata::core diff --git a/include/strata/core/qsa_shapes.hpp b/include/strata/core/qsa_shapes.hpp deleted file mode 100644 index 6ab3d81..0000000 --- a/include/strata/core/qsa_shapes.hpp +++ /dev/null @@ -1,30 +0,0 @@ -// include/strata/core/qsa_shapes.hpp - THE ONE builder of a `QsaShapes` from a `ModelGeometry`. -// -// Five sites used to transcribe the same six assignments by hand (layer.cpp, verify.cpp, mtp.cpp, session.cpp and -// prefill.cpp), and the Qwen3.6 port showed what that costs: the geometry says "no indexer" with two zeros -// (`idx_q_heads`, `idx_key_dim`) while the kernels' dense predicate (`qsa_dense`) wants the selection budget -// `idx_top_k` zero as well - a builder that copies the two and keeps `qsa_real_shapes()`'s 2,048 makes a shape -// that is neither sparse nor dense, which `qsa.cu`'s guard refuses as "not set up" at the first KV append. -// Header-only so the parity test can build the shape without linking the engine. -#pragma once - -#include "strata/core/layout.hpp" -#include "strata/kernels/qsa.hpp" - -namespace strata::core { - -/// The kernels' geometry for this model: the attention widths from the file, `n_rot`, `idx_block`, `page_size` and -/// (with an indexer) `idx_top_k` from the kernel contracts in `qsa_real_shapes()`; without an indexer the three -/// indexer widths are zero together, which is what `qsa_dense()` and the kernels' guard test. -inline strata::kernels::QsaShapes qsa_shapes(const ModelGeometry& g) { - strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head = g.n_head; - s.n_head_kv = g.n_head_kv; - s.head_dim = g.head_dim; - s.idx_n_head = g.idx_q_heads; - s.idx_dim = g.idx_key_dim; - if (!g.has_indexer()) { s.idx_n_head = 0; s.idx_dim = 0; s.idx_top_k = 0; } - return s; -} - -} // namespace strata::core diff --git a/include/strata/core/remote_expert_opt.hpp b/include/strata/core/remote_expert_opt.hpp deleted file mode 100644 index 5eb488c..0000000 --- a/include/strata/core/remote_expert_opt.hpp +++ /dev/null @@ -1,53 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -namespace strata::core { -class RemoteExperts; -class ExpertSource; - -// Remote Expert Decode Optimization v1 on existing helper caches. One instance per serial engine. -class RemoteExpertOpt { -public: - RemoteExpertOpt() = default; - ~RemoteExpertOpt(); - RemoteExpertOpt(const RemoteExpertOpt&) = delete; - RemoteExpertOpt& operator=(const RemoteExpertOpt&) = delete; - - void attach(RemoteExperts& remote); // before RemoteExperts::open - bool init(std::string& err); // after all helper caches are open - bool owns(int64_t layer, int32_t expert) const; - bool adapt(const std::vector& usage, const std::vector& primary, - const std::vector>& pending, int max_swaps, - ExpertSource& source); - - // Bracket the existing pool callback; its signature and dispatch remain unchanged. - void begin(const float* weights, int token_begin, int tokens); - void end() { weights_ = nullptr; } - void copy_rows(float* dst, const float* src, int token_begin, int tokens, - const int32_t* hit_rows, const int32_t* count, void* stream) const; - void combine(float* dst, float* scratch, int token_begin, int tokens, - const uint32_t* skip, uint32_t ring, void* stream) const; - -private: - friend class RemoteExperts; - static size_t metadata_bytes(); - bool active() const { return weights_ != nullptr; } - void prepare(const RemoteExperts& remote, void* metadata) const; - bool reduce(RemoteExperts& remote, const void* metadata, std::string& err); - void accumulate(const RemoteExperts& remote); - - struct Peer { RemoteExperts* remote; float* sum = nullptr; }; - std::vector peers_; - float* h_sum_ = nullptr; - float* m_sum_ = nullptr; - int32_t* h_mask_ = nullptr; - int32_t* m_mask_ = nullptr; - const float* weights_ = nullptr; - int token_begin_ = 0, tokens_ = 0; -}; -} // namespace strata::core diff --git a/include/strata/core/remote_experts.hpp b/include/strata/core/remote_experts.hpp deleted file mode 100644 index 224d24f..0000000 --- a/include/strata/core/remote_experts.hpp +++ /dev/null @@ -1,89 +0,0 @@ -#pragma once - -#include "strata/core/expert_cache.hpp" -#include "strata/core/expert_source.hpp" - -#include - -#include -#include -#include -#include - -namespace strata::core { -class RemoteExpertOpt; - -/// A static, profile-filled expert tier on another CUDA device. CUDA0 keeps all -/// dense weights and state; results return through the existing pinned CPU rows. -class RemoteExperts { -public: - RemoteExperts() = default; - ~RemoteExperts(); - RemoteExperts(const RemoteExperts&) = delete; - RemoteExperts& operator=(const RemoteExperts&) = delete; - - /// Initialise the device before the host expert arena registers - /// tens of GiB of portable mapped memory with CUDA. - static bool preflight(int device, double& free_gib, std::string& err); - bool open(int device, int slots, int64_t layers, int64_t experts, - const std::vector>& ranked, - const ExpertCache& primary, ExpertSource& source, - std::vector& claimed, std::string& err, bool auto_size = false); - void close(); - - /// `kind` is the primary verifier's classification (-1 = CPU candidate), - /// or null on the one-token path. Entries already served on CUDA0 are excluded. - bool begin(int64_t layer, const float* x, const int32_t* ids, int64_t n_tok, - int64_t k, const int32_t* kind, const int32_t* primary_res, - std::string& err); - bool owns(int64_t index) const { return owned_[(size_t) index] != 0; } - bool optimized_decode() const { return remote_opt_ != nullptr; } - bool finish(float* out, std::string& err); - int64_t resident() const { return cache_.resident(); } - int64_t computed() const { return computed_; } - int64_t launched_layers() const { return launched_layers_; } - double gib() const { return cache_.gib(); } - uint64_t returned_bytes() const { return returned_bytes_; } - uint64_t full_row_bytes() const { return full_row_bytes_; } - /// host time spent in begin() (staging + launches) and in finish() (waiting for this GPU), cumulative - double ms_begin() const { return ms_begin_; } - double ms_wait() const { return ms_wait_; } - -private: - friend class RemoteExpertOpt; - RemoteExpertOpt* remote_opt_ = nullptr; - int device_ = -1; - int64_t n_expert_ = 0; - int32_t groups_ = 0; - int64_t computed_ = 0; - int64_t launched_layers_ = 0; - uint64_t returned_bytes_ = 0; - uint64_t full_row_bytes_ = 0; - double ms_begin_ = 0, ms_wait_ = 0; - ExpertCache cache_; - cudaStream_t stream_ = nullptr; - float* h_x_ = nullptr; - float* h_out_ = nullptr; - void* h_meta_ = nullptr; - float* d_x_ = nullptr; - float* z_x_ = nullptr; ///< h_x_ as the helper GPU sees it (zero-copy: no input copy per layer) - float* z_out_ = nullptr; ///< h_out_ as the helper GPU sees it (zero-copy: no result copy) - bool zero_copy_ = false; - float* d_out_ = nullptr; - uint8_t* d_q8_ = nullptr; - float* d_scales_ = nullptr; - void* d_scratch_ = nullptr; - void* d_meta_ = nullptr; ///< one contiguous upload of grouped indices, instead of five small copies - int32_t* d_start_ = nullptr; - int32_t* d_dst_ = nullptr; - int32_t* d_tok_ = nullptr; - int32_t* d_count_ = nullptr; - unsigned long long* d_ptr_ = nullptr; - std::vector owned_; - std::vector layers_present_; - std::vector group_of_, group_id_; - std::vector start_, dst_, tok_, original_row_; - std::vector ptr_; -}; - -} // namespace strata::core diff --git a/include/strata/core/session.hpp b/include/strata/core/session.hpp deleted file mode 100644 index 4d63320..0000000 --- a/include/strata/core/session.hpp +++ /dev/null @@ -1,436 +0,0 @@ -// include/strata/core/session.hpp - ONE TOKEN through all 48 layers, and the doorbell protocol between them. -// -// P2.S5's host loop, and the first place the engine runs a whole forward pass rather than one block. What it -// owns is the ORDER across layers and the state that outlives a layer: -// -// * the gated residual stack `R` - (hc, n_embd), which every block reads and writes; -// * 12 QSA states (KV cache + indexer) and 36 GDN states (recurrence + conv history), because `is_qsa_layer` -// splits the 48 layers 12/36 and the two kinds of state have nothing in common; -// * the per-token expert handoff, which is where the CPU pool meets the GPU. -// -// WHY THE LAYER GRAPHS ARE CAPTURED AND THE LOOP IS NOT. A graph bakes in its arguments, so the graph unit is -// ONE LAYER: everything per-token (the position, the step counts) arrives through fixed-address device buffers -// (rounds 211-214), and the HOST decides when each layer runs. That decision is the whole point - it is what -// lets the CPU expert pool start while the GPU is still working on the next layer. -#pragma once - -#include "strata/core/hit_hook.hpp" -#include "strata/core/layer.hpp" -#include "strata/kernels/cpu/pool.hpp" - -#include - -#include -#include -#include - -namespace strata::core { - -/// Everything a sequence needs that is NOT a weight: the per-layer state, the block scratch, and the pinned -/// handoff between the GPU and the CPU expert pool. -struct SessionState { - int64_t max_cells = 0; - - GdnBuffers gdn; ///< the 36 GDN layers share one set of scratch; their STATE is per layer - float* gdn_state = nullptr; ///< (n_gdn_layers, gdn_state_floats) - - QsaState* qsa_states = nullptr; ///< one per QSA layer - void* qsa_state_arena = nullptr; - QsaBuffers qsa_bufs; ///< scratch, shared across the 12 (they never run concurrently) - void* qsa_buf_arena = nullptr; - - MoEBuffers moe; - void* moe_arena = nullptr; - BlockBuffers block; - void* block_arena = nullptr; - - float* R = nullptr; ///< alias of `block.R`, named for what it means at this level - int64_t k = 10; ///< experts per token - - // **THE LAYER-RANGE CARVE (multi-GPU).** A split stage's session used to carve state for ALL 48 layers - // (every QSA KV pool at max_cells, every GDN recurrence) while running only its slice - the same - // whole-model-sized-buffer disease the QSA chunked-prefill PR cured upstream. A session now owns - // [layer_lo, layer_hi): `qsa_states`/`gdn_state` keep GLOBAL ordinal indexing, the arrays simply hold - // fewer rows, so per-layer consumers subtract `gdn_ord0`, and every old model-level `qsa_states[0]` use - // (the shared RoPE table, the prefill staging identity, the MTP rope borrow) reads `qsa_states[primary]`. - // A range with no QSA layer still carves ONE primary state so those model-level uses stay valid. - int64_t layer_lo = 0, layer_hi = 0; ///< resolved by `session_init` (hi = n_layers for the full range) - int64_t qsa_ord0 = 0; ///< global QSA ordinal of the first allocated state - int64_t qsa_alloc = 0; ///< allocated QSA states (>= 1 whenever the model has any) - int64_t gdn_ord0 = 0; ///< global GDN ordinal of `gdn_state` row 0 - int64_t gdn_alloc = 0; ///< allocated GDN rows - int qsa_primary() const { return (int) qsa_ord0; } - /// The doorbell the host loop polls. Null until a caller provides one - the engine runs without it, and - /// neither `session_token` nor `session_replay` looks at it. - const Doorbell* db = nullptr; - - // ================================ THE PLE, AND IT IS SEQUENCE STATE ================================ - // - // **THE PLE IS A LAYER-1 MODULE AND THIS ENGINE DID NOT RUN IT, WHICH IS WHY C1 FAILED** (LEDGER L123). - // Every part of it was already built and parity-tested - the hash against `ref/ngram.py` with the - // artifact's own constants, the IQ4_NL row read against numpy over the original GGUF, and the block - // against ggml's own graph - and none of it was ever called from the model path. These fields are what - // was missing on the state side. - // - // `ple_prev` is the last two tokens OLDEST FIRST with `-1` where there is none, which is exactly - // `ngram_rows`' `prev` argument; `ple_token` is the token being decoded. **They are advanced by the - // DRIVER, once per token**, because the hash is a function of the sequence and not of a layer. - int32_t ple_prev[2] = {-1, -1}; - int32_t ple_token = -1; - /// `NG_HIST` rows of `hc_dim` NORMALIZED history, **ROW-FASTEST**: `ple_hist[row + NG_HIST*channel]`. - /// That is `ggml_reshape_3d(state, d_conv-1, conv_channels, n_seqs)`, not a layout choice - the transposed - /// reading fails ggml's own assert (`ple_layer_xcheck.cpp` L79-83). - float* ple_hist = nullptr; - /// **THE WHOLE PLE RUN LIVES HERE, AND THAT IS NOT A CONVENIENCE.** Its history and its token window are - /// sequence state, so the session is where they belong - and putting the rest of it here too means - /// `session_capture`/`session_loop`/`session_token` need no new parameter to reach it. A `PleRun` whose - /// `ready()` is false is skipped, which is what every caller had before LEDGER L123. - PleRun ple; -}; - -/// Bytes for a whole session at `max_cells` of context. Every layer's state is sized at once, because P2.T10 -/// requires ZERO token-path allocations - a `cudaMalloc` that happened on the first token of a longer sequence -/// would satisfy every test here and fail that one. -/// -/// [layer_lo, layer_hi) carves only that range's per-layer state (a split stage runs a slice of the model); -/// the default full range is byte-identical to the old whole-model carve. Pure arithmetic - safe to call for -/// a candidate range before anything is allocated, which is how the layer-split search prices a placement. -uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k, int64_t layer_lo = 0, - int64_t layer_hi = -1); -/// Carves `base` (DEVICE memory) into `s`. Returns the bytes used. Same range convention as `session_bytes`. -uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void* base, SessionState& s, - int64_t layer_lo = 0, int64_t layer_hi = -1); -/// Before the memory `session_init` carved is freed: forgets what points into it from outside the session (the -/// rope kernels' registered angle table, #280), so a later session never rotates by freed memory. -void session_release(SessionState& s); -/// Zeroes every layer's state - the residual to `R_init`, everything else to zero, so a fresh sequence starts -/// from the reference's own `zeros()`. -void session_zero(SessionState& s, const ModelGeometry& g, const float* R_init, void* stream); - -/// One token: layers 0..47 in order, each a `block_layer`, and the residual is updated in place. -/// -/// `parts` is (k, n_embd) DEVICE memory, filled by the caller - by the CPU expert pool and the VRAM-resident -/// experts. In this phase `moe_layer` consumes it directly; the doorbell protocol's job is to let it be -/// produced DURING the layer rather than before it, which is a change to *when* the host runs, not to what this -/// function computes. -/// -/// `sync_every_layer` inserts a device synchronisation and an error check after EVERY layer. That is the -/// `--sync-every-layer` debug mode, and it is deliberately a parameter rather than a compile-time choice: the -/// errors it catches (a kernel reading a buffer that a later layer writes) are invisible otherwise, and the -/// synchronisation it costs is exactly what P2.X3 forbids in the fast path. -bool session_token(const WeightTable& tables, const ModelGeometry& g, int64_t pos, int32_t pos_base, - SessionState& s, const float* parts, void* stream, bool sync_every_layer, - std::string& err); - -// ================================ the captured form ================================ - -/// ONE GRAPH PER LAYER, because a graph bakes in its POINTERS and every layer has different weights AND -/// different state. That is not a limitation to work around - it is what makes the per-layer graph the right -/// unit: the host decides when each layer runs, which is what lets the CPU expert pool start while the GPU is -/// still working on the next one. -/// -/// WHY THIS IS WORTH DOING, MEASURED: **the engine is launch-bound, not bandwidth-bound.** Every kernel in -/// `gdn_layer` measured ~0.028 ms - including `gdn_gate`, which processes FORTY-EIGHT elements, and a kernel -/// cannot execute for 28 us. That is what a null-stream launch costs on this driver, and `gdn_layer` makes ~19 -/// of them while a block makes ~45. Replaying the 43-node block graph measured **1.585 ms against 2.393 ms** -/// for the same work as direct launches - a 1.51x that is pure launch overhead. -struct SessionGraphs { - cudaGraphExec_t* execs = nullptr; ///< one per layer, in layer order - int64_t n = 0; - /// **THE SECOND GRAPH PER LAYER: `moe_finish` + `gr_write`, launched AFTER the host has run the pool.** - /// - /// Without it the loop has to hand layer `l`'s expert vectors to layer `l+1`, which multiplies them by - /// layer `l+1`'s router weights - see `layer.hpp`'s note on `moe_route`. With it, `post[l]` is launched - /// after the pool returns, so layer `l`'s experts are combined with layer `l`'s weights. - /// - /// The cost is the overlap, and it is worth stating: the window is now whatever GPU work follows the ring - /// inside `pre[l]` - the shared expert, and nothing else, because everything after the combine depends on - /// `parts`. **A per-layer CPU pool cannot be hidden behind a strictly serial residual chain**, which is - /// why the CPU term is answered by Phase 3's VRAM cache and not by this pipeline. - cudaGraphExec_t* posts = nullptr; - bool captured = false; - /// THE DEVICE ADDRESS THE GRAPHS WERE CAPTURED WITH. The host loop copies each layer's expert outputs - /// here before launching the next layer, and a graph bakes the POINTER, so it has to be this one. - float* parts_dev = nullptr; - - /// **DIAGNOSTIC, AND IT IS THE ONE THAT SAYS WHETHER THE DOORBELL IS DECORATIVE.** - /// - /// Counts the layers where the ring was observed while the graph was STILL RUNNING - i.e. the layers where - /// the pool actually had a window to work in. A nonzero `h_seq` read at the same moment - /// `cudaEventQuery` returns `cudaSuccess` means the layer was already over, and the pool then runs with the - /// GPU IDLE, which makes the whole pipeline equivalent to a serialised one. - /// - /// That distinction is invisible in the loop's RETURN VALUE - both paths produce a correct token - and it - /// is invisible in a per-layer timing, because the layer still takes the same time either way. It shows up - /// only as "the overlap hides nothing", which is why it is counted here. - int64_t rings_mid_graph = 0; - - /// **THE WINDOW, MEASURED RATHER THAN ASSUMED.** Milliseconds from `cudaGraphLaunch` to the moment the - /// ring was observed, summed over the loop. The pool's window is `layer period - this`, and that is the - /// entire budget the overlap has: if the CPU's per-layer work exceeds it, the GPU goes idle for the - /// difference on every layer and a "pipelined" loop measures the same as a serialised one. - /// - /// It is NOT the same as the doorbell's position inside the graph. It includes the launch itself, the - /// driver's submission, and however long the host took to notice - all of which are real and none of which - /// the pool gets to use. - double ms_to_ring = 0; - - // ================================ R0.9: THE LAYER AS THREE GRAPHS ================================ - // - // **THE CAPTURED PER-STAGE TABLE THE PROTOCOL HAS DEMANDED SINCE R0 AND NOBODY HAS HAD.** Round 309's - // came from `--no-capture`, and round 312 showed its `moe_finish` figure was a host-gap artefact four - // times the captured cost of the same work - so the plan has been choosing between R3.3, R3.4 and R3.5 - // without knowing what any of them is worth. - // - // An event recorded BETWEEN two `cudaGraphLaunch` calls is not inside a capture and is therefore valid, - // so the layer is captured at its own documented seam (`block_layer_pre`'s `half`) and timed from outside. - /// **R0.11: FIVE PREFIX GRAPHS, ADDED BESIDE `preA`/`preB` RATHER THAN REPLACING THEM.** - /// `preP[k]` (k = 1..5) runs stages `0..k-1`. Consecutive differences are the per-stage times, which is - /// what prices the two `gr_read`s and the `gr_write` (R3.3) against GDN's interior (R3.4). A prefix and not - /// a range, because the stages are a chain: stage 1 reads what stage 0 wrote and stage 2 mutates the - /// residual in place. - /// - /// **THE FIFTH PREFIX USED TO BE `execs[l]`, AND THAT WAS THE BUG ROUND 324 COULD NOT FIND.** Prefix 5 - /// has ~7 more nodes than prefix 4, so the two differ in launch setup as well as in execution - and the - /// difference attributed ALL of it to stage 4, the router. Capturing prefix 5 the same way as the others - /// makes the two comparable and the difference purely stage 4's. - cudaGraphExec_t* preP[5] = {nullptr, nullptr, nullptr, nullptr, nullptr}; - cudaGraphExec_t* preA = nullptr; ///< `half == 1`: gr_read -> attention -> gr_write (the MIXER) - cudaGraphExec_t* preB = nullptr; ///< `half == 2`: gr_read -> moe_route (FFN front + ROUTER) - bool split_captured = false; - - /// How many times `session_loop` has run. `rings_mid_graph` and `ms_to_ring` are CUMULATIVE and the loop - /// is called once per token, so anything reporting a ratio needs this - and prefill runs the loop too, so - /// "per generated token" is the wrong denominator. - int64_t calls_total = 0; - - /// **WHERE THE PER-LAYER ROUND TRIP GOES, AND `ms_to_ring` ALONE CANNOT SAY.** - /// - /// `--no-pool` measures **38.73 ms/token against a 26.32 ms pure-GPU floor**, so ~12.4 ms/token - a quarter - /// of the token - is spent in the loop with no expert work at all: 0.258 ms per layer. `ms_to_ring` covers - /// only the first half of that; it stops when the ring is seen, and everything the host then does before - /// the next `pre` is launched is invisible to it. - /// - /// So the round trip is split at the ring, and **`ms_to_ring` above IS the first half** - do not add a - /// second counter for it: - /// - /// * `ms_to_ring` - launch -> ring observed. The GPU is working (or already finished) here. - /// * `ms_host` - ring observed -> `pre[l+1]` launched. **The GPU has nothing queued and is IDLE for - /// all of this unless `pre[l]`'s tail still covers it.** This is - /// `cudaMemcpyAsync(parts)` + `cudaGraphLaunch(post[l])` + `cudaGraphLaunch(pre[l+1])` + - /// `cudaEventRecord`, and if it is the large half then the fix is fewer driver calls - /// (R2.4), not a faster kernel. - /// - /// Cumulative, like `ms_to_ring`; divide by `calls_total * n_layers`. - double ms_host = 0; -}; - -/// Captures all 48 layer graphs. Idempotent: a second call is a no-op. -/// -/// `pos`/`pos_base` are baked in ONLY through the fixed-address pinned staging in each `QsaState`, which the -/// replay re-reads every token - so the position is data, not an argument. That is the whole reason rounds -/// 211-214 moved the per-token counts into device buffers. -bool session_capture(const WeightTable& tables, const ModelGeometry& g, SessionState& s, const float* parts, - SessionGraphs& gr, std::string& err, bool split = false, int64_t layer_lo = 0, - int64_t layer_hi = -1); - -/// One token by REPLAYING the captured graphs. Identical arithmetic to `session_token`; the only difference is -/// that ~2,000 kernel launches become 48 graph launches. -bool session_replay(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, SessionGraphs& gr, - void* stream, std::string& err); - -/// One token by replaying BOTH halves of every layer - `pre[l]` and `post[l]` - with no pool running. -/// -/// **THIS IS THE TRUE PER-TOKEN GPU FLOOR, AND `session_replay` IS NOT.** `session_replay` launches only -/// `gr.execs[l]`, the `pre` graphs, so it omits the 48 `post` graphs (shared expert, combine, second `gr_write`) -/// entirely - and everything published as "39.8 ms pure GPU" came from it while being described as the whole -/// GPU. See `Memory/ERRORS.md` A4. -/// -/// `parts` is left at whatever the buffer holds, because no pool writes it; that is deliberate and makes the -/// measurement pure GPU work. The LM head is NOT included here - the caller times it separately, since it runs -/// on the host-side path rather than inside a captured graph. -bool session_replay_full(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, - SessionGraphs& gr, void* stream, std::string& err); - -/// **ONE TOKEN THROUGH THE SPLIT GRAPHS, WITH EVERY STAGE TIMED FROM OUTSIDE THE CAPTURE.** Requires -/// `session_capture(..., split = true)`. Replays `preA[l]`, `preB[l]`, `post[l]` in order on one stream - -/// the same order `session_loop` uses - and reports the three totals in milliseconds for the whole token. -/// -/// The stages are ordered by the stream, so an event pair around each launch measures that launch's GPU work -/// plus the gap the driver left before it. That gap is real and is why the three totals sum slightly above -/// `session_replay_full`; the comparison is printed by the caller rather than hidden here. -/// **R0.11: THE FIVE STAGES SEPARATELY, BY DIFFERENCING PREFIXES.** `stage_ms` is resized to 5 and holds -/// stages 0..4 in milliseconds for a whole token; `mixer_per_layer` holds prefix 3's time for each layer, which -/// is what R0.10's GDN-versus-QSA split needs. Requires `session_capture(..., split = true)`. -/// -/// **THE RESIDUAL IS SAVED AND RESTORED BETWEEN PREFIXES.** Stage 2 is `gr_write`, which mutates `R` in -/// place, so without the restore every prefix after the first reads a residual the earlier ones already -/// advanced - and every number after the first would be measuring a different tensor while looking correct. -bool session_replay_stage_prefixes(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, - SessionGraphs& gr, void* stream, std::vector& stage_ms, - std::vector& mixer_per_layer, std::string& err); - -/// **R3.5c: ONE PREFIX, ALL 48 LAYERS, BACK TO BACK.** `k` in 1..5 replays `preP[k-1][l]` (or `execs[l]` for -/// k = 5) for every layer with no other graph in between, and reports the whole sweep in milliseconds. -/// -/// **WHY THIS EXISTS: TO RULE OUT THE PREFIX TABLE'S OWN BIAS.** The five-stage table differences prefix -/// times measured with FIVE DIFFERENT GRAPHS LAUNCHED PER LAYER. Stage 4's interval therefore contains the -/// launch of `execs[l]` - the full five-stage graph - while stage 3's contains `preP[3][l]`, a four-stage one. -/// A launch cost that scales with graph size would inflate stage 4 specifically, and stage 4 is the router, -/// which is the thing under investigation. This sweep launches ONE graph type per layer, so there is nothing -/// to switch between and nothing to attribute wrongly. -/// -/// Five separate sweeps give five totals; their consecutive differences are the stage times on the same -/// arithmetic as before, and **if the two methods disagree the difference is the bias and the sweep is right.** -bool session_replay_stage_sweep(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, - SessionGraphs& gr, void* stream, int k, double& ms, std::string& err); - -bool session_replay_stages(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, - SessionGraphs& gr, void* stream, double& ms_mixer, double& ms_ffn, double& ms_post, - std::string& err); - -/// **THE SAME REPLAY, KEEPING EVERY LAYER INSTEAD OF SUMMING THEM.** -/// -/// The 48 layers are not 48 of the same thing: 36 are GDN and 12 are QSA, and the mixer - 55.8% of the GPU -/// floor - contains both. A total cannot separate them; a per-layer vector can, and it is already being -/// measured. `out` is resized to `n_layers` and holds each layer's mixer time in milliseconds. -/// -/// **THIS IS THE CHEAPEST HALF OF R0.10 AND IT NEEDS NO NEW SPLIT.** Round 309's uncaptured table put GDN at -/// 10.88 ms for 36 layers and QSA at 4.56 for 12, which would make the recurrence the largest single R3 -/// target; that table also had `moe_finish` wrong by 4x, so the ratio is worth re-deriving from the captured -/// graph rather than inherited. -bool session_replay_stages_per_layer(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, - SessionGraphs& gr, void* stream, std::vector& mixer_per_layer, - double& ms_ffn, double& ms_post, std::string& err); - -/// Releases the graph execs. The `SessionGraphs` struct holds no device memory of its own. -void session_graphs_free(SessionGraphs& gr); - -// ================================ THE HOST LOOP ================================ - -/// WHAT THE POOL HAS TO DO, as the loop sees it: given the `x_f` a layer published and the miss list it -/// selected, produce the `k` expert outputs into `out` (k x n_embd, HOST memory). A function pointer rather -/// than a virtual class because the loop is the thing under test and the pool is the thing being faked. -using PoolFn = void (*)(void* user, const float* x_f, const int32_t* ids, const float* weights, int64_t n_embd, - int64_t k, float* out); - -/// **R4.2c: THE VRAM-RESIDENT HALF OF THE LAYER'S EXPERTS.** Called by the loop after the misses have been -/// staged into `parts` and before `post[l]` is launched, so its kernels are stream-ordered between them: the -/// misses are already in `parts`, the hits overwrite the rows the CPU zeroed, and `post[l]`'s `moe_combine` -/// reads the sum and cannot tell which engine produced which row. -/// -/// **WHY IT IS A CALLBACK RATHER THAN MORE PARAMETERS.** `session_loop` owns the ORDER across layers and has -/// no business knowing what an expert cache is. Everything the hit path needs lives on the caller's `user`, -/// and this has the same shape as `PoolFn` for the same reason. -/// -/// A null pointer means "no VRAM tier" - the default, and what every caller had before R4. -// The hit hook's type lives in its own header - see `hit_hook.hpp` for why and for the ordering it wants. - -/// `phases/phase-2-correct-engine.md` P2.S5's host loop, which is the point of everything above it: -/// -/// launch G[l] -> poll the doorbell -> read the miss list -> dispatch the pool -> wait for it -> -/// write y_miss -> launch G[l+1] -/// -/// **NO `cudaStreamSynchronize` IN THE LOOP**, which is P2.X3. Waiting is `cudaEventQuery` on an event recorded -/// right after the launch - a QUERY, and it is not optional: round 195 measured a host spin that only read -/// memory never running the kernel at all, 5,907,703 spins over 500 ms with the datum flipping only when -/// `cudaStreamSynchronize` was called. -/// -/// **THE OVERLAP IS THE ONE-LAYER DELAY.** A layer publishes `x_f` at ~71% of its own duration, so the pool has -/// the remaining 29% of that layer to work in; its result is consumed by the NEXT layer, which is why the -/// combine is not waiting on it. `overlap = false` runs the same sequence with a synchronisation after every -/// layer, which is the comparison that says whether the pipeline is worth its complexity - and it is a -/// parameter rather than a second function so that the two cannot drift. -/// -/// **`dump_layers`, WHEN NOT NULL, IS THE C1 ORACLE AND IT IS A HOST BUFFER OF `(n_layers + 1) * hc * n_embd` -/// FLOATS.** Slot 0 is the residual the function was ENTERED with - the token's embedding broadcast to every -/// stream, which is the reference's `hc_init` node - and slot `l + 1` is `s.R` after layer `l`, which is the -/// reference's `l_last-`. Each is enqueued as a device-to-host copy, and the final `cudaStreamSynchronize` -/// at the end of the loop is what makes every one of them complete. **NO EXTRA SYNCHRONISATION IS INSERTED**, -/// which is the whole reason this is written as an enqueue rather than a read: `pre[l+1]` does not write `R` and -/// `post[l+1]` is launched after the copy on the same stream, so FIFO order alone makes slot `l + 1` a true -/// snapshot. It costs 40 KB per layer per token, and it is the only way to bisect the engine against the -/// reference layer by layer instead of against one end-to-end perplexity. -/// Per-token scratch that MUST NOT be reallocated per token (P2.T10, review finding H3). -/// -/// **`session_loop` IS CALLED ONCE PER TOKEN, SO ANYTHING IT ALLOCATES IS A PER-TOKEN ALLOCATION.** It used to -/// allocate three things on every token of every run: -/// -/// * `cudaHostAlloc` for the pool's pinned staging, freed by an RAII destructor at the end of the call - and -/// `cudaFreeHost` IMPLICITLY SYNCHRONISES THE DEVICE, so every token ended with a device sync; -/// * `cudaEventCreate` / `cudaEventDestroy` for the doorbell probe; -/// * a host-affinity change (`physical_cores` + pin + restore). -/// -/// A comment in the old code said "allocated once", but once per token is not once. -/// -/// Own one of these at session setup and pass it in. **Passing `nullptr` keeps the old behaviour** - the loop -/// allocates and frees locally - so every existing caller and test is unaffected, but the allocation is then -/// visible at the call site instead of hidden inside a hot function. -struct SessionLoopScratch { - float* y_miss = nullptr; ///< pinned host staging for the pool's answer, `parts_bytes` long - size_t parts_bytes = 0; - cudaEvent_t probe = nullptr; - strata::kernels::cpu::ThreadAffinity pinned_core{}; ///< affinity to restore, or invalid if the host was not pinned - bool pinned = false; - - /// Allocates the buffers and pins the host thread. Call ONCE, at session setup. - bool init(size_t parts_bytes_in, std::string& err); - /// Frees everything and restores the affinity. Safe to call twice, or on a default-constructed object. - void free(); -}; - -bool session_loop(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, SessionGraphs& gr, - PoolFn pool, HitFn hits, void* user, bool overlap, void* stream, std::string& err, - float* dump_layers = nullptr, SessionLoopScratch* scratch = nullptr); - -// ================================ plan v0.3 P3: THE WHOLE TOKEN AS ONE GRAPH ================================ -// -// Under WDDM every graph launch costs ~0.3-0.4 ms of submission latency, and the per-layer loop above makes 96 -// of them per token: measured 48.6 ms/token for 12 ms of GPU kernels and 27 ms of pool. The token graph holds -// all 48 layers. Between `pre[l]` (which rings the doorbell) and the parts copy, a one-thread kernel waits ON -// THE DEVICE until the host writes the ring value into `db.h_flag`; the host only polls rings, runs the pool -// and writes flags, with no driver call in the loop (bench/micro/device_wait.cu: 5.2 us per handoff). -// -// for l: pre[l] (.. router, doorbell ring, shared expert) -> doorbell_wait -> parts <- y_miss (H2D) -// -> post[l] (combine, gr_write) -// -// Same kernels, same order per layer as `session_loop`, so the token is bitwise the same. No VRAM expert tier -// yet (the hit decision is a host step between ring and post); the caller falls back to `session_loop` then. -struct TokenGraph { - cudaGraphExec_t exec = nullptr; - bool captured = false; - int64_t n_layers = 0; - const float* y_src = nullptr; ///< the pinned host staging the graph's H2D copies read (baked in) - size_t parts_bytes = 0; - int64_t calls = 0; - double ms_wait = 0; ///< host waiting for rings (the GPU is running) - double ms_pool = 0; ///< host inside the pool - int64_t flushes = 0; ///< cudaStreamQuery calls made because a ring was slow to appear -}; - -/// Plan v0.3 P4: the VRAM expert tier inside the token graph. Residency is STATIC during a token (a -/// `n_layers x n_expert` table, slot or -1, on the device; the host pool reads its own copy), so the hit list -/// is built on the device right after the ring and the hits run while the CPU computes the misses. -struct TokenHits { - const int32_t* d_res = nullptr; ///< device [n_layers * n_expert] - int64_t n_expert = 0; - const uint8_t* cache_base = nullptr; ///< slot 0 of the VRAM expert arena - int64_t blob = 0; ///< bytes per slot - int32_t* d_slot = nullptr; ///< device, k entries - int32_t* d_dst = nullptr; ///< device, k entries - int32_t* d_count = nullptr; ///< device, 1 - uint8_t* x_q8 = nullptr; ///< the activation's q8_0 blocks, (n_embd/32)*34 B - float* x_scale = nullptr; ///< and its fp32 scales (the CPU pool's contract) - void* scratch = nullptr; ///< moe_hit_grouped_scratch_bytes(k, ...) - float* hit_out = nullptr; ///< device, k * n_embd - bool on() const { return d_res && cache_base && d_slot && d_dst && d_count && x_q8 && x_scale && scratch && hit_out; } -}; - -bool session_capture_token(const WeightTable& tables, const ModelGeometry& g, SessionState& s, float* parts_dev, - const float* y_miss_host, size_t parts_bytes, TokenGraph& tg, std::string& err, - const TokenHits* hits = nullptr); -bool session_run_token(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, TokenGraph& tg, - PoolFn pool, void* user, float* y_miss_host, void* stream, std::string& err); -void token_graph_free(TokenGraph& tg); - -} // namespace strata::core diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp deleted file mode 100644 index 3262503..0000000 --- a/include/strata/core/verify.hpp +++ /dev/null @@ -1,371 +0,0 @@ -// include/strata/core/verify.hpp - plan v0.3 P6: the speculative VERIFY window. -// -// T tokens at consecutive positions p0 .. p0+T-1 - the last accepted token and T-1 drafts - go through all 48 -// layers in ONE captured graph, and the head's argmax is produced for every one of them. Token t's argmax is -// what plain greedy decode would produce after token t, BIT FOR BIT: every kernel here is either the single-token -// kernel applied per token, or a multi-token kernel whose per-token arithmetic is the single-token kernel's -// (multi-column MMVQ in exact mode, the T-token GDN kernels, the per-token hit activation, the multi-token CPU -// expert rows). So a draft is accepted exactly when greedy decode would have produced it. -// -// What the window costs is the dense weights read ONCE for T tokens and the union of the T tokens' missed -// experts on the CPU (measured on decode traces: 1.75x one token's misses for T=2, 2.4x for 3, 3.05x for 4). -// -// STATE. The window appends K/V and indexer keys for all T positions and leaves the GDN state untouched. -// `commit(n_keep)` then makes the first `n_keep` tokens permanent: the GDN conv history and recurrent state are -// advanced by replaying those tokens from inputs the window stored, the indexer's key tail is restored from a -// snapshot and the accepted keys re-appended (a rejected key can land in a slot the current block still needs), -// and the PLE history is set to its snapshot after token n_keep-1. K/V cells past the accepted prefix are simply -// overwritten when those positions are processed again, before any query can read them. -// -// Requires the default native decode configuration (native projections, fused GR, fused GDN, fast attention and -// selection, native indexer) and a profile-filled VRAM expert tier with its residency table on the device. -#pragma once - -#include - -#include "strata/core/expert_source.hpp" -#include "strata/core/layer.hpp" -#include "strata/core/session.hpp" -#include "strata/kernels/sampler.hpp" - -#include - -#include -#include -#include -#include -#include -#include - -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); - -struct VerifyHits { - const int32_t* d_res = nullptr; ///< device [n_layers * n_expert] slot or -1 - const int32_t* h_res = nullptr; ///< host [n_layers * n_expert] slot or -1 (when all >= 0 in stage: zero-doorbell) - const uint8_t* cache_base = nullptr; ///< slot 0 of the VRAM expert arena - const uint64_t* slot_off = nullptr; ///< E-6: host per-slot offsets when slots differ in size (null: slot * blob) - int64_t n_slots = 0; ///< E-6: how many (for the device copy) - int64_t blob = 0; -}; - -class Verifier { -public: - Verifier() = default; - ~Verifier(); - Verifier(const Verifier&) = delete; - Verifier& operator=(const Verifier&) = delete; - void set_remote_expert_opt(RemoteExpertOpt* opt) { remote_opt_ = opt; } // before init/capture - - /// The watchdog's view of the window in flight (issue #31): the layer, the GPU's sequence, the flags. - void diag(std::FILE* f) const; - /// #649 (STRATA_VERIFY_TRACE=1, opt-in): the last windows' host-side handshake events and the GPU's breadcrumbs - /// (in mapped memory, so they read while the GPU hangs). Nothing when the trace is off. - void trace_dump(std::FILE* f) const; - - /// #267: raise every flag the window's spin kernels wait on past any ring (UINT32_MAX), so a window the GPU - /// cannot finish drains instead of staying resident, then wait up to `timeout_ms` for its streams. For the - /// paths that give up on the engine (a timed-out window, the serve watchdog): the window then ran on whatever - /// the flags guarded, so this verifier refuses every later window. True when the streams finished. - bool release_gpu_waits(int timeout_ms); - - /// `max_t` <= kVerifyMaxT. `head` may be null (the canonical head is then run per token). - bool init(const WeightTable& wt, const ModelGeometry& g, SessionState& ss, const VerifyHits& hits, - const NativeHead* head, int max_t, std::string& err); - - /// One window: `tokens[0..T)` at positions pos0.., the pool served per layer; `out[t]` = argmax after token t. - /// The PLE rows are gathered here from `ss.ple_prev` and the tokens. Captures the T-token graph on first use. - bool run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, void* user, int32_t* out, std::string& err); - /// Diagnostics: row `t` of the last window's head logits (n_vocab floats) to the host. Valid after run(). - bool copy_logits(int t, float* host) const; - int64_t vocab() const { return next_ ? next_->vocab() : n_vocab_; } - /// The sampling the verify window's head applies (temperature / top_p / top_k / seed). Set per - /// request; greedy by default. The sampling itself runs OUTSIDE the captured graph - its - /// parameters would otherwise be baked forever - so this can change between requests freely. - void set_sampling(const strata::kernels::SamplerParams& sp) { - sampling_ = sp; // row t of a window at pos0 draws Philox(seed, pos0 + t): see run() - if (next_) next_->set_sampling(sp); - } - - /// The penalty histories for `sampling_.penalty_last_n`: ONE ROW PER WINDOW ROW, T rows of `history_len` - /// int32 slots at that stride (`strata::kernels::penalty_rows` builds them), most recent token LAST, unused - /// front slots -1 (the kernel reads only the tail window). Row t follows the window's drafts 1..t - staging - /// row 0 alone (before 0.1.19) left the drafted rows with unwritten histories. Null disables the penalties - /// entirely - the neutral run's sampling call is byte-for-byte what it was. The engine re-uploads the rows - /// before every window; the buffer must hold kVerifyMaxT rows and stay alive across the request. - void set_history(const int32_t* history, int history_len) { - hist_d_ = history; - hist_len_ = history_len; - if (next_) next_->set_history(history, history_len); - } - /// Off: `run` skips the request's head sampling and `out` is the recorded greedy pick. For windows whose - /// picks are discarded - a prompt read through windows commits every token - so they cost no sampler launch - /// or sync and never read a history staged for another position. - void set_head_sampling(bool on) { head_sampling_ = on; if (next_) next_->set_head_sampling(on); } - - /// LAYER SPLIT (multi-GPU): this verifier runs layers [layer_begin, layer_end) of every window. A stage that - /// does not start at layer 0 takes its residual from `handoff_in` instead of embedding the tokens; a stage that - /// does not end at the last layer writes its residual to `handoff_out` and has no head. The hand-off holds, - /// per token, the residual R (hc x n_embd), the last layer's pending write bo (n_embd) and inject (hc): the next - /// stage folds that write into its first read exactly as the unsplit window does, so the split is bit-exact. - /// Both pointers must be device-visible (mapped pinned memory, portable when the stages are on two devices). - /// Set before `init`. Default: the whole model, no hand-off. - void set_stage(int64_t layer_begin, int64_t layer_end, const float* handoff_in, float* handoff_out) { - lb_ = layer_begin; le_ = layer_end; hand_in_ = handoff_in; hand_out_ = handoff_out; - } - /// The next stage: `run` and `commit` continue into it (its pool calls get `next_user`); sampling settings - /// and `final_R` are the last stage's. - void set_next(Verifier* next, void* next_user) { next_ = next; next_user_ = next_user; } - /// floats per token in a hand-off buffer - static int64_t handoff_floats(const ModelGeometry& g) { return (int64_t) g.hc * g.n_embd + g.n_embd + g.hc; } - - /// Keep the first `n_keep` (1..T) tokens of the last window; advances `ss.ple_prev` by them. - bool commit(int n_keep, std::string& err); - - // ================================ SEVERAL SEQUENCES IN ONE WINDOW ================================ - // - // A batch window holds S INDEPENDENT sequences, one token each: row s is slot s, at slot s's own position, - // reading and writing slot s's own state (GDN recurrence and conv history, QSA K/V and indexer, PLE history), - // which lives in `slots[s]` - a session carved like this verifier's own (same layer range, same max_cells). - // Everything that is per row already (hyper-connections, dense projections, router, shared expert, the - // routed experts on the GPU and the CPU, the head) runs once over the S rows, so the weights are read once - // per window for all the sequences. Row s's arithmetic is the single-token window's, so a slot's greedy - // tokens are its solo greedy tokens (modulo the multi-token CPU kernel choice: STRATA_IQ_MT_MIN=1). - // - // Greedy only, no drafts (MTP) in a batch window. `init_slots` once after `init` (S <= max_t); a layer - // split's stages each get their own sessions, and run_slots/commit_slots continue into the next stage. - bool init_slots(const std::vector& slots, std::string& err); - int n_slots() const { return (int) slots_.size(); } - /// One batch window over slots [0, S): tokens[s] at positions pos[s]; out[s] = the greedy pick after it. - bool run_slots(int S, const int32_t* tokens, const int64_t* pos, PoolMultiFn pool, void* user, int32_t* out, - std::string& err); - /// The same over the S slots `rows` (row t is slot rows[t], any distinct slots in any order): the slots not - /// listed are not touched, so an idle slot keeps its state (a finished conversation it may continue later). - bool run_slot_rows(const int* rows, int S, const int32_t* tokens, const int64_t* pos, PoolMultiFn pool, void* user, - int32_t* out, std::string& err); - /// Keep every row of the last batch window: each slot's state advances by its one token. - bool commit_slots(std::string& err); - - // ---- The stages of a layer split as a PIPELINE. A batch window over the slot GROUP - // [base, base + S) is launched on ONE stage with its commit right behind it on the stage's stream (a batch window - // keeps every row, so the commit needs no host decision), and the host serves the rings of every stage that has - // a window in flight from one thread (batch_poll does not block). Stage k can then run group g while stage k+1 - // runs group g-1. Rows of group `base` use hand-off rows [base, base + S), so groups never share a hand-off row. - bool batch_launch(int base, int S, const int32_t* tokens, const int64_t* pos, std::string& err); - /// 1 = this stage's window and commit are done (the last stage's picks are in batch_out), 0 = still running, - /// -1 = an error (err). Serves every layer that has rung so far. - int batch_poll(PoolMultiFn pool, void* user, std::string& err); - bool batch_busy() const { return b_running_; } - /// A slot's sampling (temperature / top_p / top_k / min_p / seed; penalties are not applied in batch windows): - /// its row is drawn again on the last stage with Philox(seed, position), as a solo window draws it. Greedy by - /// default. Set on the first stage, it reaches the last. - void set_slot_sampling(int slot, const strata::kernels::SamplerParams& sp) { - if (slot >= 0 && slot < (int) slot_sp_.size()) slot_sp_[(size_t) slot] = sp; - if (next_) next_->set_slot_sampling(slot, sp); - } - const int32_t* batch_out() const { return b_out_; } - bool last_stage() const { return g_ != nullptr && le_ == g_->n_layers; } - /// commit() returns without waiting for its graph (a single-GPU session sets it): the next window follows it on - /// the same stream and the drafter reads nothing it writes, so it overlaps the draft. Whoever reads or writes - /// the session from another stream or the host afterwards (a new request, a checkpoint, a snapshot, the prompt - /// path, the end of a run) calls wait_commit() first. STRATA_COMMIT_SYNC=1 keeps the wait. - static void set_commit_async(bool on); - /// Waits for the last commit graph when commit() did not (an event recorded after it, not the whole device); - /// false with `err` when it failed. Free when nothing is pending. - bool wait_commit(std::string& err); - - /// Measurement hook (STRATA_LOGPOS): after run(), write one line per row t of the last window's head - - /// "pos target logprob top top_logprob hit extra_logprob target_logprob_without_extra" - where row t is the - /// distribution at pos0 + t, targets[t] is the token at pos0 + t + 1, extra_logprob is the log-probability of - /// `extra_id` in the same row, and the last column is the target's log-probability in that row renormalized - /// over every token but `extra_id` (both nan when they do not apply). A layer split's earlier stage forwards - /// to the stage that holds the head. - bool window_logprobs(const int32_t* targets, int T, int64_t pos0, int32_t extra_id, std::FILE* out, - std::string& err); - - /// Token t's residual after the last layer, (hc, n_embd) on the device, valid until the next `run`. - const float* final_R(int t) const; - const float* final_R_all() const { return next_ ? next_->final_R_all() : R_; } - - /// The GPU plan the pool writes each layer (VRAM hits + the PCIe share of the misses); give it to the - /// dispatch (`ExpertDispatch::plan`) before the first `run`. - GpuPlanSink* plan_sink() { return &sink_; } - /// Plan v0.3 P6: split the window into two token groups and pipeline the CPU experts of one with the GPU work - /// of the other (default on). Set before the first `run`. - void set_split(bool on) { split_ = on; } - /// Plan v0.3 P6: how the PCIe share of the misses reaches the GPU: 0 = DMA into staging (the copy engine works - /// beside the CPU; best when the CPU is compute-bound, the i-quants), 1 = the grouped kernel reads the mapped - /// arena directly, 2 = a copy kernel stages it inside the graph (no API calls on the pool's thread; best when - /// the CPU is RAM-bound, Q2_0). Set before the first `run`. - void set_pcie_mode(int mode) { sink_.pcie_mode = mode; } - /// the pool never plans a PCIe share (--pcie-frac 0): the window skips that path. Before the first run. - - double ms_wait = 0, ms_pool = 0, ms_host = 0, ms_commit = 0; - int64_t windows = 0; - /// STRATA_VERIFY_PROFILE=1 - GPU stage times of the windows since the last call (ms per - /// window), as one line; empty when off. - std::string profile_report(); - -private: - RemoteExpertOpt* remote_opt_ = nullptr; - bool capture(int T, std::string& err); - // batch windows (see init_slots) - std::vector slots_; - bool batch_rec_ = false; ///< record_window is capturing a batch window - int row_base_ = 0; ///< ... its hand-off rows start here (a pipeline group's own rows) - int brow_[8] = {}; ///< ... and row t is slot brow_[t] - bool last_batch_ = false; ///< the last run was a batch window (set_plan_slot: one group) - std::map exec_bm_, commit_bm_; ///< key: batch_key(rows, S, hand-off base) - int last_rows_[8] = {}; ///< the slots of the last batch window's rows - static uint64_t batch_key(const int* rows, int S, int hbase) { - uint64_t k = (uint64_t) hbase << 40 | (uint64_t) S << 32; - for (int t = 0; t < S; ++t) k |= (uint64_t) (rows[t] & 15) << (4 * t); - return k; - } - // batch_launch / batch_poll - bool b_running_ = false; - int64_t b_k_ = 0, b_steps_ = 0; - std::chrono::steady_clock::time_point b_last_; - int32_t b_out_[8] = {}; - std::vector slot_sp_; - bool sample_rows(int S, std::string& err); ///< the sampled slots' rows of the last batch window - int32_t* h_commitb_ = nullptr; int32_t* m_commitb_ = nullptr; // per slot [1, 0, pos, -1 ..], stride 2 + max_t - int32_t* commitb_ = nullptr; - float* tail_snap_b_ = nullptr; ///< per (slot, QSA layer) indexer tail snapshot - void* arena_b_ = nullptr; - int64_t last_pos_b_[8] = {}; - bool capture_batch(const int* rows, int S, int hbase, std::string& err); - void collect_profile(); ///< STRATA_VERIFY_PROFILE: add the last window's stamps to prof_sum_ - bool capture_commit_batch(const int* rows, int S, int hbase, std::string& err); - bool stage_batch(const int* rows, int S, int hbase, const int32_t* tokens, const int64_t* pos, std::string& err); - strata::kernels::SamplerParams sampling_ = [] { - strata::kernels::SamplerParams s; - s.greedy = true; - s.temperature = 0.0f; - return s; - }(); ///< greedy by default; per-request via set_sampling - const int32_t* hist_d_ = nullptr; ///< penalty-history row (set_history); null = no penalties apply - int hist_len_ = 0; - bool head_sampling_ = true; ///< set_head_sampling - int device_ = -1; ///< the device `init` ran on: run/commit switch to it (layer split) - std::atomic released_{false}; ///< #267: release_gpu_waits ran (maybe on the watchdog thread): no more windows - bool all_resident_ = false; ///< 100% of experts in [lb_, le_) resident in VRAM: zero-doorbell graph - bool device_plan_ = false; ///< E-6: resident-only layers planned on the device (STRATA_VERIFY_DEVICE_PLAN) - uint32_t* skip_ = nullptr; ///< E-6: per group, the ring whose plan the device built (0: the host's) - unsigned long long* slot_off_d_ = nullptr; ///< E-6: the slot offsets on the device - int64_t lb_ = 0, le_ = -1; ///< set_stage: the layers this verifier runs (-1: to the last) - const float* hand_in_ = nullptr; - float* hand_out_ = nullptr; - Verifier* next_ = nullptr; - void* next_user_ = nullptr; - bool ple_stage() const { return lb_ <= 1 && 1 < le_; } ///< holds layer 1, where the PLE block runs - void stage_inputs(int T, const int32_t* tokens, int64_t pos0); - bool staged_ = false; - bool copy_used_ = false; - bool capture_commit(std::string& err); - bool record_window(int T, cudaStream_t cs, std::string& err); - // #649: STRATA_VERIFY_TRACE=1 - a host event ring (trace_ev) and GPU breadcrumbs: the profiler's stamp points, - // per layer and token group, written to mapped memory (null when the trace is off) - void trace_ev(const char* what, int64_t step, int64_t layer, int64_t aux) const; - unsigned long long* trace_h_ = nullptr; - unsigned long long* trace_m_ = nullptr; - size_t trace_n_ = 0; - static constexpr int kProfPer = 33; // stamps per layer (32 left the hc-read second - // half's up-stamp at slot 32 = the next layer's slot 0: D8) - bool prof_on_ = false; - unsigned long long* prof_ = nullptr; // device: n_layers * kProfPer + 4 stamps - std::vector prof_h_; - double prof_sum_[2][kProfPer] = {}; // [GDN / QSA layers][stage] - int64_t prof_windows_ = 0; - - const WeightTable* wt_ = nullptr; - const ModelGeometry* g_ = nullptr; - SessionState* ss_ = nullptr; - VerifyHits hits_; - const NativeHead* head_ = nullptr; - int max_t_ = 0; - int last_t_ = 0; - int64_t last_pos0_ = 0; - int32_t last_tokens_[8] = {}; - int64_t n_vocab_ = 0; - cudaStream_t cs_ = nullptr; - cudaStream_t sh_cs_ = nullptr; - cudaEvent_t ev_fork_ = nullptr, ev_join_ = nullptr; - cudaGraphExec_t exec_[9] = {}; - cudaGraphExec_t commit_exec_ = nullptr; - - // mapped staging (host pointer, device alias) - int32_t* h_tok_ = nullptr; int32_t* m_tok_ = nullptr; // T - int32_t* h_step_ = nullptr; int32_t* m_step_ = nullptr; // T * kStepCount - int32_t* h_pos_ = nullptr; int32_t* m_pos_ = nullptr; // T * n_head - int32_t* h_commit_ = nullptr; int32_t* m_commit_ = nullptr; // [n_keep, n_keep-1, pos_0 .. pos_{T-1}] - float* h_ple_ = nullptr; float* m_ple_ = nullptr; // T * n_embd - int32_t* h_out_ = nullptr; int32_t* m_out_ = nullptr; // T argmax ids - float* h_x_ = nullptr; float* m_x_ = nullptr; // doorbell payload: T * n_embd - int32_t* h_ids_ = nullptr; int32_t* m_ids_ = nullptr; // T * k - float* h_w_ = nullptr; float* m_w_ = nullptr; // T * k - uint32_t* h_seq_ = nullptr; uint32_t* m_seq_ = nullptr; - uint32_t* h_flag_ = nullptr; uint32_t* m_flag_ = nullptr; - uint32_t* h_flagA_ = nullptr; uint32_t* m_flagA_ = nullptr; // the GPU plan is in place - uint32_t* h_flagB_ = nullptr; uint32_t* m_flagB_ = nullptr; // the PCIe share's DMA copies have landed - cudaEvent_t commit_done_ = nullptr; // recorded after an async commit (set_commit_async); see wait_commit - bool commit_pending_ = false; - cudaStream_t copy_ = nullptr; // the copy engine's stream (DMA of missed experts) - struct FlagSet { uint32_t* flag; uint32_t value; }; - FlagSet flag_sets_[2 * 64 * 2] = {}; // host-function arguments, one per (layer, group) - static void fetch_dma(void* ctx, const uint8_t* const* src, int n, size_t bytes); - static void raise_flag(uint32_t* flag, uint32_t value); - int32_t* h_plan_ = nullptr; int32_t* m_plan_ = nullptr; // counts | start | dst | tok | ptr (as int32 pairs) - int64_t plan_i32_ = 0; // int32 words in the plan block - GpuPlanSink sink_; - uint32_t cur_layer_ = 0; - static void publish_plan(void* ctx); - void set_plan_slot(int grp); - bool split_ = false; // opt-in (--spec-split): exact but slower, see the overlap study - int groups_[9] = {}; - float* h_ymiss_ = nullptr; float* m_ymiss_ = nullptr; // T * k * n_embd - - // device - void* arena_ = nullptr; - int32_t *tok_ = nullptr, *step_ = nullptr, *pos_ = nullptr, *commit_ = nullptr; - float *ple_ = nullptr, *emb_ = nullptr, *R_ = nullptr, *mixed_ = nullptr, *bo_ = nullptr; - float *inj_ = nullptr, *inj2_ = nullptr, *lo_ = nullptr, *rs_ = nullptr, *xn_ = nullptr; - uint8_t* xq_ = nullptr; // T columns of q8_1 - uint8_t* sh_xq_ = nullptr; // T columns of q8_1 for shared expert branch - float *qkv_L_ = nullptr, *h_L_ = nullptr, *gate_L_ = nullptr, *beta_L_ = nullptr; // per GDN layer - float *z_ = nullptr, *y_ = nullptr, *y_dummy_ = nullptr; - float *qfull_ = nullptr, *qcur_ = nullptr, *kcur_ = nullptr, *vcur_ = nullptr, *idx_raw_L_ = nullptr; - float *qidx_ = nullptr, *scores_ = nullptr, *attn_ = nullptr, *attn32_ = nullptr, *attn_scratch_ = nullptr; - float* tail_snap_ = nullptr; // per QSA layer - int32_t* sel_ = nullptr; - float *logits_ = nullptr, *w_ = nullptr, *shared_ = nullptr, *parts_ = nullptr, *hit_out_ = nullptr; - int32_t *ids_ = nullptr, *hit_slot_ = nullptr, *hit_dst_ = nullptr, *hit_count_ = nullptr; - int32_t* plan_ = nullptr; // device copy of the plan block - uint8_t* staging_ = nullptr; // VRAM slots for the PCIe share of the misses - static constexpr int64_t kStagingBlobs = 16; - static constexpr int64_t kPcieGroupRows = 4; // the PCIe call's groups side by side (of <= 16) - uint8_t* hit_xq_ = nullptr; - uint8_t* nat_xq_ = nullptr; // plan v0.3 P6: q8_1 activations for a native pack's grouped experts - float* hit_xs_ = nullptr; - void* hit_scratch_ = nullptr; - float *head_mixed_ = nullptr, *head_inj_ = nullptr, *head_logits_ = nullptr; - uint16_t* sh_bf16_ = nullptr; - float *sh_gate_ = nullptr, *sh_up_ = nullptr, *sh_g_ = nullptr; - float* hist_snap_ = nullptr; // T * NG_HIST * NG_HC_DIM - int64_t cap_ = 0, max_blocks_ = 0, attn_scratch_floats_ = 0; -}; - -} // namespace strata::core diff --git a/include/strata/core/weights.hpp b/include/strata/core/weights.hpp deleted file mode 100644 index aa83448..0000000 --- a/include/strata/core/weights.hpp +++ /dev/null @@ -1,144 +0,0 @@ -// include/strata/core/weights.hpp - the dense weights, loaded into VRAM in ENGINE form. -// -// The pack is the ARTIFACT's business; this is the ENGINE's. The differences are deliberate, and they run in -// BOTH directions: -// -// * SHRINKING. A tensor whose source type is BF16 is stored in the pack promoted to 32 bits, because that is -// lossless and it keeps the canonical decoder simple, but a running engine re-rounds it to 16 - which costs -// nothing at all, because the value CAME from 16 bits. Per `tools/pack_budget.py` that saving is the -// difference between the dense weights fitting in VRAM beside the expert cache and not fitting at all. -// -// * GROWING. 90 of the 303 quantized tensors carry fp16 SCALES in the pack (all 58 Q2_0 expert tensors, plus -// Q4_0, Q5_0, Q8_0 and IQ4_NL) because that is what the source block holds. Every kernel here takes -// `const float* scales`, and fp16 is a subset of f32, so this loader WIDENS them - exactly, changing no -// value - for 11,407,360 B. See `docs/pack-format.md` §2.4; assuming 4 bytes per scale instead of reading -// `scales_fp16` is what made the plane arithmetic disagree with the pack for a whole round. -// -// pack 5.305 GiB dense + 0.444 GiB embd -// engine 4.067 GiB dense + 0.444 GiB embd + 10.88 MiB widened scales = 4.522 GiB -// -// WHAT THE LOADER DOES NOT DO: it does not know what any tensor MEANS. It reads a flat index -// (`/index.txt`, written by `tools/pack_index.py`), copies each tensor into one arena at a recorded -// offset - as a list of PLANE SEGMENTS, because a scale plane can change width and the rest cannot - and hands -// back a name -> WeightRef map. Geometry, forms and semantics belong to the caller. -// -// WHY AN INDEX FILE AND NOT A JSON PARSER: a JSON parser in the engine would be a new, unaudited component -// whose failure mode is a wrong byte offset - which decodes to a plausible weight and produces plausible -// logits. Python wrote the manifest and already parses it correctly. -#pragma once - -#include -#include -#include -#include -#include - -namespace strata::core { - -/// What the loader had to DO for a tensor, decided by `tools/pack_index.py` and written into the index -/// rather than inferred here. The four cases are distinguishable in the manifest only by combining -/// `source_type` with `values_fp16`, and getting that combination wrong yields a plausible tensor. -enum class WeightKind : int { - Verbatim = 0, ///< quantized planes, or F16 already stored as 2 bytes: copy straight through - Bf16InF32 = 1, ///< the pack holds the bf16 value promoted to f32: take the HIGH 16 BITS (exact) - F32 = 2, ///< copy 4 bytes per element - F16InF32 = 3, ///< an f16 value promoted to f32: a real f32->f16 conversion, not a truncation -}; - -struct WeightRef { - const void* data = nullptr; ///< device pointer inside the arena - uint64_t bytes = 0; - int64_t ne0 = 0; ///< the manifest's own shape, ne0 the CONTIGUOUS axis - int64_t ne1 = 0; - int64_t elements = 0; - WeightKind kind = WeightKind::Verbatim; - /// The canonical-form attributes, valid only for a quantized VERBATIM tensor (`code_bits != 0`). - int code_bits = 0; - int code_bias = 0; - int group_elems = 0; - bool codebook_iq4nl = false; - bool has_offset = false; - - /// THE THREE PLANE SIZES, IN ENGINE FORM, in the order they sit inside `data`. Recorded by the loader - /// from what the index TOLD it rather than re-derived by each caller: the one time this layout was - /// re-derived independently it assumed 4-byte scales for tensors whose pack scales are fp16, and the - /// only reason that was not a silent wrong answer is that the re-derivation checked itself and refused. - /// Two places computing one layout is two places to disagree. - uint64_t codes_bytes = 0; - uint64_t scales_bytes = 0; ///< always 4 B per scale in the arena, whatever the pack held - uint64_t offset_bytes = 0; ///< 0 when the form has no offset plane - - /// WHERE THIS TENSOR CAME FROM, so a caller can check the loader's work against the pack's own bytes - /// instead of against the loader's opinion of them. Without `src_off` a test can only compare two - /// derived numbers; with it, the widening of an fp16 scale plane can be verified value by value against - /// `.bin` - and the pack files are named, so `file_id` says which one to open. - uint64_t src_off = 0; - uint64_t src_bytes = 0; - int file_id = 0; - bool scales_fp16 = false; ///< the PACK's width, before the loader widened it - - /// WHICH ACTIVATION THIS WEIGHT WANTS - 0 for Q8_0, 1 for Q8_K. Decided by ools/pack_index.py from - /// source_type and carried here, because **the S-form CANNOT express it**: Q5_0 and Q5_K are both 8-bit - /// with bias -16, and IQ4_NL and IQ4_XS differ in nothing the S-form holds. docs/activation-contract.md. - int act_kind = 0; - bool wants_q8k() const { return act_kind == 1; } - - bool quantized() const { return code_bits != 0; } - - // Optional native GGUF projection, owned by NativeDense. All references in - // one table share its scratch and must execute on one ordered session stream. - const void* native_data = nullptr; - void* native_q8_1 = nullptr; - int native_type = -1; - /// Plan v0.3 P1: false when the loader SKIPPED this tensor's canonical bytes because another form serves it - /// (native GGUF projections, the native head). The metadata above stays valid; `data` is null. - bool resident = true; -}; - -struct LoadReport { - size_t tensors = 0; - uint64_t arena_bytes = 0; - size_t re_rounded = 0; ///< tensors written as 16 bits out of a 32-bit container - uint64_t bytes_saved = 0; ///< what those conversions saved against the pack - double read_ms = 0.0; - double upload_ms = 0.0; -}; - -class WeightTable { -public: - /// The arena size the index asks for, readable WITHOUT loading anything - so a caller can size its - /// `DeviceArena` before committing to the load, and a plan that cannot fit is refused at startup rather - /// than halfway through a 5 GB upload. - /// With `skip`, the size of the compacted arena that holds every tensor EXCEPT the named ones. - static bool pool_bytes(const std::string& pack_dir, uint64_t& out, std::string& err, - const std::set* skip = nullptr); - - /// The `code_bits` field of one row of `/index.txt`, readable WITHOUT loading anything (0 = the - /// pack stores the tensor unquantized, e.g. a --compat-bf16 key; -1 = no such row). #326: the loader has - /// to know this before it builds the skip set. - static bool index_code_bits(const std::string& pack_dir, const std::string& name, int& code_bits, - std::string& err); - - /// Load every tensor in `/index.txt` into `arena_base`. - /// - /// `arena_bytes` MUST be at least `pool_bytes`; the loader checks rather than trusting the caller, - /// because the failure mode otherwise is a device write past the end of the arena. - /// With `skip`, the named tensors are not read: their rows keep their metadata with `data == nullptr` and - /// `resident == false`, and the other tensors are packed into the compacted arena `pool_bytes` sized. - bool load(const std::string& pack_dir, void* arena_base, uint64_t arena_bytes, std::string& err, - const std::set* skip = nullptr); - - const WeightRef* find(const std::string& name) const; - const std::map& 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: - friend class NativeDense; - std::map table_; - LoadReport report_; -}; - -} // namespace strata::core diff --git a/include/strata/hip_compat/cublas_v2.h b/include/strata/hip_compat/cublas_v2.h deleted file mode 100644 index 8794479..0000000 --- a/include/strata/hip_compat/cublas_v2.h +++ /dev/null @@ -1,60 +0,0 @@ -#pragma once -#include -#include - -#if hipblasVersionMajor == 0 -// Ubuntu's hipBLAS 0.54 has no workspace API or compute-type enum. Use its -// underlying rocBLAS API directly, including ownership of the real handle, -// so the engine's explicit workspace contract is preserved. -#include -#define CUBLAS_COMPUTE_32F rocblas_datatype_f32_r -#define CUBLAS_DEFAULT_MATH 0 -#define CUBLAS_GEMM_DEFAULT rocblas_gemm_algo_standard -#define CUBLAS_OP_N rocblas_operation_none -#define CUBLAS_OP_T rocblas_operation_transpose -#define CUBLAS_STATUS_SUCCESS rocblas_status_success -#define CUDA_R_16BF rocblas_datatype_bf16_r -#define CUDA_R_16F rocblas_datatype_f16_r -#define CUDA_R_32F rocblas_datatype_f32_r -#define cublasCreate rocblas_create_handle -#define cublasDestroy rocblas_destroy_handle -#define cublasHandle_t rocblas_handle -#define cublasSetStream rocblas_set_stream -#define cublasSetWorkspace rocblas_set_workspace -#define cublasStatus_t rocblas_status - -inline rocblas_status cublasSetMathMode(rocblas_handle h, int mode) { - // This API has only its default arithmetic; GEMM below explicitly selects - // FP32 accumulation. Reject any request for a different math mode. - if (!h) return rocblas_status_invalid_handle; - return mode == CUBLAS_DEFAULT_MATH ? rocblas_status_success : rocblas_status_invalid_value; -} -inline rocblas_status cublasGemmEx(rocblas_handle h, rocblas_operation trans_a, - rocblas_operation trans_b, int m, int n, int k, const void* alpha, - const void* a, rocblas_datatype a_type, int lda, - const void* b, rocblas_datatype b_type, int ldb, const void* beta, - void* c, rocblas_datatype c_type, int ldc, - rocblas_datatype compute_type, rocblas_gemm_algo algo) { - return rocblas_gemm_ex(h, trans_a, trans_b, m, n, k, alpha, - a, a_type, lda, b, b_type, ldb, beta, c, c_type, ldc, - c, c_type, ldc, compute_type, algo, 0, 0); -} -#else -#define CUBLAS_COMPUTE_32F HIPBLAS_COMPUTE_32F -#define CUBLAS_DEFAULT_MATH HIPBLAS_DEFAULT_MATH -#define CUBLAS_GEMM_DEFAULT HIPBLAS_GEMM_DEFAULT -#define CUBLAS_OP_N HIPBLAS_OP_N -#define CUBLAS_OP_T HIPBLAS_OP_T -#define CUBLAS_STATUS_SUCCESS HIPBLAS_STATUS_SUCCESS -#define CUDA_R_16BF HIP_R_16BF -#define CUDA_R_16F HIP_R_16F -#define CUDA_R_32F HIP_R_32F -#define cublasCreate hipblasCreate -#define cublasDestroy hipblasDestroy -#define cublasGemmEx hipblasGemmEx -#define cublasHandle_t hipblasHandle_t -#define cublasSetMathMode hipblasSetMathMode -#define cublasSetStream hipblasSetStream -#define cublasSetWorkspace hipblasSetWorkspace -#define cublasStatus_t hipblasStatus_t -#endif diff --git a/include/strata/hip_compat/cuda_fp16.h b/include/strata/hip_compat/cuda_fp16.h deleted file mode 100644 index 969acef..0000000 --- a/include/strata/hip_compat/cuda_fp16.h +++ /dev/null @@ -1,2 +0,0 @@ -#pragma once -#include diff --git a/include/strata/hip_compat/cuda_runtime.h b/include/strata/hip_compat/cuda_runtime.h deleted file mode 100644 index 8ea907a..0000000 --- a/include/strata/hip_compat/cuda_runtime.h +++ /dev/null @@ -1,143 +0,0 @@ -#pragma once -// Included only by STRATA_ENABLE_HIP builds. CUDA builds use NVIDIA headers. -#if defined(_WIN32) -// hip_runtime.h pulls in on Windows: keep its min/max macros and the rarely used APIs out of the engine. -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#ifndef NOMINMAX -#define NOMINMAX -#endif -#endif -#include -#include -// Do not let HIP's legacy macro corrupt libstdc++ attribute names. -#ifdef __noinline__ -#undef __noinline__ -#endif -#define cudaDevAttrMaxSharedMemoryPerBlockOptin hipDeviceAttributeMaxSharedMemoryPerBlock -#define cudaDevAttrMultiProcessorCount hipDeviceAttributeMultiprocessorCount -#define cudaDevAttrClockRate hipDeviceAttributeClockRate -#define cudaDevAttrComputeCapabilityMajor hipDeviceAttributeComputeCapabilityMajor -#define cudaDevAttrComputeCapabilityMinor hipDeviceAttributeComputeCapabilityMinor -#define cudaDeviceGetAttribute hipDeviceGetAttribute -#define cudaDeviceCanAccessPeer hipDeviceCanAccessPeer -#define cudaDeviceEnablePeerAccess hipDeviceEnablePeerAccess -#define cudaDeviceProp hipDeviceProp_t -#define cudaDeviceSynchronize hipDeviceSynchronize -#define cudaDriverGetVersion hipDriverGetVersion -#define cudaErrorNotReady hipErrorNotReady -#define cudaErrorPeerAccessAlreadyEnabled hipErrorPeerAccessAlreadyEnabled -#define cudaErrorStreamCaptureUnsupported hipErrorStreamCaptureUnsupported -#define cudaError_t hipError_t -#define cudaEventCreate hipEventCreate -#define cudaEventCreateWithFlags hipEventCreateWithFlags -#define cudaEventDestroy hipEventDestroy -#define cudaEventDisableTiming hipEventDisableTiming -#define cudaEventElapsedTime hipEventElapsedTime -#define cudaEventQuery hipEventQuery -#define cudaEventRecord hipEventRecord -#define cudaEventSynchronize hipEventSynchronize -#define cudaEvent_t hipEvent_t -#define cudaFree hipFree -#if HIP_VERSION_MAJOR < 7 -#define cudaFreeHost hipHostFree -#else -#define cudaFreeHost hipFreeHost -#endif -#define cudaFuncAttributeMaxDynamicSharedMemorySize hipFuncAttributeMaxDynamicSharedMemorySize -#define cudaFuncAttributePreferredSharedMemoryCarveout hipFuncAttributePreferredSharedMemoryCarveout -#define cudaGetDevice hipGetDevice -#define cudaGetDeviceCount hipGetDeviceCount -#define cudaGetDeviceProperties hipGetDeviceProperties -#define cudaGetErrorString hipGetErrorString -#define cudaGetLastError hipGetLastError -#define cudaGraphDestroy hipGraphDestroy -#define cudaGraphExecDestroy hipGraphExecDestroy -#define cudaGraphExec_t hipGraphExec_t -#define cudaGraphGetNodes hipGraphGetNodes -#define cudaGraphLaunch hipGraphLaunch -#define cudaGraphUpload hipGraphUpload -#define cudaGraph_t hipGraph_t -#define cudaHostAlloc hipHostMalloc -#if HIP_VERSION_MAJOR < 7 -#define cudaHostAllocDefault hipHostMallocDefault -#define cudaHostAllocMapped hipHostMallocMapped -#define cudaHostAllocPortable hipHostMallocPortable -#else -#define cudaHostAllocDefault hipHostAllocDefault -#define cudaHostAllocMapped hipHostAllocMapped -#define cudaHostAllocPortable hipHostAllocPortable -#endif -#define cudaHostGetDevicePointer hipHostGetDevicePointer -#define cudaHostRegister hipHostRegister -#define cudaHostRegisterMapped hipHostRegisterMapped -#define cudaHostRegisterPortable hipHostRegisterPortable -#define cudaHostRegisterReadOnly hipHostRegisterReadOnly -#define cudaHostUnregister hipHostUnregister -#define cudaLaunchHostFunc hipLaunchHostFunc -#define cudaMalloc hipMalloc -#define cudaMallocHost(...) (::strata::hip_compat::malloc_host(__VA_ARGS__)) -#if defined(_WIN32) -// Windows: hipMemGetInfo counts this process's own allocations only, so the desktop's and other programs' share of -// the card is invisible to it, and VRAM sized by it overfills the card (WDDM then moves memory out to system RAM and -// the GPU slows down). Its free figure is lowered by what Windows' video memory budget for this process withholds -// (src/core/device.cu; STRATA_WDDM_BUDGET=0: hipMemGetInfo as it is). -namespace strata::hip_compat { -hipError_t mem_get_info(size_t* free_bytes, size_t* total_bytes); -} -#define cudaMemGetInfo ::strata::hip_compat::mem_get_info -#else -#define cudaMemGetInfo hipMemGetInfo -#endif -#define cudaMemcpy hipMemcpy -#define cudaMemcpy2DAsync hipMemcpy2DAsync -#define cudaMemcpyAsync hipMemcpyAsync -#define cudaMemcpyPeerAsync hipMemcpyPeerAsync -#define cudaMemcpyDefault hipMemcpyDefault -#define cudaMemcpyDeviceToDevice hipMemcpyDeviceToDevice -#define cudaMemcpyDeviceToHost hipMemcpyDeviceToHost -#define cudaMemcpyHostToDevice hipMemcpyHostToDevice -#define cudaMemset hipMemset -#define cudaMemsetAsync hipMemsetAsync -#define cudaPeekAtLastError hipPeekAtLastError -#define cudaRuntimeGetVersion hipRuntimeGetVersion -#define cudaSetDevice hipSetDevice -#define cudaStreamBeginCapture hipStreamBeginCapture -#define cudaStreamCaptureModeThreadLocal hipStreamCaptureModeThreadLocal -#define cudaStreamCaptureStatus hipStreamCaptureStatus -#define cudaStreamCaptureStatusNone hipStreamCaptureStatusNone -#define cudaStreamCreate hipStreamCreate -#define cudaStreamCreateWithFlags hipStreamCreateWithFlags -#define cudaStreamDestroy hipStreamDestroy -#define cudaStreamEndCapture hipStreamEndCapture -#define cudaStreamIsCapturing hipStreamIsCapturing -#define cudaStreamNonBlocking hipStreamNonBlocking -#define cudaStreamQuery hipStreamQuery -#define cudaStreamSynchronize hipStreamSynchronize -#define cudaStreamWaitEvent hipStreamWaitEvent -#define cudaStream_t hipStream_t -#define cudaSuccess hipSuccess - -namespace strata::hip_compat { -template -inline hipError_t malloc_host(T** pointer, size_t bytes) { - return hipHostMalloc(reinterpret_cast(pointer), bytes, hipHostMallocDefault); -} -} // namespace strata::hip_compat - -template -inline hipError_t cudaFuncSetAttribute(Kernel kernel, hipFuncAttribute attribute, int value) { - return hipFuncSetAttribute(reinterpret_cast(kernel), attribute, value); -} -inline hipError_t cudaGraphInstantiate(hipGraphExec_t* exec, hipGraph_t graph, unsigned long long flags) { - return hipGraphInstantiateWithFlags(exec, graph, flags); -} -inline hipError_t cudaGraphInstantiate(hipGraphExec_t* exec, hipGraph_t graph, - hipGraphNode_t* error, char* log, size_t size) { - return hipGraphInstantiate(exec, graph, error, log, size); -} -#define __trap() __builtin_trap() // the compiled-out sm_80 paths (never selected on AMD) -#define cudaMemcpyToSymbol(symbol, ...) hipMemcpyToSymbol(HIP_SYMBOL(symbol), __VA_ARGS__) - -#include "intrinsics.hpp" diff --git a/include/strata/hip_compat/cuda_runtime_api.h b/include/strata/hip_compat/cuda_runtime_api.h deleted file mode 100644 index cf546fc..0000000 --- a/include/strata/hip_compat/cuda_runtime_api.h +++ /dev/null @@ -1,2 +0,0 @@ -#pragma once -#include "cuda_runtime.h" diff --git a/include/strata/hip_compat/intrinsics.hpp b/include/strata/hip_compat/intrinsics.hpp deleted file mode 100644 index 3129f04..0000000 --- a/include/strata/hip_compat/intrinsics.hpp +++ /dev/null @@ -1,162 +0,0 @@ -#pragma once - -// CUDA device intrinsics used by Strata kernels on supported wave32 HIP targets. -// This header is included only from the HIP cuda_runtime compatibility shim. -#if defined(__HIPCC__) -#include - -#include - -namespace strata::hip_compat { - -__device__ __forceinline__ int signed_byte(uint32_t word, int lane) { - const unsigned value = (word >> (lane * 8)) & 0xffu; - return value < 0x80u ? static_cast(value) : static_cast(value) - 0x100; -} - -// CUDA's signed __dp4a: four signed byte products accumulated modulo 2^32. -__device__ __forceinline__ int dp4a(int a, int b, int c) { -#if (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1200__) || \ - defined(__gfx1201__)) && __has_builtin(__builtin_amdgcn_sudot4) - // RDNA3 and RDNA4 expose the signed/unsigned dot4 form (v_dot4_i32_iu8). Mark - // both packed operands signed to preserve CUDA __dp4a semantics; keep the - // portable path for other HIP compilers/targets. - return __builtin_amdgcn_sudot4(true, a, true, b, c, false); -#elif (defined(__gfx1030__) || defined(__gfx1031__) || defined(__gfx1032__)) && __has_builtin(__builtin_amdgcn_sdot4) - // RDNA2 has no sudot4 (that is gfx11+), but it has the plain signed v_dot4_i32_i8 (dot1-insts): the same - // signed x signed byte products accumulated modulo 2^32, no clamp. - return __builtin_amdgcn_sdot4(a, b, c, false); -#elif defined(__gfx1012__) && !defined(STRATA_GFX1012_PORTABLE_DOT) - // RDNA1 has no native signed dot4. SDWA selects and sign-extends byte - // operands directly, avoiding separate shift/mask/sign-extension work. - // Adapted from pinned llama.cpp ggml-cuda/common.cuh (MIT; see - // third_party/ggml/LICENSE), same modulo-2^32 accumulation contract. - int lo, hi; - asm("v_mul_i32_i24 %1, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0 src1_sel:BYTE_0\n" - "v_mul_i32_i24 %2, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1 src1_sel:BYTE_1\n" - "v_add3_u32 %0, %1, %2, %0\n" - "v_mul_i32_i24 %1, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_2 src1_sel:BYTE_2\n" - "v_mul_i32_i24 %2, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_3 src1_sel:BYTE_3\n" - "v_add3_u32 %0, %1, %2, %0\n" - // c changes before the high-byte reads; it must not alias a or b. - : "+&v"(c), "=&v"(lo), "=&v"(hi) : "v"(a), "v"(b)); - return c; -#else - const uint32_t ua = static_cast(a); - const uint32_t ub = static_cast(b); - uint32_t sum = static_cast(c); -#pragma unroll - for (int lane = 0; lane < 4; ++lane) - sum += static_cast(signed_byte(ua, lane) * signed_byte(ub, lane)); - return static_cast(sum); -#endif -} - -// CUDA's __byte_perm (default mode): result byte i is byte s.nibble[i] & 7 of the pair {y:x}, x the low word. -// HIP's own version indexes a byte array in private memory, which becomes scratch traffic in the i-quant table -// lookups; v_perm_b32 is the same selection in one instruction (selector bytes 0-3 pick from its second -// operand, 4-7 from its first), so the nibble selector is spread to bytes and masked to 0-7. -__device__ __forceinline__ uint32_t byte_perm(uint32_t x, uint32_t y, uint32_t s) { - const uint32_t sel = (s & 0x7u) | ((s & 0x70u) << 4) | ((s & 0x700u) << 8) | ((s & 0x7000u) << 12); - return __builtin_amdgcn_perm(y, x, sel); -} - -// The packed byte operations below work on all four lanes at once (SWAR, Hacker's Delight 2-18): gfx11/gfx12 have -// no packed 8-bit subtract, and a per-lane loop costs the Q3_K/Q6_K dots and the i-quant sign expansion several -// times the instructions. kHigh is each lane's top bit. -constexpr uint32_t kHigh = 0x80808080u; - -// CUDA's packed byte subtract wraps independently in each unsigned byte lane: subtract the low seven bits with the -// minuend's top bit forced on (so no borrow crosses a lane), then fix each top bit by XOR. -__device__ __forceinline__ int vsub4(int a, int b) { - const uint32_t ua = static_cast(a); - const uint32_t ub = static_cast(b); - return static_cast(((ua | kHigh) - (ub & ~kHigh)) ^ ((ua ^ ~ub) & kHigh)); -} - -// CUDA's packed signed-byte saturating subtract: the wrapping difference, and in each lane that overflowed (operand -// signs differ and the result's sign differs from the minuend's) the bound on the minuend's side, 0x7f or 0x80. -__device__ __forceinline__ int vsubss4(int a, int b) { - const uint32_t ua = static_cast(a); - const uint32_t ub = static_cast(b); - const uint32_t d = static_cast(vsub4(a, b)); - const uint32_t overflow = (ua ^ ub) & (ua ^ d) & kHigh; - const uint32_t mask = (overflow >> 7) * 0xffu; - const uint32_t bound = 0x7f7f7f7fu + ((ua & kHigh) >> 7); - return static_cast((d & ~mask) | (bound & mask)); -} - -// CUDA's four-lane byte compare, returning 0xff for each unequal lane and 0 otherwise: a lane of a ^ b is nonzero -// when its low seven bits carry into the top bit on adding 0x7f, or its top bit is already set. -__device__ __forceinline__ int vcmpne4(int a, int b) { - const uint32_t t = static_cast(a) ^ static_cast(b); - const uint32_t nonzero = (((t & ~kHigh) + ~kHigh) | t) & kHigh; - return static_cast((nonzero >> 7) * 0xffu); -} - -// CUDA's mask argument describes participating lanes. The current kernel set uses full -// wave32 masks; reject future partial-mask use instead of silently dropping its semantics. -__device__ __forceinline__ void require_full_wave_mask(uint32_t mask) { - if (mask != 0xffffffffu) __builtin_trap(); -} - -// Older HIP has no __syncwarp. A wave barrier alone does not order memory. -// Release/acquire fences cover the shared-memory exchange used by attention. -#if HIP_VERSION_MAJOR < 7 -__device__ __forceinline__ void syncwarp(uint32_t mask = 0xffffffffu) { - require_full_wave_mask(mask); - __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup"); - __builtin_amdgcn_wave_barrier(); - __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup"); -} -#endif - -template -__device__ __forceinline__ T shfl_xor_sync(uint32_t mask, T value, int lane_mask, int width = 32) { - require_full_wave_mask(mask); - return __shfl_xor(value, lane_mask, width); -} - -template -__device__ __forceinline__ T shfl_down_sync(uint32_t mask, T value, unsigned delta, int width = 32) { - require_full_wave_mask(mask); - return __shfl_down(value, delta, width); -} - -template -__device__ __forceinline__ T shfl_up_sync(uint32_t mask, T value, unsigned delta, int width = 32) { - require_full_wave_mask(mask); - return __shfl_up(value, delta, width); -} - -template -__device__ __forceinline__ T shfl_sync(uint32_t mask, T value, int source_lane, int width = 32) { - require_full_wave_mask(mask); - return __shfl(value, source_lane, width); -} - -__device__ __forceinline__ unsigned ballot_sync(uint32_t mask, int predicate) { - require_full_wave_mask(mask); - return static_cast(__ballot(predicate)); -} - -} // namespace strata::hip_compat - -#define __dp4a(a, b, c) (::strata::hip_compat::dp4a((a), (b), (c))) -#define __byte_perm(x, y, s) (::strata::hip_compat::byte_perm((x), (y), (s))) -#define __vsub4(a, b) (::strata::hip_compat::vsub4((a), (b))) -#define __vsubss4(a, b) (::strata::hip_compat::vsubss4((a), (b))) -#define __vcmpne4(a, b) (::strata::hip_compat::vcmpne4((a), (b))) -#define __shfl_xor_sync(...) (::strata::hip_compat::shfl_xor_sync(__VA_ARGS__)) -#define __shfl_down_sync(...) (::strata::hip_compat::shfl_down_sync(__VA_ARGS__)) -#define __shfl_up_sync(...) (::strata::hip_compat::shfl_up_sync(__VA_ARGS__)) -#define __shfl_sync(...) (::strata::hip_compat::shfl_sync(__VA_ARGS__)) -#define __ballot_sync(mask, predicate) (::strata::hip_compat::ballot_sync((mask), (predicate))) -#if HIP_VERSION_MAJOR < 7 -#define __syncwarp(...) (::strata::hip_compat::syncwarp(__VA_ARGS__)) -#endif -// AMD's sleep instruction accepts only 0..15; the synchronization loops use it as a -// backoff hint, so use its smallest portable delay independently of CUDA cycle counts. -#define __nanosleep(cycles) __builtin_amdgcn_s_sleep(1) - -#endif // defined(__HIPCC__) diff --git a/include/strata/hip_compat/math_constants.h b/include/strata/hip_compat/math_constants.h deleted file mode 100644 index 50a0862..0000000 --- a/include/strata/hip_compat/math_constants.h +++ /dev/null @@ -1,4 +0,0 @@ -#pragma once -// CUDA spelling used by the attention kernels; included only in HIP builds. -#include -#define CUDART_INF_F HIP_INF_F diff --git a/include/strata/kernels/bf16_bits.hpp b/include/strata/kernels/bf16_bits.hpp deleted file mode 100644 index 5c32532..0000000 --- a/include/strata/kernels/bf16_bits.hpp +++ /dev/null @@ -1,61 +0,0 @@ -// include/strata/kernels/bf16_bits.hpp - the bf16 conversions, written out, as bits. -// -// bf16 is the TOP HALF of an f32, so `f32_from_bf16` is a shift and needs no rounding at all. The forward -// direction does: ggml's `ggml_compute_fp32_to_bf16` adds `((i >> 16) & 1) + 0x7FFF` and truncates 16 bits. -// -// **THE `& 1` IS ON BIT 16**, the lowest KEPT bit, which is what makes an exact tie round to EVEN. Using bit -// 15 there is a plausible mistake: it differs only on exact ties, i.e. almost never on real data, which is -// exactly why it would survive any amount of end-to-end testing. `ref/quant.py` documents the same rule for -// the same reason. -// -// WHY THIS IS SEPARATE FROM `f16_bits.hpp`: fp16 and bf16 are not two spellings of one idea. fp16 has 5 -// exponent bits and 10 mantissa bits; bf16 has 8 and 7. A conversion routine written for one and reused for -// the other is wrong in a way that produces plausible numbers - bf16's 2^-9 relative precision looks like a -// small fp16 error and is not small at all next to fp16's 2^-11. -// -// `gr.cu` carried a private copy of `f32_to_bf16_bits` until this header existed. It now includes this. -#pragma once - -#include -#include - -#if defined(__CUDACC__) || defined(__HIPCC__) -#define STRATA_BF16_HD __host__ __device__ -#else -#define STRATA_BF16_HD -#endif - -namespace strata::kernels { - -/// Round-to-nearest-even f32 -> bf16, returned as raw bits in the LOW half of the uint16. -/// -/// **A NaN IS PASSED THROUGH, QUIETED, AS `ggml_compute_fp32_to_bf16` DOES.** The rounding add alone -/// carries out of the mantissa for a NaN: 0x7FFFFFFF became 0x8000 (-0) and 0x7F800001 became 0x7F80 (+inf), so -/// a NaN upstream was masked instead of propagated. The test is on the magnitude bits, the result keeps the -/// sign and the top mantissa bits and sets the quiet bit (64 = bit 6 of the bf16). Every non-NaN input, -/// infinities included, rounds exactly as before. -STRATA_BF16_HD inline uint16_t bf16_from_f32(float f) { - uint32_t i; -#if defined(__HIP_DEVICE_COMPILE__) - __builtin_memcpy(&i, &f, 4); -#else - std::memcpy(&i, &f, 4); -#endif - if ((i & 0x7FFFFFFFu) > 0x7F800000u) return (uint16_t) ((i >> 16) | 64u); - i = (i + ((i >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u; - return (uint16_t) (i >> 16); -} - -/// bf16 bits -> f32. Exact, and no rounding: the low 16 bits of an f32 are simply zero. -STRATA_BF16_HD inline float f32_from_bf16(uint16_t h) { - const uint32_t i = (uint32_t) h << 16; - float f; -#if defined(__HIP_DEVICE_COMPILE__) - __builtin_memcpy(&f, &i, 4); -#else - std::memcpy(&f, &i, 4); -#endif - return f; -} - -} // namespace strata::kernels diff --git a/include/strata/kernels/bf16_gemv.hpp b/include/strata/kernels/bf16_gemv.hpp deleted file mode 100644 index e3efe0f..0000000 --- a/include/strata/kernels/bf16_gemv.hpp +++ /dev/null @@ -1,56 +0,0 @@ -// include/strata/kernels/bf16_gemv.hpp - the GEMV for a BF16 weight, P2.S5. -// -// WHY THIS EXISTS WHEN `s_gemv` ALREADY DOES. `s_gemv` decodes the S-family canonical forms (S2/S4/S8) from -// `codes` + `scales`, and a BF16 weight is not one of them - it has no codes and no scales, it is a plain -// 16-bit matrix. Six tensors per layer are in that state: -// -// ssm_alpha.weight, ssm_beta.weight GDN, [n_embd, 48] -// indexer.q_proj.weight, indexer.k_proj.weight QSA, [n_embd, 512] and [n_embd, 128] -// ple_value.weight layer 1, [n_embd, n_embd] -// ffn_gate_inp.weight handled inside `router_top10` -// -// The original entry points take BF16 activation bits for the historical CPU-derived contract. The explicit -// FP32 entry point below follows the pinned CUDA single-token MMVF contract. See docs/activation-contract.md -// for why activation precision depends on backend and batch geometry rather than weight type alone. -#pragma once - -#include - -namespace strata::kernels { - -/// `y[o] = sum_i f32(x[i]) * f32(w[o*n_in + i])`, with both sides bf16-valued so every product is exact in -/// f32 and only the summation order differs. -/// -/// THE WEIGHT LAYOUT IS THE MANIFEST'S: shape [n_in, n_out] with ne0 = n_in CONTIGUOUS, so row `o` is a -/// contiguous run of `n_in` bf16 values. That is the same convention `s_gemv` uses, and it is what -/// `strata::core::WeightRef::ne0/ne1` already report. -void bf16_gemv(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, void* stream); - -/// The row-split variant, for the same reason `s_gemv_split` exists: with one thread per output row the -/// parallelism IS the output width, and `ssm_alpha` has 48 of them over 48 SMs. One warp per row, lanes -/// striding the reduction axis - which is also what makes the access pattern coalesced in this layout. -/// -/// NOT bit-identical to `bf16_gemv`: the partial sums are added in a different order. Both are kept and both -/// are tested, because the naive one is the reference the split one is checked against. -void bf16_gemv_split(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, - int threads_per_row, void* stream); - -/// Single-token, contiguous 2D BF16-weight/F32-activation MMVF from the pinned llama.cpp CUDA path. -/// Preserves pair accumulation, adaptive block size and warp-XOR reduction order. This is a separate -/// opt-in entry point; the legacy BF16-activation kernels above retain their behavior. -/// `w[o*n_in+i]` is BF16 bits; x/y are F32. n_in must be positive and even, n_out positive, both <= INT_MAX. -/// x must be 8-byte aligned, w 4-byte aligned, and y 4-byte aligned. Throws on invalid geometry/pointers. -/// The device buffers must not overlap; allocation bounds remain the caller's responsibility. -/// No allocations or synchronization, including when stream is null (the CUDA default stream). -void bf16_gemv_fp32_mmvf(const float* x, const uint16_t* w, float* y, - int64_t n_in, int64_t n_out, void* stream); -/// `ncols` columns at once: x is [ncols][n_in], y is [ncols][n_out]; each column bitwise equal to a -/// `bf16_gemv_fp32_mmvf` call on it. -void bf16_gemv_fp32_mmvf_cols(const float* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, int ncols, - void* stream); -/// bf16_gemv_fp32_mmvf for n_tok (1..8) activation rows x[t * ldx], outputs y[t * ldy + j]; one launch, -/// the weight read once, every output bit-identical to its own single-row call. -void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy, - int64_t n_in, int64_t n_out, int n_tok, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/cpu/expert.hpp b/include/strata/kernels/cpu/expert.hpp deleted file mode 100644 index ab05db8..0000000 --- a/include/strata/kernels/cpu/expert.hpp +++ /dev/null @@ -1,179 +0,0 @@ -// include/strata/kernels/cpu/expert.hpp - P2.S3: the CPU expert path. -// -// This is the Q2_0 expert kernel promoted out of `bench/micro/cpu_s2.cpp`, which is the instrument that -// measured `c` (Memory/LEDGER.md L9/L10: 15.03 ms for one token's full routed set on 6 cores, DRAM-bound at -// 44.14 GB/s) and whose P0.T2 parity passes at 1.461e-06. -// -// IT IS THE SAME CODE, NOT A COPY. Keeping a second implementation next to a validated one is how a project -// ends up with two answers and no way to say which is right, so `cpu_s2.cpp` is expected to become a thin -// benchmark over these functions. (Until it is, the two exist side by side and this header says so.) -// -// WHAT MAKES IT FAST, and each of the three was paid for once: -// -// * `vpdpbusd` (AVX512-VNNI) does four int8 MACs per instruction. The scalar loop it replaces ran at -// 9.89 GB/s on one core; VNNI is the reason the 6-core figure is 42.55 GB/s. -// * `vpmultishiftqb` (AVX512-VBMI) unpacks the 2-bit codes eight at a time. Its ARGUMENT ORDER is -// (control, data) and was determined empirically - the Intel guide states the opposite, and following the -// guide produced 43 of 64 wrong codes. -// * The row accumulator stays a FLOAT VECTOR and is reduced ONCE at the end of the row. Reducing per -// 64-weight block cost more than the dot products themselves: it made the kernel compute-bound at -// 21 GB/s instead of DRAM-bound at 32. -// -// THE CONTRACT THAT MATTERS, because collapsing it is invisible and cannot match ggml's logits: one Q2_0 -// WEIGHT block is QK=64 weights with one fp16 scale, while one ACTIVATION chunk is QKA=32 elements with -// its OWN scale. So a weight block spans TWO activation chunks with two different scales. Using one scale -// per weight block is the natural-looking mistake. -#pragma once - -#include -#include - -namespace strata::kernels::cpu { - -// ---- geometry, all of it fixed by the artifact (tools/verify_q2_0_geometry.py: 202/202 tensors at QK=64) ---- -inline constexpr int H = 2560; // n_embd -inline constexpr int FF = 640; // expert intermediate width -inline constexpr int NE = 512; // routed experts per layer -inline constexpr int QK = 64; // QK2_0: weights per fp16 scale -inline constexpr int QKA = 32; // QK8_1/QK8_0: ACTIVATION elements per scale -inline constexpr int BB = 18; // bytes per 64-weight Q2_0 block: 2 fp16-scale + 16 codes -inline constexpr int MAXC = H / QKA; // 80 activation chunks across the widest reduction -inline constexpr int ROW_GU = H * 2 / 8; // 640 B of codes per gate/up row -inline constexpr int ROW_D = FF * 2 / 8; // 160 B of codes per down row -inline constexpr int SC_GU = H / QK; // 40 weight blocks per gate/up row -inline constexpr int SC_D = FF / QK; // 10 weight blocks per down row -inline constexpr size_t BLOB = 3ull * (H * FF * BB / QK); // 1,382,400 - -// ---- the blob's internal layout (one expert) ---- -inline constexpr size_t O_GU_CODES = 0; -inline constexpr size_t O_D_CODES = 2ull * FF * ROW_GU; -inline constexpr size_t O_GU_SCALES = O_D_CODES + 1ull * H * ROW_D; -inline constexpr size_t O_D_SCALES = O_GU_SCALES + 2ull * FF * SC_GU * 2; - -/// One activation in Strata's planar storage: `QKA` elements per chunk. -/// The default legacy quantizer uses FP32 scales and half-away rounding. It is -/// not the pinned ggml CPU Q8_0 contract; expert_set_oracle_q8_0 selects that -/// experimental contract (FP16-rounded scales and x86 nearest-even codes). -/// -/// The historical function name `act_quant_q8_1` does not describe a native -/// ggml block layout. One 64-weight block always spans two 32-element chunks. -/// -/// `hx[k] = scale[k] * sum[k]` is the weight-independent correction the Q2_0 identity needs -/// (`sum (c-1) d_w xhat d_x = d_w (d_x*sum(c*xhat) - d_x*sum(xhat))`), precomputed once per layer rather than -/// once per row: 640 rows would otherwise recompute it 640 times. -struct ActQ { - alignas(64) int8_t q[H]; - float scale[MAXC]; - int32_t sum[MAXC]; - float hx[MAXC]; - int nchunks; -}; - -/// Per-worker scratch. Owned by the caller and passed in, so the token path performs NO allocations -/// (P2.T10) - the kernel itself allocates nothing. -struct ExpertScratch { - ActQ a1; - ActQ a2; - alignas(64) float ff[FF]; -}; - -/// Runtime CPU feature check. The kernel uses AVX512-VNNI + AVX512-VBMI + AVX512VL, and code compiled with -/// `/arch:AVX512` can emit AVX-512 anywhere in its translation unit, so a machine without them must be -/// REFUSED rather than silently run. `s2_expert_scalar` is the fallback and exists for tests. -struct CpuFeatures { - bool avx512f = false; - bool avx512bw = false; - bool avx512vl = false; - bool avx512_vnni = false; - bool avx512_vbmi = false; - bool usable() const { return avx512f && avx512bw && avx512vl && avx512_vnni && avx512_vbmi; } - /// A one-line description of what is missing, or "ok". - const char* reason() const; -}; -CpuFeatures cpu_features(); - -/// Exits with a clear message if the CPU cannot run `s2_expert_vnni`. Called once at startup, so a user on an -/// older CPU learns why at second zero instead of seeing an illegal instruction at token 4000. -void cpu_require_expert_support(); - -/// Select the pinned x86 Q8_0 activation contract at BOTH expert quantization -/// boundaries and the pinned generic CPU Q2_0 dot reduction in all projections. -/// Default false preserves the legacy quantizer and eight-lane FP32 reduction. -/// Configure before starting worker threads and do not change during a request. -/// GPU expert-cache parity is not established for this mode; the driver must -/// reject combining it with that cache. No allocation occurs in either mode. -void expert_set_oracle_q8_0(bool enabled); - -/// `x` -> `a` in the configured contract. The function name is historical; -/// `n` must be a multiple of QKA and at most H. No allocation occurs. -void act_quant_q8_1(const float* x, int n, ActQ& a); - -/// One expert: `out(H) = down( swiglu( gate(x), up(x) ) )`, all three projections Q2_0, -/// with the configured activation and dot contracts at both quantization boundaries. -/// -/// `blob` is one 1,382,400-byte expert in the pack's layout; `x` is the H-wide input; `out` is H-wide. -void s2_expert_vnni(const uint8_t* blob, const float* x, float* out, ExpertScratch& ws); - -/// The same, with the activation ALREADY quantized in the configured contract. -/// Workers may share this read-only activation; each must own its scratch/output. -/// -/// This split exists for the pool. A layer runs TEN experts against ONE activation, so quantizing inside -/// `s2_expert_vnni` would do the same 2560-element conversion ten times per layer per token - 480 redundant -/// conversions per token. P2.S3's work item is `(blob, x-hat quantized, block sums, weight, out)`, and this -/// is the entry point that matches it. -void s2_expert_vnni_q(const uint8_t* blob, const ActQ& a1, float* out, ExpertScratch& ws); - -/// Plan v0.3 P6: ONE expert applied to up to MAXT tokens that were all routed to it (a speculative verify -/// window routes ~1.5 tokens to each distinct expert). The 1.38 MB blob is read and its 2-bit codes unpacked -/// ONCE per block for all tokens; only the VNNI dot and the accumulation run per token. Every token's output -/// is bitwise equal to `s2_expert_vnni_q` on that token (same operation order per token). Legacy activation -/// contract only; with `expert_set_oracle_q8_0(true)` it falls back to one `s2_expert_vnni_q` per token. -inline constexpr int MAXT = 8; -/// Plan v0.3 P4: the expert in row ranges, so several threads can share one expert. `s2_expert_gu_rows` writes -/// ff[r] = silu(gate_r . x) * (up_r . x) for r in [r0, r1) (of FF); `s2_expert_down_rows` writes out[r] for r in -/// [r0, r1) (of H) from the intermediate's quantized image. Together with `act_quant_q8_1(ff, FF, a2)` in -/// between they are exactly `s2_expert_vnni_q`, row for row (same `row_dot`), so the result is bitwise the same. -bool expert_oracle_q8_0_enabled(); -void s2_expert_gu_rows(const uint8_t* blob, const ActQ& a1, float* ff, int r0, int r1); -void s2_expert_down_rows(const uint8_t* blob, const ActQ& a2, float* out, int r0, int r1); - -/// Plan v0.3 P6: the row-range kernels for up to MAXT tokens routed to the same expert (legacy contract only). -/// Each token's rows are bitwise the single-token `s2_expert_gu_rows` / `s2_expert_down_rows`. -void s2_expert_gu_rows_multi(const uint8_t* blob, const ActQ* const* a1, int n_tokens, float* const* ff, int r0, - int r1); -void s2_expert_down_rows_multi(const uint8_t* blob, const ActQ* const* a2, int n_tokens, float* const* out, int r0, - int r1); - -struct ExpertScratchMulti { - ActQ a2[MAXT]; - alignas(64) float ff[MAXT][FF]; - ExpertScratch single; // the oracle-contract fallback -}; -void s2_expert_vnni_multi(const uint8_t* blob, const ActQ* const* a1, int n_tokens, float* const* out, - ExpertScratchMulti& ws); - -/// The scalar transcription of ggml's formula - NOT a second opinion, but the ORACLE the VNNI path is checked -/// against, and the only path available on a CPU without AVX-512. -/// -/// `quant_acts` makes the oracle consume the SAME INT8 activation values the VNNI path uses, **at BOTH -/// stages**. With it OFF the oracle is exact-FP32-activation and the gap between them IS the activation -/// contract; with it ON the two differ only by FP32 evaluation order, so a small gap there proves the kernel -/// itself correct. That separation is the whole point of P0.T2 and it is why this parameter exists rather -/// than two functions. -/// -/// CORRECTION TO THE ORIGINAL: `bench/micro/cpu_s2.cpp`'s comment says "at both stages" but its code -/// quantizes only the intermediate, leaving the gate/up projections on raw f32 `x`. That is invisible when -/// the caller passes an already-quantized input - which the engine does - and shows up as a ~1.2% gap when it -/// does not, which reads as a kernel bug and is not one. This version quantizes both. -/// Plan v0.3 P6: rows [r0, r1) of a Q2_0 matrix in the GGUF block layout (18 bytes per 64 weights, `row_bytes` -/// per row, `nblocks` blocks each) against `nt` activations: out[t][r]. -void q2_0_gguf_rows_multi(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, - float* const* out, int r0, int r1); -/// The same two for CPUs without AVX-512 (src/kernels/cpu/q2_avx2.cpp, compiled for AVX2 only). -void q2_0_gguf_rows_multi_avx2(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, - float* const* out, int r0, int r1); -void act_quant_q8_1_avx2(const float* x, int n, ActQ& a); - -void s2_expert_scalar(const uint8_t* blob, const float* x, float* out, bool quant_acts); - -} // namespace strata::kernels::cpu diff --git a/include/strata/kernels/cpu/expert_layout.hpp b/include/strata/kernels/cpu/expert_layout.hpp deleted file mode 100644 index 5c35447..0000000 --- a/include/strata/kernels/cpu/expert_layout.hpp +++ /dev/null @@ -1,87 +0,0 @@ -// include/strata/kernels/cpu/expert_layout.hpp - plan v0.3 P6: where each routed expert lives in experts.bin. -// -// A Q2_0 pack (tools/strata_pack.py) has one blob size for every layer, `BLOB`, in the Strata expert form. A -// native pack (tools/iq_pack.py, the IQ2_XS / IQ3_XXS files) keeps each expert's raw GGUF slices, so the blob -// size and the formats change from layer to layer; `native_experts.txt` says how. Everything that touches an -// expert blob - the arena, the VRAM tier, the prompt path, the CPU pool, the GPU window - asks this table. -#pragma once - -#include "strata/kernels/cpu/expert.hpp" -#include "strata/kernels/cpu/native_expert.hpp" - -#include -#include -#include - -namespace strata::kernels::cpu { - -struct ExpertLayout { - bool native = false; - int64_t n_layers = 0, n_expert = NE; - std::vector fmt; ///< per layer (native packs) - std::vector offset, bytes; ///< per layer: where its 512 blobs start, bytes per blob - /// Plan v0.3 P6: per layer, the absolute offsets of the gate / up / down tensors in their GGUF files, so the - /// arena can be filled from the GGUF itself when the pack has no experts.bin (3 x n_layers, 0 = unknown). - std::vector gguf_off; - /// Per layer PER ROLE (3 x n_layers, `3 * layer + role`, matching `gguf_off`), the GGUF file - a name beside - /// the --native shard - that holds that role's tensor. Empty = the --native shard itself. Per role because a - /// shard boundary can fall inside a layer: Unsloth's UD-Q4_K_XL has layer 11's down in shard 2 and its gate - /// and up in shard 3 (native_experts.txt v4, the `gate,up,down` shard column). - std::vector gguf_file; - int version = 0; ///< native_experts.txt's header version (0 = none given) - uint64_t max_blob = BLOB; - uint64_t total = 0; ///< experts.bin size - - uint64_t blob_bytes(int64_t layer) const { return native ? bytes[(size_t) layer] : (uint64_t) BLOB; } - uint64_t layer_offset(int64_t layer) const { - return native ? offset[(size_t) layer] : (uint64_t) layer * (uint64_t) n_expert * (uint64_t) BLOB; - } - uint64_t blob_offset(int64_t layer, int64_t expert) const { - return layer_offset(layer) + (uint64_t) expert * blob_bytes(layer); - } -}; - -/// Plan v0.3 P6: whether this CPU (and its OS) runs the AVX-512 kernels (F, BW, VL, VNNI, VBMI). Probed in a -/// file compiled without AVX-512, so asking is safe everywhere; STRATA_FORCE_AVX2=1 answers no (for tests). -bool cpu_avx512_ok(); -/// Whether this CPU runs AVX-512F + AVX-512BW + AVX-512VL + AVX-512DQ (e.g. Skylake-X i9-9920X) for iq_avx512.cpp. -bool cpu_avx512bw_ok(); -/// Whether this CPU (and its OS) runs the AVX2 kernels (AVX, AVX2, FMA, F16C): the floor of every expert kernel -/// (q2_avx2.cpp, iq_avx2.cpp, and ggml-cpu in the portable build). STRATA_FORCE_AVX2 does not change it. -bool cpu_avx2_ok(); -/// Whether this CPU (and its OS) runs AVX (Sandy Bridge and newer): the AVX1 router dot (kq_avx1.cpp) and ggml-cpu in -/// a STRATA_ISA_FLOOR=avx build. The other expert rows then run on ggml-cpu (experimental, slow). -bool cpu_avx1_ok(); -/// SSE4.2 + POPCNT: ggml-cpu in a STRATA_ISA_FLOOR=none build. -bool cpu_sse42_ok(); -/// STRATA_FORCE_ISA=avx2|avx|sse caps the probes above (3 = no cap, 2 = AVX2, 1 = AVX, 0 = SSE4.2), so the older-CPU -/// paths run on any PC: tests and the experimental builds' checks. ggml-cpu keeps what it was compiled for. -int cpu_isa_cap(); -/// The experimental older-CPU build this engine is ("avx", "sse4.2"), or "" for the normal build (AVX2 floor). -const char* isa_floor_build(); -/// Whether a native pack's layer of this ggml type runs on Strata's own Q2_0 kernels (AVX2 / AVX-512). On a -/// CPU without AVX2 (a native, non-portable build: ggml-cpu compiled for this CPU's SSE) a Q2_0 layer takes -/// ggml-cpu's own Q2_0 vec_dot like every other native type: slower, but it runs. -inline bool q2_native_kernels(int type) { return type == 42 && cpu_avx2_ok(); } -/// The CPU's brand string (CPUID 0x80000002..4), for messages; "unknown" when it has none. -std::string cpu_name(); -/// Q2_0 GGUF rows / activation quantizer on the kernels this CPU has. -void q2_rows_any(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, float* const* out, - int r0, int r1); -void act_quant_any(const float* x, int n, ActQ& a); - -/// The process-wide layout (canonical Q2_0 until `expert_layout_load` finds a native pack). -const ExpertLayout& expert_layout(); -/// Reads `/native_experts.txt` when it exists (a native pack), else sets the canonical layout. -/// Versions up to kExpertLayoutVersion are read; a newer one is refused (a newer packer wrote it). -/// `n_embd` / `n_ff` are the MODEL's widths (ModelGeometry, read from the model file): each layer's `NativeFmt` is -/// built with them and its byte count checked against the pack's blob size, so a pack of another geometry is refused -/// here by its numbers. Until Phase 2 step 2 of the Qwen3.6 port this passed the compile-time 2560/640 -/// (geometry-inventory.md row 108), which refused every 2048/512 pack as "blob is X B but its formats make Y". -bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int64_t n_embd, int64_t n_ff, - std::string& err); -/// 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; - -} // namespace strata::kernels::cpu diff --git a/include/strata/kernels/cpu/iq_avx2.hpp b/include/strata/kernels/cpu/iq_avx2.hpp deleted file mode 100644 index a9628d3..0000000 --- a/include/strata/kernels/cpu/iq_avx2.hpp +++ /dev/null @@ -1,26 +0,0 @@ -// include/strata/kernels/cpu/iq_avx2.hpp - AVX-2 multi-token dot products for the i-quant expert -// formats (IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S, IQ4_XS) against Q8_K activations (ggml's block_q8_K). -// -// The AVX-512 kernel's scheme on the CPUs without it (AMD Zen 2/3, Intel Core 12th-14th gen): the weights of a -// 32-value chunk are decoded once per verify window and every token applies them with five instructions. -#pragma once - -#include -#include - -namespace strata::kernels::cpu { - -bool iq256_supported(int ggml_type) noexcept; -/// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]), rows [r0, r1); gate rows at blob, up rows at blob + up_off. -void iq256_gu_rows(int ggml_type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, - int nt, float* const* ff, int r0, int r1); -/// out[t][r] = w_r . a[t], rows [r0, r1). -void iq256_rows(int ggml_type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, - float* const* out, int r0, int r1); - -/// out[t][r] = w_r . h[t] for IQ4_NL (type 20) rows against Q8_0 activations (ggml's block_q8_0). -/// IQ4_NL is a 32-value-block format, so this does not go through iq256_rows (QK_K blocks, Q8_K acts). -void iq4nl256_down_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* hq, int nt, - float* const* out, int r0, int r1); - -} // namespace strata::kernels::cpu diff --git a/include/strata/kernels/cpu/iq_avx512.hpp b/include/strata/kernels/cpu/iq_avx512.hpp deleted file mode 100644 index a9a71c4..0000000 --- a/include/strata/kernels/cpu/iq_avx512.hpp +++ /dev/null @@ -1,18 +0,0 @@ -// include/strata/kernels/cpu/iq_avx512.hpp - plan v0.3 P6: AVX-512 multi-token dot products for the i-quant -// expert formats (IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S) against Q8_K activations (ggml's block_q8_K). -#pragma once - -#include -#include - -namespace strata::kernels::cpu { - -bool iq512_supported(int ggml_type) noexcept; -/// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]), rows [r0, r1); gate rows at blob, up rows at blob + up_off. -void iq512_gu_rows(int ggml_type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, - int nt, float* const* ff, int r0, int r1); -/// out[t][r] = w_r . a[t], rows [r0, r1). -void iq512_rows(int ggml_type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, - float* const* out, int r0, int r1); - -} // namespace strata::kernels::cpu diff --git a/include/strata/kernels/cpu/kq_avx1.hpp b/include/strata/kernels/cpu/kq_avx1.hpp deleted file mode 100644 index c9afc3f..0000000 --- a/include/strata/kernels/cpu/kq_avx1.hpp +++ /dev/null @@ -1,18 +0,0 @@ -// include/strata/kernels/cpu/kq_avx1.hpp - the AVX1 router dot for older CPUs (from the Strata_Dirigo fork). -// -// bf16_rows_dot_multi (kq_avx2.cpp) is compiled with -mavx2 and uses instructions an AVX-only CPU does -// not have (`vpmovzxwd`, `vfmadd`), so an AVX-only host cannot call it at all. This is the same -// arithmetic on AVX1 instructions: 8 float lanes per token, one weight stream per row shared by all -// `nt` tokens, one horizontal sum per (row, token). AVX1 has no FMA, so the multiply and the add stay -// separate; it has no 256-bit integer ops, so the bf16 -> f32 widening runs in 128-bit halves. -#pragma once - -#include - -namespace strata::kernels::cpu { - -/// Mirrors bf16_rows_dot_multi's arithmetic (same accumulation shape, mul+add instead of FMA). -/// Requires cols % 8 == 0 and nt <= 8, exactly like the AVX2 kernel it stands in for. -void bf16_rows_dot_multi_avx1(const uint16_t* w, int rows, int cols, const float* x, int nt, float* out); - -} // namespace strata::kernels::cpu diff --git a/include/strata/kernels/cpu/kq_avx2.hpp b/include/strata/kernels/cpu/kq_avx2.hpp deleted file mode 100644 index 01b7a63..0000000 --- a/include/strata/kernels/cpu/kq_avx2.hpp +++ /dev/null @@ -1,25 +0,0 @@ -// include/strata/kernels/cpu/kq_avx2.hpp - AVX-2 multi-token dot products for Unsloth UD-Q4_K_XL's expert formats -// (Q4_K gate/up against Q8_K activations; Q5_1 down against Q8_1, Q8_0 down against Q8_0), bit-exact against -// ggml-cpu's AVX2 vec_dot for every token. See src/kernels/cpu/kq_avx2.cpp. -#pragma once - -#include -#include - -namespace strata::kernels::cpu { - -/// Q4_K (12), Q5_1 (7), Q8_0 (8). -bool kq256_supported(int ggml_type) noexcept; -/// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]), rows [r0, r1); gate rows at blob, up rows at blob + up_off. -void kq256_gu_rows(int ggml_type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, - int nt, float* const* ff, int r0, int r1); -/// out[t][r] = w_r . a[t], rows [r0, r1). -void kq256_rows(int ggml_type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, - float* const* out, int r0, int r1); - -/// out[r] = w_r . x for BF16 rows (bits), fp32 x: the routing-aware prefetch's router (an estimate only). -void bf16_rows_dot(const uint16_t* w, int rows, int cols, const float* x, float* out); -/// The same for `nt` <= 8 tokens (x: nt rows of cols, cols % 8 == 0), out[t * rows + r]. -void bf16_rows_dot_multi(const uint16_t* w, int rows, int cols, const float* x, int nt, float* out); - -} // namespace strata::kernels::cpu diff --git a/include/strata/kernels/cpu/native_expert.hpp b/include/strata/kernels/cpu/native_expert.hpp deleted file mode 100644 index 9b80742..0000000 --- a/include/strata/kernels/cpu/native_expert.hpp +++ /dev/null @@ -1,49 +0,0 @@ -// include/strata/kernels/cpu/native_expert.hpp - plan v0.3 P6: one routed expert in its GGUF form on the CPU. -// -// The IQ2_XS / IQ3_XXS model files keep their experts in i-quant formats (IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, -// IQ3_S gate/up; Q2_0 or IQ4_NL down) whose values cannot be re-expressed in the Q2_0 pack form. A native expert -// blob is the three GGUF slices back to back, [gate rows | up rows | down rows], and the arithmetic is ggml-cpu's -// own (`ggml_get_type_traits_cpu`): the activation is quantized with the weight type's `vec_dot_type` and each row -// is one `vec_dot`, exactly what llama.cpp's CPU backend computes for the same tensor. -#pragma once - -#include -#include -#include - -namespace strata::kernels::cpu { - -/// Bytes of the largest quantized activation any native layer uses (2560 values as Q8_K: 10 x 292). -inline constexpr size_t kNativeActBytes = 4096; -/// Bytes of the largest quantized down activation (640 values as Q8_0: 20 x 34, or Q8_K 3 x 292). -inline constexpr size_t kNativeHBytes = 1024; - -/// One layer's native expert geometry. -struct NativeFmt { - int gu_type = -1, d_type = -1; ///< ggml types of gate/up and of down - int gu_act = -1, d_act = -1; ///< their vec_dot_type (the activation formats) - int64_t n_embd = 0, n_ff = 0; - size_t gu_row = 0, d_row = 0; ///< bytes per weight row - size_t up_off = 0, down_off = 0; ///< inside the blob - size_t bytes = 0; ///< the whole blob - size_t act_bytes = 0, h_bytes = 0; ///< quantized activation sizes (n_embd of gu_act, n_ff of d_act) -}; - -/// Whether this build has the ggml-cpu path. -bool native_experts_available() noexcept; -/// Fills `f` for a layer; false (with a reason) when ggml-cpu has no dot product for a type. -bool native_fmt(int gu_type, int d_type, int64_t n_embd, int64_t n_ff, NativeFmt& f, std::string& err); - -/// x (n_embd floats) -> the gate/up activation (act_bytes). -void native_quant_act(const NativeFmt& f, const float* x, void* dst); -/// h (n_ff floats) -> the down activation (h_bytes). -void native_quant_h(const NativeFmt& f, const float* h, void* dst); - -/// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]) for rows r in [r0, r1), `nt` tokens. -void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const* act, int nt, float* const* ff, - int r0, int r1); -/// out[t][r] = down_r . hq[t] for rows r in [r0, r1). -void native_down_rows(const NativeFmt& f, const uint8_t* blob, const void* const* hq, int nt, float* const* out, - int r0, int r1); - -} // namespace strata::kernels::cpu diff --git a/include/strata/kernels/cpu/pool.hpp b/include/strata/kernels/cpu/pool.hpp deleted file mode 100644 index 662bb03..0000000 --- a/include/strata/kernels/cpu/pool.hpp +++ /dev/null @@ -1,286 +0,0 @@ -// include/strata/kernels/cpu/pool.hpp - P2.S3: the CPU expert pool. -// -// A layer runs TEN experts against ONE activation, and the expert kernel is DRAM-bound (Memory/LEDGER.md L9: -// 42.55 GB/s on 6 cores, tracking core count almost exactly). So the pool's job is not to be clever - it is -// to keep every physical core reading expert bytes for the whole layer, and to be cheap enough that ten -// dispatches per layer cost less than one expert. -// -// WHY A FLAT BATCH AND NOT A RING. P2.S3 describes a "lock-free SPMC ring", which is what you need when -// jobs arrive while others are still being computed. Here they cannot: the host must SUM all ten outputs -// before the next layer starts, so a layer is a barrier by construction and the queue never holds more than -// one batch. A ring would add a wrap-around to get wrong and buy nothing. What is kept from the phase is -// the part that matters: `head`/`done` are single fetch_add counters, one claim per worker, no lock. -// -// THE COMPLETION PROTOCOL, because this is where a pool usually goes wrong. `run()` waits for `done == n` -// AND for every worker to PARK. Waiting only for `done` is not enough: a worker can still be inside the -// drain loop after its last `done` increment, and the host resetting `head` underneath it would let that -// worker claim a job from the NEXT batch before the next batch has been published. -// -// **AND `parked` IS NOT ENOUGH EITHER (issue #29).** A worker that went to sleep (after `kSpinBeforeSleep`) is -// still counted as parked when it wakes, so for a moment after it has seen a new epoch the host believes it is -// idle. On a card with most experts in VRAM the workers sleep in the middle of a request, tiny batches finish -// before a sleeper is awake, and that moment comes round constantly: a late worker could claim from the NEXT -// batch while the host was still writing it, run a job twice, or add to `done` after the host had reset it - -// and `done != n` then never ended, with the GPU waiting on the pool forever. So every claim carries its -// batch: `head` is one 64-bit word `epoch | njobs | index`, a claim is a CAS that only succeeds for the epoch -// the worker woke for, and a late worker's claim simply fails. A claim that succeeds belongs to the current -// batch, whose description the host cannot change until that job's `done` has landed. -#pragma once - -#include "strata/kernels/cpu/expert.hpp" -#include "strata/kernels/cpu/native_expert.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace strata::kernels::cpu { - -/// One expert evaluation. `act` is SHARED and read-only across the whole batch - that sharing is the point -/// of `s2_expert_vnni_q` and it is what saves 480 redundant activation conversions per token. -struct ExpertJob { - const uint8_t* blob = nullptr; ///< one 1,382,400-byte expert - const ActQ* act = nullptr; ///< the layer's quantized activation, shared - float* out = nullptr; ///< H floats, written by exactly one worker - float weight = 1.0f; ///< the router weight; applied by the HOST, not here - int slot = -1; ///< the job's index, for diagnostics -}; - -/// Plan v0.3 P6: one expert for the `nt` tokens of a verify window that were routed to it. Every token's output -/// is bitwise the single-token job's. -struct ExpertJobMulti { - const uint8_t* blob = nullptr; - int nt = 0; - const ActQ* act[MAXT] = {}; - float* out[MAXT] = {}; - /// Plan v0.3 P6: a native pack's activations (the layer's `vec_dot_type`), one per token. - const void* nact[MAXT] = {}; -}; - -/// How worker threads are allocated across physical/logical CPU cores (#272). `All` is the layout the pool has -/// always used and the default; the hybrid-aware ones are opt-in (--pool-affinity auto|p-cores). -enum class PoolAffinity { - Auto, ///< Hybrid: prioritize physical P-cores, then SMT, then E-cores (defaults to P-core count) - PCores, ///< Restrict workers strictly to Performance cores and their SMT siblings - All, ///< The default: one worker per physical core in the OS's order, without hybrid distinction -}; - -struct CpuTopology { - bool is_hybrid = false; - int p_cores = 0; ///< Physical performance cores - int p_threads = 0; ///< Total logical threads on performance cores - int e_cores = 0; ///< Efficient cores - std::vector worker_cores; ///< Ordered CPU IDs; on Windows, group * 64 + processor within the group - int host_core = -1; ///< Logical core reserved for host thread -}; - -CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity = PoolAffinity::All); - -/// One logical processor per PHYSICAL core, so a worker is never scheduled onto an SMT sibling of another -/// worker. On the 6-core/12-thread machine this project measures on, `hardware_concurrency()/2` workers on -/// logical processors 0..5 would put every worker on a sibling pair and halve the useful bandwidth - which is -/// exactly the kind of error that shows up as "the CPU path is slower than the model says" with no clue why. -/// -/// `skip_first` drops the first core, which P2.S3 reserves for the host loop. -std::vector physical_cores(bool skip_first, PoolAffinity affinity = PoolAffinity::All); - -/// **THE RESERVATION IS A FICTION UNLESS THE HOST IS ACTUALLY PUT THERE.** -/// -/// `physical_cores(true)` keeps the workers off the first physical core so that the host loop can spin on -/// `cudaEventQuery` without stealing a worker's cycles. Nothing in the pool can enforce the other half of -/// that, so this is it: the host loop calls this on entry and restores on exit. -/// -/// MEASURED, and this is why it exists: the pool runs at **36.32 GB/s on 5 workers with nothing else running** -/// - exactly 5/6 of L9's 44.14 on 6 - and at **26.9 GB/s inside the host loop**, where the unpinned spinning -/// host is free to land on a worker's core or its SMT sibling. That 1.35x is not the kernel. -/// -/// The previous host placement. `valid` is false when querying or setting placement failed. -/// Windows uses a reversible CPU Set selection, leaving hard affinity (including Windows 11's implicit -/// all-group eligibility) untouched. An empty selection restores inheritance from the process defaults. -/// Linux stores the complete, dynamically sized native CPU mask, including CPU IDs above 63. -struct ThreadAffinity { -#if defined(_WIN32) - std::vector cpu_sets; -#else - std::vector mask; -#endif - bool valid = false; -}; - -/// Selects one encoded processor for the caller; Windows CPU Sets respect existing hard-affinity limits. -/// Restore on the same calling thread. Pool-owned workers use hard group affinity instead. -ThreadAffinity pin_current_thread(int core); -void restore_thread_affinity(const ThreadAffinity& previous); - -class ExpertPool { -public: - /// `n_workers <= 0` means "every physical core except the first". Workers are pinned to physical cores - /// (minus core 0 by default) and each owns one `ExpertScratch`, so nothing in the token path allocates. - /// - /// **`host_works` PUTS THE HOST THREAD INTO THE DRAIN (R2.2's FIRST HALF).** - /// - /// The pool reserves core 0 for the host loop so the doorbell spin cannot steal a worker's cycles - but - /// during `run()` the host does not spin, it waits, so core 0 is idle for the whole drain. Measured on the - /// 6-core machine this project targets: the engine's pool drains at **33.7 GB/s** (663.6 MB of expert - /// blobs in 19.71 ms/token) where the same kernel on 5 workers should reach 5/6 x 44.14 = 36.8 and the - /// machine measures 44.14 GB/s on all six. So the sixth core is being paid for and not used. - /// - /// With `host_works`, `run()` claims jobs itself instead of spinning on `done_`, and the pool is six - /// threads on six cores. `false` is the A/B arm and exists so the change is measurable rather than - /// asserted - the counter it moves is `pool phases ... drain`, which is host-side and needs no profiler. - explicit ExpertPool(int n_workers = 0, bool pin = true, bool host_works = true, - PoolAffinity affinity = PoolAffinity::All); - /// The watchdog's view of the pool (issue #31): the batch, the counters, every thread's state. - void diag(std::FILE* f) const; - ~ExpertPool(); - ExpertPool(const ExpertPool&) = delete; - ExpertPool& operator=(const ExpertPool&) = delete; - - int workers() const { return n_; } - /// Whether the host thread also drains. Reported at startup, because "the engine adapts to the machine it - /// is on" is only true if the engine says which adaptation it took. - bool host_works() const { return host_works_; } - - bool is_hybrid() const { return topo_.is_hybrid; } - int p_cores() const { return topo_.p_cores; } - int p_threads() const { return topo_.p_threads; } - int e_cores() const { return topo_.e_cores; } - PoolAffinity affinity() const { return affinity_; } - - /// Publish `n` jobs, then block until every one has been claimed AND every worker has parked. - /// `jobs` must outlive the call (it does, and the workers never touch it afterwards). - void run(ExpertJob* jobs, int n); - - /// Plan v0.3 P4: the same outputs as `run`, bitwise, with every expert split by rows across all threads - /// (gate/up rows, then the intermediate's quantization, then down rows). With fewer experts than threads - - /// the case once the VRAM tier takes half of them - `run` leaves cores idle and each expert streams at one - /// core's bandwidth; this streams every expert at all of them. At most `kMaxSplit` experts. - void run_split(ExpertJob* jobs, int n); - static constexpr int kMaxSplit = 16; - /// Plan v0.3 P6: `run_split` for multi-token jobs (at most `kMaxSplitMulti`); the rows of each expert are - /// read once for all of its tokens. - void run_split_multi(ExpertJobMulti* jobs, int n); - /// Plan v0.3 P6: the same for a native pack's layer (ggml-cpu arithmetic, `nact` activations). - void run_split_multi_native(const NativeFmt& f, ExpertJobMulti* jobs, int n); - static constexpr int kMaxSplitMulti = 96; - /// run_split_multi's phases, accumulated ms: gate/up rows, the intermediate quantization, down rows. - double ms_multi_gu = 0, ms_multi_q = 0, ms_multi_down = 0; - int64_t multi_bytes = 0; - - /// Total `_mm_pause` iterations spent waiting, over all workers, is no longer counted - see the note on the - /// atomics below. It was a LOCKED read-modify-write in the park loop, so measuring the contention added to - /// it. - long long pauses() const { return 0; } - - /// **WHERE `run()` SPENDS ITS TIME, in milliseconds accumulated over its lifetime.** Three phases per - /// layer - wait for every worker to be parked, wait for the drain, wait for them to re-park - and until now - /// all three were reported as one number. Without the split there is no way to tell a pool that is slow at - /// the WORK from one that is slow at the SYNCHRONISATION, and those need opposite fixes: the first is a - /// kernel problem and the second is a barrier problem. - /// - /// Only the host thread touches these, in `run()`, so they need no atomics. - void phase_ms(double& wait_park, double& drain, double& repark) const { - wait_park = ms_wait_park_; - drain = ms_drain_; - repark = ms_repark_; - } - - /// **A PARKED WORKER SPINS FOR THIS LONG, THEN SLEEPS.** The park is a `_mm_pause` spin because a layer's - /// batches are microseconds apart and a wake-up from the OS costs more than that. But a spin that never ends - /// keeps every worker's core at 100% while the engine waits for a request - issue #4, "CPU 50% even when - /// doing nothing" (7 of the 5700X's 16 threads). Between requests the workers block on `sleep_cv_`. NOT only - /// between requests: with most experts in VRAM (a 24 GB card) many layers have no CPU work, so the workers - /// also sleep mid-request - which the claim protocol above must survive (issue #29). - /// `STRATA_POOL_SPIN_US` overrides it (a test knob: a short spin makes the workers sleep constantly). - static constexpr std::chrono::milliseconds kSpinBeforeSleep{20}; - /// A pool wait that sees no completion for this long is a bug; the engine stops with a message instead of - /// spinning forever, and the server starts it again (issue #29). - static constexpr std::chrono::seconds kStall{60}; - -private: - void worker(int id); - void drain(int id, ExpertScratch& scratch, uint32_t epoch); - void run_phase(int mode, int n_tasks); - /// Claim the next job of batch `epoch`, or -1 (that batch is exhausted, or it is not the current one). - int claim(uint32_t epoch); - /// Publish the batch whose description the caller has just written: reset `done`, then `head`, then the epoch. - uint32_t begin_batch(int n); - /// The host's waits, bounded by `kStall`. - void wait_parked(const char* what); - void wait_done(int n); - /// Bump `epoch_`, and wake the workers that went to sleep. Every publish goes through here. - void publish(); - - int n_ = 0; - bool host_works_ = true; - ExpertJob* jobs_ = nullptr; - int njobs_ = 0; - /// The host's own scratch when `host_works_`. A separate object rather than a share of `scratch_[i]`, - /// because a worker may own any index and the two must not be able to collide. - ExpertScratch host_scratch_; - // `run()`'s three phases, accumulated. Host-thread only; see `phase_ms`. - double ms_wait_park_ = 0.0; - double ms_drain_ = 0.0; - double ms_repark_ = 0.0; - // ---- EACH ATOMIC GETS ITS OWN CACHE LINE, AND THE SPIN COUNTER IS GONE. (Review finding C3.) - // - // These were six adjacent atomics, which put `head_`, `done_`, `parked_` and `epoch_` on ONE cache line - - // the four that workers and the host actually contend on, invalidating each other on every access. - // - // Worse, the parked spin did `pauses_.fetch_add(1)` on EVERY iteration: a LOCKED read-modify-write, five - // workers against one line, at roughly one iteration per `_mm_pause`. So the line the host must WRITE to - // publish work (`epoch_`) and READ to confirm the workers are parked (`parked_`) was being hammered by the - // very threads waiting for it. That is contention the pool imposes on itself. - // - // The counter was diagnostic only - `pauses()` was read in one place, to print a number nothing branched on - // - so it is deleted rather than amortised. `alignas(64)` then stops the remaining four sharing. - // issue #31 diagnostics: each worker's state (kParked, kSleeping, kBetween, or the job it runs) and the host's - // (kIdle, kWaitParked, kWaitDone, or its job), printed by the serve watchdog through `diag` - static constexpr int32_t kParked = -1, kSleeping = -2, kBetween = -3, kIdle = -10, kWaitParked = -11, - kWaitDone = -12; - std::unique_ptr[]> wstate_; - std::atomic hstate_{kIdle}; - std::atomic hstate_ms_{0}; - alignas(64) std::atomic head_{0}; // epoch << 32 | njobs << 16 | next index (issue #29) - alignas(64) std::atomic done_{0}; - alignas(64) std::atomic parked_{0}; - alignas(64) std::atomic epoch_{0}; - alignas(64) std::atomic stop_{false}; - // The sleep after `kSpinBeforeSleep`. `sleepers_` is how `publish` knows whether anyone needs waking, so the - // token path pays one uncontended load per publish and never takes the mutex while the workers spin. - alignas(64) std::atomic sleepers_{0}; - std::mutex sleep_mu_; - std::condition_variable sleep_cv_; - std::chrono::microseconds spin_before_sleep_{kSpinBeforeSleep}; - std::vector threads_; - std::vector scratch_; // one per worker: no allocation, no false sharing of the hot data - // run_split state: mode 0 = whole experts, 1 = gate/up row parts, 2 = down row parts - int mode_ = 0; - int parts_a_ = 1, parts_b_ = 1; - struct SplitBuf { - alignas(64) float ff[FF]; - ActQ a2; - }; - std::vector split_; - // run_split_multi state: mode 3 = gate/up row parts, 4 = down row parts - ExpertJobMulti* mjobs_ = nullptr; - int64_t mrows_ = 0; // rows of the current multi phase across all its experts (n * FF, then n * H) - int mtasks_ = 1; // equal row ranges the phase is cut into - struct SplitBufMulti { - alignas(64) float ff[MAXT][FF]; - ActQ a2[MAXT]; - alignas(64) uint8_t hq[MAXT][kNativeHBytes]; // plan v0.3 P6: native down activations - }; - const NativeFmt* nfmt_ = nullptr; - std::vector split_multi_; - PoolAffinity affinity_ = PoolAffinity::All; - CpuTopology topo_; -}; - -} // namespace strata::kernels::cpu diff --git a/include/strata/kernels/cvec.hpp b/include/strata/kernels/cvec.hpp deleted file mode 100644 index a447eb5..0000000 --- a/include/strata/kernels/cvec.hpp +++ /dev/null @@ -1,61 +0,0 @@ -// include/strata/kernels/cvec.hpp - a control vector on the residual stream: the engine's side of llama.cpp's -// `llama_adapter_cvec` with the `--cvec-mode` / `--cvec-dir` extension of the `experimental-speed-projection` -// package (its `02-cvec-projection-mode.patch`, and `01-qwen4exp-cvec-hooks.patch` for WHERE it applies). -// -// After layer l's FFN write - llama.cpp's `build_cvec(res_hc, il)` right after the layer's second -// `build_hc_combine` - every one of the hc residual streams h of every token becomes -// -// project: h <- h - s_l (h . v_l) v_l v_l = d / |d|, s_l = |d|, d = the scaled direction -// add: h <- h + d llama.cpp's stock additive control vector -// -// for l in [first, last]. `d` is the GGUF's `direction.` times the file's scale (summed over files), with -// src = l (per-layer) or one fixed layer (single:L, project mode only), exactly as llama.cpp's loader places it; -// layer 0 has no direction. Off unless a vector is loaded (--control-vector-scaled); a loaded one is switched -// per request through a device flag, so the captured graphs are the same either way. With the flag off the -// result is bit-identical to the engine without a vector: the kernel then only applies the pending residual -// write, with the fused read's own arithmetic. -#pragma once - -#include -#include -#include - -namespace strata::kernels { - -struct Cvec { - const float* dir = nullptr; ///< device, n_layers * n_embd: project = the unit v_l, add = d_l; zero rows elsewhere - const float* s = nullptr; ///< device, n_layers: project = s_l, add = 1; 0 = the layer is not steered - const int* on = nullptr; ///< device int: 0 = this request runs the stock model - int mode = 0; ///< 0 = project, 1 = add - int first = 0, last = -1; ///< the steered layers, inclusive - int64_t n_embd = 0, hc = 0; - bool loaded() const { return dir != nullptr; } - /// Layer l's FFN write is followed by the vector (with a real direction there). Decided at load time, never - /// per request: it changes where the residual write happens, so the graphs depend on it. - bool covers(int64_t l) const { return loaded() && l >= first && l <= last && l < (int64_t) steered.size() && steered[(size_t) l]; } - std::vector steered; ///< host copy of s_l != 0 -}; - -/// The loaded vector (empty until `cvec_upload`). -const Cvec& cvec(); - -/// Upload a vector built by the loader: `dir` is n_layers * n_embd, `s` n_layers (see `Cvec`). Starts ON. -bool cvec_upload(const std::vector& dir, const std::vector& s, int mode, int first, int last, - int64_t n_embd, int64_t hc, std::string& err); - -/// A layer split: put the loaded vector's tables on the CURRENT device too (cvec_apply uses the tables of the device -/// it runs on). No-op without a vector or when this device has them already. -bool cvec_replicate(std::string& err); - -/// The per-request switch, on every device that holds the vector. Synchronizes them when it changes, so call it -/// between requests. -void cvec_set_enabled(bool on); -bool cvec_enabled(); - -/// Layer `layer`'s vector on T tokens' residual stacks (`R + t * r_ld`, hc streams of n_embd). With `write`, the -/// pending FFN write `R += bo * 2 sigmoid(inj / hc)` (the fused read's arithmetic) is applied first, for callers -/// whose writes are folded into the next layer's read; without it, R must already hold the layer's output. -void cvec_apply(float* R, int64_t layer, int64_t T, int64_t r_ld, const float* bo, int64_t bo_ld, const float* inj, - int64_t inj_ld, bool write, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/dequant_bf16.hpp b/include/strata/kernels/dequant_bf16.hpp deleted file mode 100644 index 5a8ed08..0000000 --- a/include/strata/kernels/dequant_bf16.hpp +++ /dev/null @@ -1,27 +0,0 @@ -// include/strata/kernels/dequant_bf16.hpp - plan v0.3 P5: native GGUF blocks -> BF16 on the device, for the -// tensor-core GEMMs of batched prompt processing. -// -// One thread per 32-element group, transcribed from the reference `dequantize_row_*` functions of the pinned -// llama.cpp (`ggml/src/ggml-quants.c`, MIT): Q4_0 (2), Q5_0 (6), Q8_0 (8), Q3_K (11), Q4_K (12), Q5_K (13), Q6_K (14), -// IQ4_NL (20), IQ4_XS (23) and Q2_0 (42). A row-major (n_rows, n_cols) tensor of blocks becomes a row-major BF16 -// matrix; `n_cols` must be a multiple of the type's block size. -#pragma once - -#include - -namespace strata::kernels { - -bool dequant_bf16_supported(int ggml_type) noexcept; - -/// `rows` rows of `cols` values starting at block row `row0` (so a caller can dequantize a slice of a tensor). -void dequant_bf16(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, uint16_t* out, - void* stream); - -/// The same into FP16 bits (the prompt path's quantized-weight GEMMs: Q2_0 values are exact in FP16). -void dequant_f16(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, uint16_t* out, - void* stream); - -/// The same into FP32 (tests and small tensors). -void dequant_f32(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, float* out, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/dequant_s2.hpp b/include/strata/kernels/dequant_s2.hpp deleted file mode 100644 index 2603f48..0000000 --- a/include/strata/kernels/dequant_s2.hpp +++ /dev/null @@ -1,18 +0,0 @@ -// include/strata/kernels/dequant_s2.hpp - the S2 decode, host-callable. -// -// S2 is Q2_0's canonical form and 31.64 GiB of the artifact is Q2_0, so this is the hottest decode in the -// engine. Plane layout is docs/pack-format.md's: codes packed 4 per byte LSB-first (element i at byte i/4, -// bits (i%4)*2) and one FP32 scale per group of 64. Decode is `(code - 1) * scale` with the subtraction in -// the INTEGER domain, which is what makes it bit-exact (docs/pack-format.md §3.1). -#pragma once - -#include - -namespace strata::kernels { - -// Decode `n_blocks` S2 blocks. `codes` is n_blocks*16 bytes, `scales` n_blocks floats, `out` n_blocks*64 -// floats. All device pointers. Synchronises before returning, so a caller can read `out` immediately - -// correctness first; overlap is a Phase 3 concern. -void dequant_s2(const uint8_t* codes, const float* scales, float* out, int64_t n_blocks); - -} // namespace strata::kernels diff --git a/include/strata/kernels/dp4a.hpp b/include/strata/kernels/dp4a.hpp deleted file mode 100644 index e73be4d..0000000 --- a/include/strata/kernels/dp4a.hpp +++ /dev/null @@ -1,45 +0,0 @@ -// include/strata/kernels/dp4a.hpp - the two instructions the kernels use that Pascal (sm_60) does not have. -// -// The engine is written for compute capability 7.5 and newer and refuses older cards at CMake configure time -// (a Pascal build passes -DSTRATA_EXPERIMENTAL_SM60=ON). A GP100-class card is compute capability 6.0, which is -// missing exactly two things the i-quant kernels rely on: -// -// * `__dp4a`, a byte-wise dot product, available from 6.1 (Pascal GP10x/GV11x). Its fallback below is -// llama.cpp's own (`ggml/src/ggml-cuda/common.cuh`), which is the reference for the kernels in this -// directory: they are transcribed from llama.cpp's vecdotq.cuh, and that wrapper's operands are the same -// sites. It reinterprets the operands as SIGNED bytes and accumulates in int32, which is what `__dp4a` -// does for these calls, so the fallback is bit-exact rather than merely close. -// * `__nanosleep`, available from 7.0 (Volta). It only paces single-thread doorbell waits, so a loop that -// spins without it is correct, merely busier. -// -// Both are compile-time selections on `__CUDA_ARCH__`, so one source tree builds for Pascal and for RTX -// 20/30/40/50 without a #define at the call sites. A HIP build never takes either fallback: `__CUDA_ARCH__` is -// undefined there, so `STRATA_DP4A` is `__dp4a` (which `hip_compat/intrinsics.hpp` provides) and the pause is -// HIP's own `__nanosleep`. -#pragma once - -#include -#if defined(STRATA_HIP_GFX906) -#include // gfx906: the compat layer (__forceinline__, __nanosleep, __dp4a) -#endif - -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 610 -__device__ __forceinline__ int strata_dp4a(const int a, const int b, const int c) { - const int8_t* a8 = (const int8_t*) &a; - const int8_t* b8 = (const int8_t*) &b; - return c + a8[0] * b8[0] + a8[1] * b8[1] + a8[2] * b8[2] + a8[3] * b8[3]; -} -#define STRATA_DP4A(a, b, c) strata_dp4a((a), (b), (c)) -#else -#define STRATA_DP4A(a, b, c) __dp4a((a), (b), (c)) -#endif - -/// Yield the thread while a doorbell flag is being polled. The length of the pause is a backoff hint, not a -/// contract, and only pre-Volta CUDA has no `__nanosleep` at all. -__device__ __forceinline__ void strata_spin_pause() { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 700 - // sm_6x: the loop spins. Every call site is a single-thread doorbell wait, so nothing else is delayed. -#else - __nanosleep(100); -#endif -} diff --git a/include/strata/kernels/elementwise.hpp b/include/strata/kernels/elementwise.hpp deleted file mode 100644 index ae0973c..0000000 --- a/include/strata/kernels/elementwise.hpp +++ /dev/null @@ -1,128 +0,0 @@ -// include/strata/kernels/elementwise.hpp - the small ops a LAYER needs between its GEMVs, P2.S5. -// -// These are not interesting kernels and that is why they are in one file with one parity test: they are the -// glue in the per-layer graph, and glue that is written inline at each call site is glue with several -// slightly different float conventions. Three of them exist because a projection returns a DIFFERENT -// quantity from the one the next kernel wants: -// -// * `gdn_gate` turns (alpha, dt, ssm_a) into the recurrence's `gate`. `ref/gdn.py` L265: -// `gate = softplus(w_alpha . x + dt) * ssm_a`, with `softplus(x) = log1p(exp(x))` and the large-x branch -// `ggml_compute_softplus_f32` uses. `ssm_a` is NEGATIVE, which is what puts `exp(gate)` in (0,1). -// * `scale_inplace` applies the delta net's `1/sqrt(S)` to q. It is a separate op because -// `ref/gdn.py` says the two llama.cpp paths apply it in DIFFERENT places, so the caller has to own the -// choice rather than have it buried in a kernel. -// * `f32_to_f16_bulk` is what lets the f32 arithmetic of the mixer feed the fp16-activation GEMVs. -// `docs/activation-contract.md` is explicit that this is NOT the contract for a quantized weight - it is -// the bridge between two stages that both already exist, and the contract decision is a separate one. -// -// `silu_inplace` is here because `shared_expert` has its own copy inline and `gdn` needs one for the conv -// output; a third copy would be two too many. -#pragma once - -#include - -namespace strata::kernels { - -/// Decode one canonical embedding row already selected by the caller. Codes are -/// packed low bits first (2, 4 or 8 bits); scales/offsets are FP32 per group. -/// The optional offset defaults to +0. Multiplication and addition round separately, -/// matching the former CPU decoder. Launches asynchronously on the supplied stream. -/// The caller validates positive, divisible dimensions and row/plane bounds. -void embedding_gather(const uint8_t* codes, const float* scales, const float* offsets, - int64_t n, int code_bits, int code_bias, int group_elems, - float* out, void* stream); - -/// `y[t][h] = softplus(alpha[t][h] + dt[h]) * ssm_a[h]`, one thread per (t, h). In place is not possible: -/// `alpha` is read and `gate` is written, and they are different buffers by construction. -/// -/// `h_v` is the number of v heads (48) and `n_tokens` the leading dimension; the real call is (1, 48). -void gdn_gate(const float* alpha, const float* dt, const float* ssm_a, float* gate, int64_t n_tokens, - int64_t h_v, void* stream); - -/// `x[i] *= s`, in place. -void scale_inplace(float* x, int64_t n, float s, void* stream); -/// `dst[i] += src[i]`. **ADDED FOR R4's HIT/MISS SPLIT, WHERE THE TWO HALVES COME FROM DIFFERENT -/// ENGINES.** The CPU writes the misses into `parts` and the GPU writes the resident experts into a -/// buffer of their own, so that the GPU's work can run CONCURRENTLY with the CPU's instead of after it - -/// and the two are summed here, on the stream, immediately before `moe_combine` reads the result. -/// -/// The alternative - having the hit kernel write straight into `parts` - costs the whole overlap, because -/// the copy of the misses into `parts` cannot happen until the pool has produced them, and the kernel is -/// then ordered behind that copy. Measured: the drain fell 18.2 -> 10.2 ms and the token did not move. -void add_inplace(float* dst, const float* src, int64_t n, void* stream); - -/// `y[i] = f16(x[i])`, round-to-nearest-even, using the shared conversion in `f16_bits.hpp`. -void f32_to_f16_bulk(const float* x, uint16_t* y, int64_t n, void* stream); - -/// `y[i] = bf16(x[i])`, for the weights whose contract is a bf16 activation - the BF16 `hc_*`, `ssm_alpha`, -/// `ssm_beta`, `indexer.*` and `ple_value` tensors. -/// -/// A SEPARATE ENTRY POINT FROM `f32_to_f16_bulk` and not a flag on it, because the two conversions are not -/// variants of one idea: fp16 has 5 exponent bits and 10 mantissa bits, bf16 has 8 and 7. A caller that -/// picked the wrong one would get a plausible tensor at the wrong precision - 2^-11 against 2^-9, a factor of -/// four - and nothing downstream could tell which was intended. -void f32_to_bf16_bulk(const float* x, uint16_t* y, int64_t n, void* stream); - -/// `x[i] = x[i] / (1 + exp(-x[i]))`, in place. -void silu_inplace(float* x, int64_t n, void* stream); - -/// `build_norm`: `y[r][c] = x[r][c] / sqrt(MEAN_c(x[r]^2) + eps) * w[c]`, over the LAST axis. -/// -/// QSA's norm, used on `attn_q` (24x256), `attn_k` (2x256) and `indexer.q_proj` (4x128). `w` may be null. -/// -/// **IT IS NOT `gdn_l2_norm` AND THE DIFFERENCE IS A FACTOR OF sqrt(cols) = 16 HERE.** `gdn_l2_norm` divides by -/// `sqrt(SUM(x^2) + eps)` and applies no weight; this divides by `sqrt(MEAN(x^2) + eps)` and multiplies by `w`. -/// Two kernels whose names both say "norm" and whose bodies differ in one `/ cols` is exactly the pair that -/// gets swapped, and swapping them produces a well-scaled, plausible tensor - so they are separate entry -/// points and the parity test asserts the two readings are OBSERVABLE apart rather than trusting the names. -/// -/// There is NO `(1 + w)` folding: `ref/qsa.py::rms_norm` is `y * w`, and `build_norm` in the source is -/// `ggml_rms_norm` followed by a plain multiply. Some norms in this artifact DO fold (the GDN path records -/// which); this one does not, and the same `sqrt(cols)`-sized argument applies to getting it wrong. -void rms_norm_weighted(float* x, const float* w, int64_t rows, int64_t cols, float eps, void* stream); - -/// *seq = v in MAPPED PINNED memory - THE DOORBELL. A KERNEL and not cudaEventRecord, because round 199 -/// found that an event record inside a capture is SILENTLY DROPPED while a kernel is captured normally, and -/// round 209 measured the host seeing this one's result 0.050 ms into a 39.8 ms graph. -/// -/// It lives here because the caller that needs it - moe_layer - is a HOST translation unit, where -/// __global__ and <<<>>> do not exist. -/// *seq += 1 - AN INCREMENT, NOT A STORE OF A CALLER-SUPPLIED VALUE. A value passed in is evaluated on the -/// HOST at CAPTURE time, so a captured graph would ring the same number on every replay. Reading and -/// incrementing in memory is what makes the count advance under cudaGraphLaunch. -void doorbell_ring(uint32_t* d_seq, void* stream); - -/// Plan v0.3 P3 token graph: one thread spins until the host-written `*d_flag` equals the ring value `*d_seq` -/// (both mapped pinned memory), then fences so everything the host wrote before the flag is visible to the -/// nodes that follow. Captured once per layer between `pre[l]` and the parts copy; it is what lets one graph -/// hold the whole token (bench/micro/device_wait.cu: 5.2 us per handoff, no driver call). -void doorbell_wait(const uint32_t* d_flag, const uint32_t* d_seq, void* stream); - -/// Plan v0.3 P3 token graph: copy `n` floats from MAPPED pinned host memory (`src` is its device pointer) into -/// device memory with a kernel, so the handoff stays on the compute queue (a memcpy node is a copy-engine -/// operation, which WDDM submits separately and which measured 67 flushes per token). -void copy_from_mapped(float* dst, const float* src, int64_t n, void* stream); -/// `rows` rows of `width` floats from mapped memory, except the rows listed in hit_rows[0, *count) (device), -/// which are written +0.0 instead (a verify window's GPU-computed entries: the pool leaves zeros there). -/// multi-GPU: dst[rows[r] * width ..] = src[r * width ..] for r < n (float4; dst may be mapped host memory). -void scatter_rows_f32(const float* src, float* dst, const int32_t* rows, int64_t n, int64_t width, void* stream); -void copy_rows_from_mapped(float* dst, const float* src, int64_t rows, int64_t width, const int32_t* hit_rows, - const int32_t* count, void* stream); - -/// Plan v0.3 P3: the doorbell's payload and its ring in ONE kernel. Copies `x` (n floats), `ids` and `weights` -/// (k each) into the mapped host regions, fences, and increments the mapped sequence number - replacing three -/// device-to-host memcpy nodes (copy-engine operations in the middle of the layer chain) and the ring kernel. -void doorbell_publish(const float* x, const int32_t* ids, const float* weights, int64_t n, int64_t k, float* x_out, - int32_t* ids_out, float* weights_out, uint32_t* d_seq, void* stream); -/// #649 (HIP, STRATA_DOORBELL_STORE=1): the ring stored as `value` instead of incremented over PCIe. -void doorbell_publish_value(const float* x, const int32_t* ids, const float* weights, int64_t n, int64_t k, - float* x_out, int32_t* ids_out, float* weights_out, uint32_t* d_seq, uint32_t value, - void* stream); -void doorbell_publish_res(const float* x, const int32_t* ids, const int32_t* d_res, int n_expert, int64_t n, int64_t k, - float* x_out, int32_t* ids_out, uint32_t* d_seq, void* stream); - -/// Plan v0.3 P3: copy `n` int32 from mapped pinned host memory into device memory with a kernel (the QSA -/// per-token step and positions), instead of a host-to-device memcpy node in the middle of a layer. -void copy_i32_from_mapped(int32_t* dst, const int32_t* src, int64_t n, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/f16_bits.hpp b/include/strata/kernels/f16_bits.hpp deleted file mode 100644 index 396d690..0000000 --- a/include/strata/kernels/f16_bits.hpp +++ /dev/null @@ -1,104 +0,0 @@ -// include/strata/kernels/f16_bits.hpp - the fp16 conversions, written out, as bits. -// -// WHY THIS IS NOT `__float2half`. Round 193 found `__float2half` producing 0x2600 for a value whose correct -// fp16 encoding is 0x26DB, and 0x3C01 for a value that is exactly 1.0 - i.e. wrong bits, not a rounding -// difference. The cause was never isolated (it is either `__float2half` itself or `__half_as_ushort`), so -// `src/kernels/cuda/quantize_act.cu` replaced it with the version below, which then came out byte-exact over -// all 20,480 blocks of the fixture. `shared_expert.cu` carries the same function privately for the same -// reason. Three copies of a converter whose failure mode is silent wrong bits is two copies too many, so the -// copy lives here and the kernel and its TEST both include it - with the test checking it against vectors -// generated by numpy's float16 (an oracle that shares no code with this), which is what neither private copy -// had. -// -// The rounding is ROUND-TO-NEAREST-EVEN, which is what numpy's `.astype(np.float16)` does and what IEEE-754 -// specifies for the default mode. The three interesting regimes are all handled explicitly and all three are -// covered by the test's oracle vectors: -// -// * normal - exponent fits, mantissa is rounded from 13 surviving bits with a sticky remainder -// * subnormal - the implicit 1 is restored and the result is shifted right, so the rounding point MOVES -// * overflow - exp >= 31 saturates to inf (0x7C00) and keeps the sign; a NaN input stays a NaN -// -// `f32_from_f16` deliberately does NOT round: it is used to compare against a reference that holds the same -// bits, so it only has to be exact. -#pragma once - -#include -#include - -#if defined(__CUDACC__) || defined(__HIPCC__) -#define STRATA_HD __host__ __device__ -#else -#define STRATA_HD -#endif - -namespace strata::kernels { - -/// Round-to-nearest-even f32 -> fp16, returned as raw bits. -STRATA_HD inline uint16_t f16_from_f32(float f) { - uint32_t x; -#if defined(__HIP_DEVICE_COMPILE__) - __builtin_memcpy(&x, &f, 4); -#else - std::memcpy(&x, &f, 4); -#endif - const uint32_t sign = (x >> 16) & 0x8000u; - const uint32_t rawexp = (x >> 23) & 0xFFu; - int exp = (int) rawexp - 127 + 15; - uint32_t man = x & 0x7FFFFFu; - // TWO different things reach here and they must not be conflated: an f32 inf/NaN (raw exponent 255) stays - // an inf/NaN, and a FINITE value too large for fp16 (1e30) SATURATES TO INF. The version of this function - // in quantize_act.cu and shared_expert.cu tests `if (exp >= 31) return sign | 0x7C00 | (man ? 0x200 : 0)` - // and therefore returns a NaN for every overflowing finite value - which their own fixtures cannot see, - // because all of their values are O(1). Round 198's numpy oracle caught it here on the first run (1e30, - // 65536, 1e45: numpy says inf, the conflated test said NaN). - if (rawexp == 0xFFu) return (uint16_t) (sign | 0x7C00u | (man ? 0x200u : 0u)); // inf, or a quiet/NaN - if (exp >= 31) return (uint16_t) (sign | 0x7C00u); // finite overflow -> inf - if (exp <= 0) { - if (exp < -10) return (uint16_t) sign; // underflows to a signed zero - man |= 0x800000u; // restore the implicit 1 - const uint32_t sh = (uint32_t) (14 - exp); - uint32_t h = (man >> sh) & 0x3FFu; - const uint32_t rem = man & ((1u << sh) - 1u); - if (rem > (1u << (sh - 1)) || (rem == (1u << (sh - 1)) && (h & 1u))) ++h; - return (uint16_t) (sign | h); - } - uint16_t h = (uint16_t) (sign | ((uint32_t) exp << 10) | (man >> 13)); - const uint32_t rem = man & 0x1FFFu; - if (rem > 0x1000u || (rem == 0x1000u && (h & 1u))) ++h; // the carry may bump the exponent - return h; -} - -/// Exact fp16 bits -> f32. No rounding, no exceptions: every one of the 65,536 inputs maps to a value f32 -/// represents exactly, including the subnormals (which is why the `ex == 0` case cannot be skipped). -STRATA_HD inline float f32_from_f16(uint16_t h) { - const uint32_t sign = (uint32_t) (h & 0x8000u) << 16; - const uint32_t ex = (h >> 10) & 0x1Fu, man = h & 0x3FFu; - uint32_t out; - if (ex == 0) { - // Subnormal or zero. The value is `man * 2^-24`, so after `s` left shifts the leading 1 reaches bit - // 10 and the value is `(1 + frac) * 2^(-14-s)`: the f32 exponent field is 113 - s and `frac` is the low - // ten bits. Flushing these to zero - which the two private copies of this function in the tree do - - // maps 0x0001 to 0.0 instead of 2^-24, a 100% relative error on any KL-quant scale that lands here. - if (man == 0) { - out = sign; - } else { - uint32_t m = man; - int s = 0; - while ((m & 0x400u) == 0) { m <<= 1; ++s; } - out = sign | ((uint32_t) (113 - s) << 23) | ((m & 0x3FFu) << 13); - } - } else if (ex == 31) { - out = sign | 0x7F800000u | (man << 13); - } else { - out = sign | ((ex - 15 + 127) << 23) | (man << 13); - } - float f; -#if defined(__HIP_DEVICE_COMPILE__) - __builtin_memcpy(&f, &out, 4); -#else - std::memcpy(&f, &out, 4); -#endif - return f; -} - -} // namespace strata::kernels diff --git a/include/strata/kernels/fused_gdn.hpp b/include/strata/kernels/fused_gdn.hpp deleted file mode 100644 index dfa2c07..0000000 --- a/include/strata/kernels/fused_gdn.hpp +++ /dev/null @@ -1,40 +0,0 @@ -// include/strata/kernels/fused_gdn.hpp - plan v0.3 P3: the gated delta-net step and its output norm in ONE kernel. -// -// The native step (after llama.cpp's gated_delta_net.cu) gives each warp one (head, column) and strides its 32 -// lanes over the 128 ROWS of the state, which is stored `[row][head][col]`: every lane's load is 24.5 KB from its -// neighbour's, so each 32 B sector delivers 4 useful bytes - 47.6 us per layer for 6.3 MB of state traffic. Here a -// block owns one whole head, its 512 threads are (row group of 32, column), and a row's 128 columns are one -// contiguous 512 B load. With the head in one block, the per-head RMS norm, the norm weight and the sigmoid(z) -// gate of `gdn_out_norm` run in the same kernel. -// -// S <- g S + k (beta (v - g S^T k))^T (g = exp(gate[head]), per value head; q/k shared by h_v / h_k heads) -// o = (S^T q) / sqrt(128) -// y = rmsnorm(o) * gamma * act(z) (act = sigmoid for Flash-Next, SiLU for Qwen3.6: `GdnGate`, gdn.hpp) -#pragma once - -#include "strata/kernels/gdn.hpp" - -#include - -namespace strata::kernels { - -/// The 4-tap causal conv + SiLU over all `channels` (history is `[channel][3]`, updated), then the L2 norm of -/// each of the first `qk_heads` 128-channel heads (q then k), eps as the native `l2_norm` (x / sqrt(sum + eps)). -/// One block per 128-channel head; replaces conv_silu + two l2_norm launches. -void fused_gdn_conv_l2(float* history, const float* qkv, const float* conv_w, float* h, int channels, int qk_heads, - float eps, void* stream); - -/// alpha and beta, both `(h_v, n_embd)` BF16 against the FP32 activation, with their epilogues: -/// gate = softplus(alpha + dt) * ssm_a, beta = sigmoid(beta). One warp per row; replaces two MMVF launches and -/// two elementwise kernels. -void fused_gdn_ab(const float* x, const uint16_t* w_alpha, const uint16_t* w_beta, const float* dt, const float* ssm_a, - float* gate, float* beta, int n_embd, int h_v, void* stream); - -/// The step and the output norm in one kernel: state (S, h_v, S) in place, q/k (h_k, 128) L2-normalised and NOT -/// pre-scaled (the 1/sqrt(S) goes on the readout), v/z/y (h_v, 128), gate/beta (h_v), gamma (128). `act` is the -/// model's output gate (`GdnGate`); `h_v % h_k == 0`, any h_v (Flash-Next 48, Qwen3.6 32). -void fused_gdn_step_norm(float* state, const float* q, const float* k, const float* v, const float* gate, - const float* beta, const float* z, const float* gamma, float eps, GdnGate act, float* y, - int h_k, int h_v, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/fused_gr.hpp b/include/strata/kernels/fused_gr.hpp deleted file mode 100644 index b5f95fc..0000000 --- a/include/strata/kernels/fused_gr.hpp +++ /dev/null @@ -1,67 +0,0 @@ -// include/strata/kernels/fused_gr.hpp - plan v0.3 P3: the hyper-connection read in TWO kernels, with the -// previous half's write folded in. -// -// The native path spends six kernels per `gr_read` (norm, down MMVF, silu, up MMVF, gate+mean, inject MMVF) and -// one per `gr_write`, 96 + 96 times per token, and its up projection (10240 rows of 320) runs one 160-thread -// block per row: 20.6 us for 6.5 MB. Here: -// -// fused_gr_down : R' = R + bo_prev * 2 sigmoid(inj_prev / hc) (only when `apply`, computed on the fly) -// rs[c] = rsqrt(mean(R'[c]^2) + eps), xn = R' * w_norm * rs -// lo[k] = silu((w_down[k] . xn) / hc) k < hc_lr -// inject[c] = w_inject[c] . xn when w_inject is given -// fused_gr_up : R <- R' in place for this block's columns (when `apply`) -// mixed[d] = mean_c xn[c,d] * sigmoid(w_up[c*n_embd + d] . lo) -// -// FP32 activations and BF16 weights, like the native MMVF contract; the summation order differs from it (G-C -// judges the result). Geometry is the artifact's: n_embd 2560, hc 4, hc_lr 320. `inj_prev` and `inject_out` -// must be different buffers (every block reads the former while one block writes the latter). -#pragma once - -#include - -namespace strata::kernels { - -struct FusedGrArgs { - const float* R = nullptr; ///< (hc, n_embd), read by `down`; `up` updates it in place when apply - float* R_out = nullptr; ///< == R for the in-place update - bool apply = false; ///< fold the previous half's gr_write - const float* bo_prev = nullptr; ///< that half's block output, n_embd - const float* inj_prev = nullptr; ///< that half's injection, hc - const float* w_norm = nullptr; ///< (hc * n_embd) f32 - const uint16_t* w_down = nullptr; ///< bf16 [hc_lr][hc*n_embd] - const uint16_t* w_up = nullptr; ///< bf16 [hc*n_embd][hc_lr] - const uint16_t* w_inject = nullptr;///< bf16 [hc][hc*n_embd], or null (the final mixer) - float eps = 1e-6f; - float* lo = nullptr; ///< workspace, hc_lr floats - float* rs = nullptr; ///< workspace, hc floats - float* inject_out = nullptr; ///< hc floats (when w_inject) - float* mixed = nullptr; ///< n_embd -}; - -bool fused_gr_supported(int64_t n_embd, int64_t hc, int64_t hc_lr); -void fused_gr_read(const FusedGrArgs& a, void* stream); - -/// Plan v0.3 P6: the same read for up to 8 tokens that share the weights (a verify window): the weights are read -/// once for all of them. `a[t]` is token t's arguments (its own R, pending write, lo, rs, inject, mixed; the four -/// weight pointers and eps must be the same for every t); `xn_scratch` is n_tok * hc * n_embd floats. Every -/// token's outputs are bitwise `fused_gr_read(a[t])`. -constexpr int kFusedGrMaxT = 8; -void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, - unsigned long long* stamp_buf = nullptr, int stamp_i0 = 0); - -/// The bench only: the AMD latency-hidden kernels on (1) or off (0); -1 = STRATA_GR_FAST. -void fused_gr_set_fast(int on); -/// The multi read's variants (#315; not main's opt-in STRATA_GR_V3 read, which sums in another order), all computing -/// every output with the plain read's operations in its order, so bitwise the plain read's and the single-token -/// read's: plain (0.1.31's default: the norm one block per token, the down projection on 41 blocks), split (the norm -/// one block per token and stream, then the plain down projection) and staged (split's norm, and the down -/// projection's activations staged ahead by cp.async, two half-stream tiles in flight, bank-conflict-free). -/// `fused_gr_check` runs all of them and the single-token read on the current card with random weights and inputs -/// (1..8 tokens, with and without the pending write) and from then on uses there the newest one that agrees with the -/// plain read bit for bit; STRATA_HC_SPLIT=0 keeps the plain read, =1 stops at split. It runs once per card -/// (Verifier::init calls it) and prints which one runs. On a card it has not checked, `fused_gr_variant` is the -/// plain read unless STRATA_HC_SPLIT=1 or 2 names a variant. -void fused_gr_check(); -int fused_gr_variant(); - -} // namespace strata::kernels diff --git a/include/strata/kernels/gdn.hpp b/include/strata/kernels/gdn.hpp deleted file mode 100644 index bc2c0f5..0000000 --- a/include/strata/kernels/gdn.hpp +++ /dev/null @@ -1,110 +0,0 @@ -// include/strata/kernels/gdn.hpp - the gated delta-net (GDN) layer's non-projection parts, P2.S2. -// -// Transcribed from `ref/gdn.py`, which is itself transcribed from `build_layer_attn_linear` and -// `build_delta_net_autoregressive`. The projections (`wqkv`, `wqkv_gate`, `ssm_out`) are the existing -// `s_gemv`/`s2_gemv` kernels; what lives here is everything BETWEEN them. -// -// Geometry of the real artifact (48 layers are GDN, 12 are QSA): -// -// S = state_size = 128 head_k_dim == head_v_dim -// h_k = 16 k/q heads h_v = 48 v heads (idx[h] = h % h_k) -// C = 2*128*16 + 128*48 = 10240 channels d_conv = 4 -// -// STATE LAYOUT. This is the one place the kernels deliberately differ from the reference, and the reason is -// coalescing. `ref/gdn.py` carries the state as (S, S, H_v) = (i, j, h); here it is **(S, H_v, S)** = -// (i, h, j), so that for a fixed i a warp walking consecutive j reads CONTIGUOUS memory. The state is a -// runtime buffer, not a weight, so this costs nothing to choose - but it must be said, because the two -// layouts index the same three numbers and a mismatch is silent. -// -// WHAT MAKES THE RECURRENCE PARALLEL, and it is worth stating because it is not obvious: -// -// dec = exp(gate) (h_v,) -// st = state * dec -// sk[h,j] = sum_i st[i,j,h] * k[idx[h]][i] -// d[h,j] = (v[h,j] - sk[h,j]) * beta[h] -// st[i,j,h] += k[idx[h]][i] * d[h,j] -// o[h,j] = sum_i st[i,j,h] * q[idx[h]][i] -// -// Every line touches ONLY the (j, h) column. Nothing couples one column to another, so one thread can own a -// column for the whole step and no barrier is needed anywhere in the recurrence. (The decay must still be -// applied BEFORE the rank-1 update - `ref/gdn.py` PROPERTY 5 pins that, and the test re-pins it here.) -#pragma once - -#include - -namespace strata::kernels { - -/// Geometry of one GDN layer. Flash-Next: S = 128, h_k = 16, h_v = 48 (VPK 3); Qwen3.6-35B-A3B: S = 128, -/// h_k = 16, h_v = 32 (VPK 2). Every kernel here takes these at runtime; `h_v % h_k == 0` is the one rule. -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 -/// q, k (h_k, S) already L2-normalised, and q ALREADY SCALED by 1/sqrt(S) - the two llama.cpp paths -/// apply that scale in different places, so the caller owns it -/// v (h_v, S) -/// gate (h_v,) the PRE-exp value; `dec = exp(gate)` is formed here -/// beta (h_v,) -/// o (h_v, S) -/// -/// The head pairing is `h % h_k` (MODULO), not `h / (h_v/h_k)` (INTERLEAVE). `ref/gdn.py` PROPERTY 8 and 11 -/// pin this and the test re-pins it, because both conventions produce well-formed output. -void gdn_step(float* state, const float* q, const float* k, const float* v, const float* gate, - const float* beta, float* o, const GdnShapes& s, void* stream); - -/// `ggml_ssm_conv` with the carried state prepended. Updates `conv_state` in place. -/// -/// conv_state (d_conv-1, channels) the previous d_conv-1 input columns, OLDEST FIRST -/// x (channels,) the new column -/// kW (channels, d_conv) the weight in GGML-NATIVE layout: `kW[c*d_conv + i]` is tap i of -/// channel c. The manifest gives `ssm_conv1d.weight` ne = [4, 10240], -/// i.e. ne0 = d_conv is the FAST axis, which is this and NOT the -/// reference's row-major (d_conv, channels). -/// out (channels,) -/// -/// out[c] = sum_{i -#include - -namespace strata::kernels { - -/// Select the activation precision for subsequent gr_read launches (default: false/BF16). -/// Configure before creating/capturing a session, and do not mutate concurrently with gr_read. -/// A captured graph retains the kernel variants chosen at capture; changing this flag cannot alter it. -/// This changes activation precision only; the existing FP32 reduction trees remain unchanged. -void gr_set_fp32_activations(bool enabled); - -/// Select pinned single-token BF16/F32 MMVF projections for subsequent gr_read launches (default false). -/// This implies FP32 activations regardless of gr_set_fp32_activations. Configure before session capture; -/// a captured graph retains its selected kernels. Requires even hc*n_embd and hc_lr, as MMVF reads pairs. -/// This also selects pinned weighted F32 RMSNorm and nonlinear/combine arithmetic. -/// Layer reads use fused HC pre; the final mixer (null w_inject) retains its unfused graph order. -/// Subsequent gr_write calls select pinned sigmoid/scatter arithmetic under the same setting. -void gr_set_native_mmvf(bool enabled); - -/// Geometry of the hyper-connection. The real model: n_embd = 2560, hc = 4, hc_lr = 320. -struct GrShapes { - int64_t n_embd = 0; ///< width of one residual stream - int64_t hc = 0; ///< number of streams in the stack - int64_t hc_lr = 0; ///< rank of the down/up bottleneck -}; - -/// Scratch for `gr_read`. EXPLICIT and caller-owned, because P2.T10 requires ZERO token-path allocations: -/// a hidden `cudaMalloc` on first use would satisfy every test here and fail the memory test in P2.S10. -/// -/// **IT MUST BE DEVICE MEMORY.** `gr_workspace_init` takes a raw pointer and does no checking, so handing it -/// a host buffer produces device kernels writing to a truncated host address - an illegal access whose -/// reported fault address is the low 32 bits of a host pointer, which reads as a wild pointer rather than as -/// the mistake it is. That cost one round in `gr_parity`; -/// -/// xn hc*n_embd floats the unrounded activated streams (the gated mean needs the unrounded value) -/// xq hc*n_embd uint16 bf16(xn), used by the default activation contract -/// lq hc_lr uint16 bf16(lo), used by the default activation contract -/// gated hc*n_embd floats xn * sigmoid(gate), before the mean over streams -/// lo hc_lr floats SiLU bottleneck, used by the FP32 activation contract -/// -/// `cudaMalloc(gr_workspace_bytes(s))`, then `gr_workspace_init(s, ptr, ws)` to carve it. -struct GrWorkspace { - float* xn = nullptr; - uint16_t* xq = nullptr; - uint16_t* lq = nullptr; - float* gated = nullptr; - float* lo = nullptr; - /// Set by `gr_workspace_init`. `gr_read` CHECKS it, so an under-sized buffer is a loud failure at the - /// first call instead of silent corruption - which is what a mis-ordered region table used to produce. - size_t bytes = 0; -}; - -/// Carves `base` (which must be DEVICE memory, or null to size only) into `out` and returns the bytes needed. -/// 16-byte aligned between regions. -size_t gr_workspace_init(const GrShapes& s, void* base, GrWorkspace& out); -inline size_t gr_workspace_bytes(const GrShapes& s) { GrWorkspace w; return gr_workspace_init(s, nullptr, w); } - -/// `build_hc_mix`. ONE token: `R` is (hc, n_embd) with n_embd fastest, i.e. stream c starts at c*n_embd. -/// -/// w_norm (hc*n_embd) per-stream RMSNorm gamma, STORED AS (1 + w) by the converter -/// w_down (hc_lr, hc*n_embd) MANIFEST LAYOUT - row k is contiguous, `w_down[k*hc*n_embd + i]` -/// w_up (hc*n_embd, hc_lr) MANIFEST LAYOUT - row i is contiguous, `w_up[i*hc_lr + k]` -/// w_inject (hc, hc*n_embd) null for the FINAL mixer, which has no write-back to gate -/// -/// mixed (n_embd) = mean over streams of xn * sigmoid(bf16(lo) @ w_up.T) -/// inject (hc) = bf16(xn) @ w_inject.T, or untouched when w_inject is null -/// -/// `lo = silu((bf16(xn) @ w_down.T) / hc)` - the division by hc is INSIDE the silu, which is easy to read -/// past and changes the result materially. -/// With gr_set_fp32_activations(true), replace bf16(xn) and bf16(lo) by xn and lo respectively. -/// -/// **NO PERMUTATION: both matrices are taken exactly as the manifest stores them**, so the loader does nothing -/// to them. Both are coalesced because each projection assigns ONE WARP PER OUTPUT ROW and strides the -/// reduction axis across its 32 lanes: for a fixed output, consecutive lanes touch consecutive addresses in -/// either orientation. An earlier version assigned one THREAD per row, which is coalesced with itself and 32 -/// transactions away from its warp neighbours - see the history below. -/// -/// **HISTORY, because this kernel was the engine's worst and the reason is instructive.** The first version -/// was launched `<<<1, 256>>>` with `xn`/`xq` in shared memory, and at the real geometry it cost **2.67 ms per -/// call, 96 calls per token = 262 ms/token, about 3.8 tok/s, 134x off the 643 GB/s memory floor.** The cause -/// was isolated by elimination: NOT memory latency (four independent accumulator chains made it 17% SLOWER), -/// NOT the SM clock (`nvidia-smi` reported 2917 MHz and 99% utilisation throughout), and only partly -/// coalescing (transposing one of the two matrices gave 31% and transposing the other gave nothing). It was -/// ISSUE THROUGHPUT - ~8.4M iterations of 6-8 instructions issued by ONE of 48 SMs. -/// -/// This version splits the work the way the shapes want: `hc` blocks for the per-stream norm, one warp per -/// row for each of the two projections, and one block-tile for the mean. The transposes are gone because the -/// warp-per-row mapping makes them unnecessary. -void gr_read(const float* R, const float* w_norm, const uint16_t* w_down, const uint16_t* w_up, - const uint16_t* w_inject, float eps, const GrShapes& s, const GrWorkspace& ws, float* mixed, - float* inject, void* stream); - -/// `build_hc_combine`. `R_out[i] = R[i] + block_out[d] * w[c]` with `w[c] = 2*sigmoid(inject[c]/hc)`. -/// -/// The `2*sigmoid` is what CENTRES the gate on 1, so a zero injection is a plain residual add - the source -/// comment says so outright and `gr_write`'s test asserts it. Note the block output is added to EVERY stream -/// identically; only the weight is per-stream. -void gr_write(const float* R, const float* block_out, const float* inject, const GrShapes& s, float* R_out, - void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/iq_kernels.hpp b/include/strata/kernels/iq_kernels.hpp deleted file mode 100644 index 97f7727..0000000 --- a/include/strata/kernels/iq_kernels.hpp +++ /dev/null @@ -1,81 +0,0 @@ -// include/strata/kernels/iq_kernels.hpp - the i-quant formats (IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S, -// IQ4_NL) and Q2_0 on the GPU for the IQ2_XS / IQ3_XXS model files, and Q4_K / Q5_K / Q5_1 / Q8_0 for Unsloth's -// UD-Q4_K_XL (gate/up Q4_K or Q5_K, down Q5_1 or Q8_0, a Q8_0 embedding). Qwen3.6-35B-A3B's files add Q6_K and -// the 256-value down types (IQ3_XXS, Q5_K, Q6_K down at n_ff 512; docs/qwen36-port/step3-experts.md). -// -// 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 -// means in llama.cpp. Activations are q8_1 (32 values, fp16 scale and fp16 sum), the llama.cpp CUDA contract. -#pragma once - -#include -#include - -namespace strata::kernels { - -/// ggml type ids handled here. -bool iq_supported(int ggml_type) noexcept; -/// The token-embedding types iq_embed_rows and iq_dequant_f32 read: the i-quants above and BF16 (30). -bool embed_type_supported(int ggml_type) noexcept; -/// Bytes of one row of `n` values of `ggml_type` (n a multiple of the type's block). -size_t iq_row_bytes(int ggml_type, int64_t n) noexcept; - -/// q8_1 blocks for `n_rows` rows of `n_cols` floats (n_cols a multiple of 32): y is n_rows * n_cols/32 blocks. -void quantize_q8_1_rows(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream); - -/// y[c][r] = W[r] . x[c] for `ncols` columns of q8_1 activations (x stride n_in/32 blocks per column). -void iq_mmvq(int ggml_type, const void* w, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream); - -/// Dequantize `n` contiguous values (n a multiple of 256) to fp16 / fp32. -void iq_dequant_f16(int ggml_type, const void* src, int64_t n, uint16_t* dst, void* stream); -void iq_dequant_f32(int ggml_type, const void* src, int64_t n, float* dst, void* stream); -/// Rows `tokens[0..n_tok)` (device ids) of a GGUF embedding table (`row_bytes` per row; the table may be mapped -/// host memory) dequantized to fp32, `n_embd` per row (a multiple of 256). -void iq_embed_rows(int ggml_type, const void* table, size_t row_bytes, const int32_t* tokens, int64_t n_tok, - int64_t n_embd, float* out, void* stream); -/// One expert's gate and up matrices (n_ff rows of n_embd each) into the interleaved fp16 layout the prompt path -/// uses: row 2r = gate row r, row 2r+1 = up row r. -void iq_dequant_gu_f16(int ggml_type, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst, - void* stream); - -/// The layout of one native expert blob: [gate rows | up rows | down rows], raw GGUF blocks. -struct NativeExpertLayout { - int gu_type = -1, d_type = -1; - int64_t n_embd = 0, n_ff = 0; - size_t gu_row = 0, d_row = 0; // bytes per row - size_t up_off = 0, down_off = 0; // byte offsets inside the blob - size_t bytes = 0; // the whole blob -}; -NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff); -/// Whether `native_expert_grouped` has kernels for this gate/up and down type pair at these dimensions, and the -/// prompt path's dequantizer takes both (checked for every layer at startup, before anything is allocated). -bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept; - -/// Bytes of scratch `native_expert_grouped` needs for `cap_entries` entries. -size_t native_expert_scratch_bytes(int64_t cap_entries, int64_t n_ff); - -/// Grouped experts in the native format: group g's blob at device address grp_ptr[g]; its entries -/// [grp_start[g], grp_start[g+1]) read token ent_tok[e]'s q8_1 activation (n_embd/32 blocks per token in x_q8_1) -/// and write row ent_dst[e] of `out` (n_embd floats). Counts are read on the device. -/// `grid_groups` (1 .. cap_groups; 0 = cap_groups) groups run side by side, a block row each striding over the rest: -/// a call that usually has few groups or none (the verify window's PCIe share) launches less for the ones it does -/// not have. The results do not depend on it. -void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long* grp_ptr, const int32_t* grp_start, - const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups, - int64_t cap_entries, const void* x_q8_1, void* scratch, float* out, void* stream, - int64_t grid_groups = 0); -/// true: `native_expert_grouped`'s launches before the group stride (STRATA_GROUPED_V1=1 at startup) - a block row -/// per possible group, SwiGLU and the q8_1 quantization as two kernels over all cap_entries. Bitwise the same results -/// (native_grouped_parity checks it); kept for A/B timing. Set before graph capture; captured graphs keep theirs. -void native_grouped_set_v1(bool v1); - -/// The bench only: the AMD kernel layout (STRATA_EXP_MODE values; -1 = the environment's) and the phase -/// (0 all, 1 gate/up + SwiGLU + quantize, 2 down). -void native_expert_set_mode(int mode, int phase); -/// `iq_mmvq` and `native_expert_grouped` decode each weight part once and apply it to every column / entry; -/// true selects the older kernels that decode it again per column (STRATA_OLD_IQ_MMVQ=1 at startup). Both give -/// bitwise the same results. Set before graph capture; captured graphs keep the kernels they captured. -void iq_set_old_kernels(bool old); -bool iq_old_kernels(); - -} // namespace strata::kernels diff --git a/include/strata/kernels/kv_q4.hpp b/include/strata/kernels/kv_q4.hpp deleted file mode 100644 index 930b628..0000000 --- a/include/strata/kernels/kv_q4.hpp +++ /dev/null @@ -1,61 +0,0 @@ -// include/strata/kernels/kv_q4.hpp - Q4_0 KV storage with Walsh-Hadamard rotation for the QSA layers (`--kv q4_0`). -// -// From PR #21 (code-martin). K and V are rotated by the orthonormal 256-point Hadamard matrix H before they are -// quantized to ggml's q4_0 (32 values per block: an fp16 scale + 16 bytes of 4-bit codes, 144 B per head per cell, -// 576 B per cell for K and V of both heads, vs 1,056 B in INT8). The rotation spreads a head's outlier channels -// over all 256 dimensions, which is what makes 4 bits usable. The query is rotated the same way, so -// = and the scores are unchanged, and the attention output (a mix of rotated values) is rotated -// back with H (self-inverse). What is lossy is the 4-bit rounding itself: measured, not assumed, in -// bench/results/2026-09-27-kv-q4. -// -// With KV streaming (--kv-resident) the codes live in the host copy and the resident slots like INT8's (KvHostPools -// k_q4/v_q4, the same block granule), so both options combine. -#pragma once - -#include "strata/kernels/qsa.hpp" - -#include - -namespace strata::kernels { - -inline constexpr int QK4_0 = 32; - -#pragma pack(push, 1) -struct block_q4_0 { - uint16_t d; // scale (fp16 bits) - uint8_t qs[QK4_0 / 2]; // 32 4-bit codes: element j in the low nibble of qs[j], j + 16 in the high one -}; -#pragma pack(pop) - -static_assert(sizeof(block_q4_0) == 18, "block_q4_0 must be 18 bytes"); - -/// Bytes per cell and KV head: 8 blocks of 32 for head_dim 256 -> 144. -inline uint64_t kv_q4_bytes_per_head(int head_dim) { return (uint64_t) (head_dim / QK4_0) * sizeof(block_q4_0); } - -/// Bytes per cell (one token, one layer): K and V of every KV head. -inline uint64_t kv_q4_bytes_per_cell(const QsaShapes& s) { - return (uint64_t) s.n_head_kv * kv_q4_bytes_per_head((int) s.head_dim) * 2; -} - -/// Orthonormal Fast Walsh-Hadamard Transform of rows of 256 floats (scale 1/16): its own inverse. -void fwht256_cuda(const float* src, float* dst, int64_t n_rows, void* stream); -inline void fwht256_inplace_cuda(float* data, int64_t n_rows, void* stream) { fwht256_cuda(data, data, n_rows, stream); } - -/// Append the (already rotated) cell at step[kStepPos]. With a host copy (KV streaming) it is written there too, -/// and to VRAM only if its block is resident. -void kv_append_q4_step(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, const int32_t* step, - const float* kcur, const float* vcur, const QsaShapes& s, void* stream, - const KvHostPools* host = nullptr); - -/// The prompt path: T consecutive (rotated) cells from pos0, K/V [T, n_head_kv, 256]; also into `stage` (identity -/// layout, the one-layer staging pool of a streamed session) when given. -void kv_append_q4(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, int64_t pos0, int64_t T, const float* K, - const float* V, const QsaShapes& s, void* stream, const KvHostPools* host = nullptr, - const KvHostPools* stage = nullptr); - -/// Gather step[kStepWidth] cells named by `ids` into FP16 scratch [id][kv_head][head_dim] (still rotated). -void kv_gather_q4_step(const uint8_t* k_q4, const uint8_t* v_q4, const int32_t* page_table, const int32_t* ids, - const int32_t* step, int64_t max_ids, const QsaShapes& s, uint16_t* k_scratch, - uint16_t* v_scratch, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/kv_q8.hpp b/include/strata/kernels/kv_q8.hpp deleted file mode 100644 index a535cc3..0000000 --- a/include/strata/kernels/kv_q8.hpp +++ /dev/null @@ -1,41 +0,0 @@ -// include/strata/kernels/kv_q8.hpp - plan v0.3 P7: 8-bit KV storage for the QSA layers. -// -// The FP16 KV pools cost 2 x 12,288 bytes per token over the 12 QSA layers; with the FP32 pooled indexer keys the -// engine allocates 29 KB per token, 7.65 GB at 262K (bench/results/2026-09-23-p7-int-audit), which cannot fit -// 12 GB. This stores K and V as int8 codes with one FP16 scale per 64 values (per cell, per KV head): -// scale = fp16(max|x| / 127), code = clamp(rint(x / scale), -127, 127), x' = fp16(code * scale) -// Per layer and token: 2 KV heads x 256 values x (K, V) = 1,024 values -> 1,024 B of codes + 32 B of scales, -// instead of 2,048 B in FP16. Over the 12 QSA layers: 12,672 B/token instead of 24,576 (3.3 GB at 262K, not 6.4). -// -// Only STORAGE changes: `kv_gather_q8_step` dequantizes the selected cells into the same FP16 scratch the -// attention kernels already read, so `qsa_attend` and the native attention adapter are untouched. Layout mirrors -// the FP16 pools: codes `[page][kv_head][page_size][head_dim]`, scales `[page][kv_head][page_size][head_dim/64]`. -#pragma once - -#include "strata/kernels/kv_stream.hpp" -#include "strata/kernels/qsa.hpp" - -#include - -namespace strata::kernels { - -inline constexpr int KV_Q8_GROUP = 64; - -/// Bytes per cell (one token, one layer): K and V codes plus their scales. -inline uint64_t kv_q8_bytes_per_cell(const QsaShapes& s) { - return (uint64_t) s.n_head_kv * s.head_dim * 2 + (uint64_t) s.n_head_kv * (s.head_dim / KV_Q8_GROUP) * 2 * 2; -} - -/// Append the cell at step[kStepPos] (graph-capturable: position and page come from device memory). With a host -/// copy (KV streaming, `kv_stream.hpp`) the cell is written there too, and to VRAM only if its block is resident. -void kv_append_q8_step(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, const int32_t* page_table, - const int32_t* step, const float* kcur, const float* vcur, const QsaShapes& s, void* stream, - const KvHostPools* host = nullptr); - -/// Gather step[kStepWidth] cells named by `ids` into FP16 scratch `[id][kv_head][head_dim]`; the grid is sized by -/// `max_ids` (capacity), the kernel reads the real count from `step`. -void kv_gather_q8_step(const int8_t* k_q, const int8_t* v_q, const uint16_t* k_scale, const uint16_t* v_scale, - const int32_t* page_table, const int32_t* ids, const int32_t* step, int64_t max_ids, - const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/kv_stream.hpp b/include/strata/kernels/kv_stream.hpp deleted file mode 100644 index 514474b..0000000 --- a/include/strata/kernels/kv_stream.hpp +++ /dev/null @@ -1,104 +0,0 @@ -// include/strata/kernels/kv_stream.hpp - KV streaming for the QSA layers (docs/kv-streaming-design.md). -// -// A streamed QSA layer keeps its AUTHORITATIVE K/V in pinned, device-mapped host memory, laid out exactly as a -// fully resident pool with the identity page table would be. VRAM holds a pool of `n_slots` pages (one page = -// `page_size` = 4 cells = one indexer block, all KV heads, K and V: 4,224 B in int8), and the page table becomes a -// RESIDENCY MAP: `page_table[block]` is the slot holding that block, or -1. -// -// Every reader (`qsa_decode_attn_*`, `kv_gather_*`) is unchanged: it goes through the page table as before. What -// changes is that after the selection and before the attention, `kv_stream_resolve` makes every block the -// selection names resident - on device, inside the captured graphs: -// 1. one block of 1,024 threads walks the selected ids: a resident block gets this call's epoch and its clock -// reference bit, a missing block is claimed once (page_table -1 -> -2) into a miss list; -// 2. the same block picks one victim slot per miss with a CLOCK sweep (second chance) that never takes a slot -// this call uses, re-points the page table (old block -> -1, new block -> slot); -// 3. a copy kernel reads the missed blocks from the host copy (zero-copy, over PCIe) into their slots. -// Writers (`kv_append_*`) write the host copy always, and the slot only if the block is resident, so the slots -// never go stale and nothing needs invalidating - not after a rejected draft, not on a conversation-cache resume. -// -// A RING (the MTP drafter, which only ever reads its last `window` cells) uses the same host copy with a static -// table `block -> block % n_slots` and no resolve: the ring is refilled from the host copy on a resume. -#pragma once - -#include "strata/kernels/qsa.hpp" -#include "strata/kernels/qsa_decode_attn.hpp" - -#include - -namespace strata::kernels { - -/// The host copy of one layer's K/V: device-mapped pointers (UVA) into pinned memory, identity layout -/// `[block][kv_head][page_size][head_dim]`. All null when the layer is fully resident. -struct KvHostPools { - uint16_t* k_pool = nullptr; ///< fp16 mode - uint16_t* v_pool = nullptr; - int8_t* k_q = nullptr; ///< int8 mode: codes - int8_t* v_q = nullptr; - uint16_t* k_scale = nullptr; ///< int8 mode: fp16 scale per 64 values - uint16_t* v_scale = nullptr; - uint8_t* k_q4 = nullptr; ///< q4_0 mode (kv_q4.hpp): block_q4_0 codes, 144 B per cell and head - uint8_t* v_q4 = nullptr; - bool present() const { return k_pool != nullptr || k_q != nullptr || k_q4 != nullptr; } -}; - -/// The KV storage format, for the functions below that move whole blocks (`fmt`): fp16, int8 (+ scales), q4_0. -/// (A bool `int8` argument still reads as kKvF16 / kKvInt8.) -enum KvFormat : int { kKvF16 = 0, kKvInt8 = 1, kKvQ4 = 2 }; - -/// The residency map of a streamed layer, all device memory at fixed addresses (the graphs bake them in). -struct KvStreamMap { - int32_t* page_table = nullptr; ///< (n_blocks,) block -> slot, or -1 - int32_t* slot_block = nullptr; ///< (n_slots,) slot -> block, or -1 - int32_t* slot_stamp = nullptr; ///< (n_slots,) the resolve epoch that last used the slot - int32_t* slot_ref = nullptr; ///< (n_slots,) clock reference bit - int32_t* ctl = nullptr; ///< kKvCtlInts: epoch, hand, misses of the last call, overflow, u64 counters - int32_t* miss_block = nullptr; ///< (n_slots,) - int32_t* miss_slot = nullptr; ///< (n_slots,) - int64_t n_blocks = 0; - int64_t n_slots = 0; -}; - -inline constexpr int kKvCtlInts = 16; ///< [0] epoch [1] hand [2] misses [3] overflow; u64 at [4] misses, [6] lookups, [8] calls -/// Bytes of the map's arrays besides the page table (which the state already has): 5 per-slot ints + ctl. -inline uint64_t kv_stream_map_bytes(int64_t n_slots) { return (uint64_t) n_slots * 4 * 5 + kKvCtlInts * 4; } - -/// Every block evicted: page table all -1, slots free, counters zero. -void kv_stream_reset(const KvStreamMap& m, void* stream); - -/// Make every block named by the selections of `n_q` queries resident (ids [n_q][cap], width from -/// steps[q * kStepCount + kStepWidth]). Capturable. `n_slots` must hold the distinct blocks of one call -/// (n_q x (cap / page_size + 2)); a call that cannot sets ctl[3] (see `kv_stream_counters`). -void kv_stream_resolve(const KvStreamMap& m, const QsaAttnPools& slots, const KvHostPools& host, int fmt, - const int32_t* ids, const int32_t* steps, int64_t n_q, int64_t cap, const QsaShapes& s, - void* stream); - -/// The static ring table `block -> block % n_slots`. -void kv_ring_table(int32_t* page_table, int64_t n_blocks, int64_t n_slots, void* stream); - -/// Copy blocks [b0, b1) of the host copy into the pool pages `page_table` names (host-side table `phys(b)` -/// computed as `b % n_slots`: the ring restore). Not capturable. -void kv_ring_restore(const QsaAttnPools& slots, const KvHostPools& host, int fmt, int64_t b0, int64_t b1, - int64_t n_slots, const QsaShapes& s, void* stream); - -/// Copy the first `n_blocks` blocks of the host copy into a fully resident (identity-layout) pool: the prompt -/// path's staging of one layer. Not capturable (DMA). -void kv_stage_from_host(const QsaAttnPools& stage, const KvHostPools& host, int fmt, int64_t n_blocks, - const QsaShapes& s, void* stream); - -/// #579 #613 (HIP A/B, STRATA_KV_HOST_DMA=1): the reverse of kv_stage_from_host for blocks [b0, b1) - the staging -/// pool's blocks into the host copy, by DMA, so the prompt path's append need not write host memory from a kernel. -/// Not capturable. -void kv_unstage_to_host(const QsaAttnPools& stage, const KvHostPools& host, int fmt, int64_t b0, int64_t b1, - const QsaShapes& s, void* stream); - -struct KvStreamCounters { - uint64_t misses = 0, lookups = 0, calls = 0; - bool overflow = false; -}; -/// Synchronous read of the counters (debug and the end-of-request summary). -KvStreamCounters kv_stream_counters(const KvStreamMap& m); - -/// Bytes of one block (page) of K and V together. -uint64_t kv_block_bytes(const QsaShapes& s, int fmt); - -} // namespace strata::kernels diff --git a/include/strata/kernels/mrope.hpp b/include/strata/kernels/mrope.hpp deleted file mode 100644 index 18dbb68..0000000 --- a/include/strata/kernels/mrope.hpp +++ /dev/null @@ -1,64 +0,0 @@ -// strata/kernels/mrope.hpp - multimodal rotary positions (the vision path). -// -// qwen4exp rotates with interleaved M-RoPE (llama.cpp LLAMA_ROPE_TYPE_IMROPE, rope.dimension_sections 11/11/10/0): -// each of the 32 rotated pairs takes its position from one of three streams, time t, height h and width w. Text -// has t = h = w, which is why every rope kernel here takes one position per row. An image does not: its tokens -// share t and differ in h and w (mtmd: t = p, h = p + y, w = p + x), and the text after it continues at -// p + max(nx, ny), not at its cell index. -// -// The table: nullptr (the default) keeps every kernel exactly as before - the position a caller passes is the -// rotary position. Set, it is a DEVICE int32 [cells][3] (t, h, w) and the position a caller passes is read as a -// CELL index; pair i rotates by tab[cell * 3 + mrope_sector(i)]. Every caller in the engine passes cell indices -// (pos_base is 0 everywhere), so the table covers the prompt path, the verify window and the MTP drafter at once. -// The pointer must be set before any CUDA graph is captured (kernels take it as an argument); the contents may -// change between requests. -#pragma once - -#include -#if defined(__HIPCC__) && defined(STRATA_HIP_GFX906) // PR #638: the gfx906 compat build only -#include -#endif - -#include "strata/kernels/rope_scaling.hpp" - -namespace strata::kernels { - -/// The table of the CURRENT device (a layer split sets one per device; null = the identity). -void mrope_table_set(const int32_t* device_table); -const int32_t* mrope_table(); - -/// #280, opt-in (STRATA_ROPE_TABLE=1): the rotation angles, 32 pairs of a 64-wide rotary slice, from the session's -/// float64 table (build_rope_table, [max_pos][32] cos and sin in VRAM, the rope scaling inside) of the CURRENT -/// device. With it the rope kernels rotate by the table's exact angles; without it they compute pos * powf(...) with cosf/sinf, which under -/// --use_fast_math is 0.0014 rad off at 32K and ~0.02 at 262K, and the prompt path (precise libm) and decode -/// (fast-math) disagree with each other. -struct RopeTab { - const float* cos = nullptr; ///< null: no table, the kernels compute the angle as they always did - const float* sin = nullptr; - int max_pos = 0; -}; -/// Registers the table the session just built with `scaling` (the latest one of the device wins). -void rope_table_set(const float* cos_tab, const float* sin_tab, int max_pos, const RopeScaling& scaling); -/// Forgets the table `cos_tab` (on every device) - before the memory that holds it is freed (session_release). -void rope_table_release(const float* cos_tab); -/// The registered table when STRATA_ROPE_TABLE=1 and it was built with `scaling`; otherwise none (the default: the -/// kernels compute the angle exactly as before). -RopeTab rope_table_for(const RopeScaling& scaling); - -#if defined(__CUDACC__) || defined(__HIPCC__) -/// ggml rope_multi, is_imrope, sections {11, 11, 10, 0}: sector = pair % 32; sector % 3 == 1 -> h (sector < 33), -/// == 2 -> w (sector < 30), == 0 -> t (sector < 33). For pairs 0..31 all three bounds hold, so it is pair % 3. -__device__ __forceinline__ int mrope_pos(const int32_t* tab, int pos, int pair) { - return tab ? __ldg(tab + (size_t) pos * 3 + pair % 3) : pos; -} -/// cos and sin of rotary position p, pair `pair` (0..31) from the table (scaling and magnitude included); false -/// when there is no table or p lies past it - then the caller computes the angle as it always did -__device__ __forceinline__ bool rope_tab_cs(const RopeTab& t, int p, int pair, float& c, float& s) { - if (t.cos == nullptr || p < 0 || p >= t.max_pos) return false; - c = __ldg(t.cos + (size_t) p * 32 + pair); - s = __ldg(t.sin + (size_t) p * 32 + pair); - return true; -} -#endif - -} // namespace strata::kernels diff --git a/include/strata/kernels/native_flash_attn.hpp b/include/strata/kernels/native_flash_attn.hpp deleted file mode 100644 index b517156..0000000 --- a/include/strata/kernels/native_flash_attn.hpp +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once -#include "strata/kernels/qsa.hpp" - -namespace strata::kernels { - -enum NativeFlashAttnStatus : int32_t { - kNativeFlashAttnSuccess = 0, - kNativeFlashAttnUnsupportedStep = 1, -}; - -// Explicitly selected short-context adapter for pinned CUDA F16/F16 vector -// FlashAttention. Geometry is exactly Q24x256, KV2x256, one query/sequence, -// scale=1/16, no ALiBi/softcap/sink. No allocation, synchronization, or KV rewrite. -// q/output: contiguous [24,256] F32. k/v: existing gathered [capacity,2,256] -// F16 buffers, with only step[kStepWidth] initialized rows required. Optional -// mask: 256 F16 additive logits, broadcast over heads; at least one valid key -// must be unmasked. Finite live q/k/v and finite or -inf live mask entries are -// preconditions; unused k/v/mask padding may contain arbitrary bytes. -// Padding is synthesized as zero K/V and -inf mask without reading it. -// -// capacity >=256; max_context in [1,256] is the HOST session limit. The device -// step must satisfy pos+1==n_kv==width in [1,max_context] and n_bid==n_kv/4. -// An invalid step writes status=UnsupportedStep and NaN output, without reading -// q/k/v/mask. status is one caller-owned device int32, overwritten on every call; -// integration MUST inspect it at its normal completion boundary. Host context -// limits must prevent unsupported steps before decoding. This is not a 20K path. -// -// All buffers (including optional mask and status) must have disjoint spans, -// with four-byte alignment for F32/step/status and two-byte alignment for F16. -// A nonnull explicit stream is mandatory. All pointers remain live for replay. -void native_flash_attn_short_step(const float* q, const uint16_t* k, const uint16_t* v, - const int32_t* step, int64_t capacity, int max_context, - const QsaShapes& shapes, float* output, int32_t* status, - const uint16_t* mask, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/native_gdn.hpp b/include/strata/kernels/native_gdn.hpp deleted file mode 100644 index feebefe..0000000 --- a/include/strata/kernels/native_gdn.hpp +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once -#include "strata/kernels/gdn.hpp" - -namespace strata::kernels { - -// Configure before creating/capturing a session. Existing captures retain their -// selected kernel, so changing the flag does not change an existing graph. -void native_gdn_set_enabled(bool enabled); -bool native_gdn_enabled(); - -// Pinned CUDA gated_delta_net recurrence for one token, S=128 and h_v % h_k=0. -// q/k are normalized F32 inputs; q MUST NOT be pre-scaled by 1/sqrt(S). -// Scaling is applied to the completed readout, as in the pinned fused operator. -// State retains Strata's layout: state[(i*h_v+h)*S+j]. The caller owns it and -// output; both must be disjoint from each other and from every read-only input. -// All spans must be aligned to four bytes. A nonnull ordered stream is required. -// No allocation, wait, or change to normalization/gate preprocessing occurs. -void native_gdn_step(float* state, const float* q, const float* k, const float* v, - const float* gate, const float* beta, float* output, - const GdnShapes& shapes, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/native_gdn_preprocess.hpp b/include/strata/kernels/native_gdn_preprocess.hpp deleted file mode 100644 index f04cb30..0000000 --- a/include/strata/kernels/native_gdn_preprocess.hpp +++ /dev/null @@ -1,40 +0,0 @@ -#pragma once -#include "strata/kernels/gdn.hpp" - -#include - -namespace strata::kernels { - -// Optional pinned CUDA GDN preprocessing. The layer selects these functions with -// native_gdn_enabled(); direct callers explicitly select them by calling them. -// Require a nonnull ordered stream, finite inputs, and four-byte aligned spans. -// No function allocates or synchronizes. All pointers are caller-owned. - -// Four-tap convolution, then FP32 fast-math SiLU. History is [channels,3], oldest -// first; weights are [channels,4]. Both outputs are required, mutually disjoint, -// and disjoint from input/weights/history. History must not alias other spans. -void native_gdn_conv_silu(float* history, const float* input, const float* weights, - float* raw_output, float* silu_output, int64_t channels, - int64_t d_conv, void* stream); - -// In-place [rows,128]: scale(rms_norm(x,epsilon/128),1/sqrt(128)). This includes -// the L2 normalization scale, but NOT the recurrence's readout scale. -// Epsilon is finite/nonnegative; epsilon=0 additionally requires nonzero rows. -void native_gdn_l2_norm(float* input, int64_t rows, int64_t cols, float epsilon, void* stream); - -// In-place sigmoid over per-head beta; one token. -void native_gdn_beta_gate(float* beta, int64_t heads, void* stream); - -// One token: gate[h] = softplus(alpha[h]+dt[h])*ssm_a[h], using the pinned CUDA -// log(1+exp(x)) expression and threshold 20. Output is disjoint from inputs. -void native_gdn_gate(const float* alpha, const float* dt, const float* ssm_a, - float* gate, int64_t heads, void* stream); - -// [heads,128]: rms_norm(output,epsilon)*gamma*act(z), act sigmoid (qwen4exp) or -// SiLU (qwen35moe) per `GdnGate`. Gamma contains only 128 floats and broadcasts -// across heads. Destination is disjoint from inputs. -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); - -} // namespace strata::kernels diff --git a/include/strata/kernels/native_gr_norm.hpp b/include/strata/kernels/native_gr_norm.hpp deleted file mode 100644 index b8bb4ed..0000000 --- a/include/strata/kernels/native_gr_norm.hpp +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -namespace strata::kernels { - -// Pinned llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d CUDA weighted F32 -// RMSNorm for contiguous [n_cols, n_rows] data and equally shaped F32 gamma. -// Every row has independent norm statistics. Output is (scale * input) * gamma. -// Uses 256 threads below n_cols=1024, otherwise 1024, with the pinned XOR tree. -// Compile the implementation with --use_fast_math; no FP64, allocation, or wait. -// All buffers are caller-owned, nonoverlapping, and at least four-byte aligned. -// Require positive dimensions and finite nonnegative epsilon. Inputs/gamma and -// intermediate sums must be finite; epsilon=0 additionally requires nonzero rows. -// Enqueues on the supplied CUDA stream. A null handle explicitly selects CUDA's -// default stream, preserving gr_read's existing API; this function never syncs. -void native_gr_rms_norm_weighted(const float* input, const float* gamma, float* output, - int n_cols, int n_rows, float epsilon, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/native_gr_postops.hpp b/include/strata/kernels/native_gr_postops.hpp deleted file mode 100644 index 790b883..0000000 --- a/include/strata/kernels/native_gr_postops.hpp +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -namespace strata::kernels { - -// Pinned llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d contiguous F32 -// single-token GR post-operations. Explicit stream, no allocation or wait; null -// selects the default stream. Positive dimensions with n*hc <= INT_MAX, finite -// values/intermediates, and four-byte alignment are required. -// Buffers must not overlap except the explicitly in-place arguments below. -// Implementation compiles separately with --use_fast_math. - -// In-place pinned SCALE(1/hc), then SiLU, applied to the raw down projection. -void native_gr_down_silu(float* lo, int hc_lr, int hc, void* stream); - -// xn and raw gate contain [n_embd,hc]. gate is overwritten with xn*sigmoid(gate). -// Layer path: pinned DSV4_HC_PRE_GATED ordered FMA accumulation, then scale. -// Head path (fused_layer=false): individually rounded products, ordered adds -// starting from stream zero, then SCALE. This retains the oracle's il=-1 graph. -void native_gr_pre_gated(const float* xn, float* gate, float* mixed, - int n_embd, int hc, bool fused_layer, void* stream); - -// inject[hc] -> SCALE(1/hc), sigmoid, SCALE(2), identity DSV4_HC_POST. -// residual/output contain [n_embd,hc], block_out has n_embd elements. -// output may equal residual exactly; all other overlaps are invalid. -void native_gr_post(const float* residual, const float* block_out, const float* inject, - float* output, int n_embd, int hc, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/native_mmvq.hpp b/include/strata/kernels/native_mmvq.hpp deleted file mode 100644 index a1554e5..0000000 --- a/include/strata/kernels/native_mmvq.hpp +++ /dev/null @@ -1,115 +0,0 @@ -#pragma once - -#include - -namespace strata::kernels { - -// Native GGUF Q2_0, Q4_0, Q5_0, Q8_0, Q3_K, Q4_K, Q5_K, Q6_K, IQ4_NL -// and IQ4_XS / CUDA Q8_1 adapters, pinned to llama.cpp -// 3cf03257f219afbe7334045ff7c6a06ac68c627d, sm_120 generic MMVQ. -// All pointers are device pointers, at least 4-byte aligned, with no overlap. -// All calls enqueue on the explicit non-null CUDA stream; no allocation or wait. -// The translation unit must use --use_fast_math, as the pinned CUDA oracle does. -// -// Shapes use GGUF order: n_in is the contiguous reduction dimension, n_out is -// the weight row count, and ncols is the activation column/token count, 1..8 -// (plan v0.3 P3). Columns are contiguous: activation column j is x + j * n_in -// (its Q8_1 blocks at j * n_in / 32) and output column j is y + j * n_out. See -// native_mmvq_set_multi_exact for how ncols > 1 relates to ncols == 1. -// n_in must be a positive multiple of 32 for quantization/Q4_0/Q5_0/Q8_0/IQ4_NL, -// 64 for Q2_0, or 256 for the other formats. n_out must be positive. Weights remain -// unmodified row-major GGUF blocks: Q3_K=110, Q4_K=144, Q5_K=176, Q6_K=210 and -// IQ4_XS=136 bytes per 256 elements; Q2_0 is 18 bytes per 64 elements. -// Q4_0/IQ4_NL=18, Q5_0=22, Q8_0=34 bytes per 32 elements. -// Q8_1 scratch has 36 bytes per 32 elements, with no extra row padding here. -// Input floats must be finite, and their block scales/sums representable in FP16. -std::size_t native_q8_1_bytes(int n_in, int ncols = 1); - -// Layout for ncols > 1. false: llama.cpp's generic multi-column table (upstream), equal to ncols == 1 to -// float rounding, speed not yet measured. true (default): the ncols == 1 layout, every column bitwise equal to a -// single-column call. Set before -// graph capture; captured graphs keep the kernels they captured. -void native_mmvq_set_multi_exact(bool exact); -bool native_mmvq_multi_exact(); - -// One quantization may serve multiple weight matrices sharing the same input. -// Q8_1 stores FP16 scale and FP16 warp sum of the ORIGINAL float inputs; it does -// not reconstruct that sum from the quantized integers. -void native_quantize_q8_1(const float* x, void* x_q8_1, int n_in, int ncols, - void* stream); - -void native_swiglu_quantize_q8_1(const float* gate, const float* up, void* x_q8_1, - int n_in, int ncols, void* stream); - -void native_q5_k_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream); - -// Convenience composition: caller owns scratch sized by native_q8_1_bytes. -void native_q5_k_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream); - -void native_q2_0_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream); - -void native_q2_0_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream); - -void native_q3_k_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream); - -void native_q3_k_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream); - -void native_iq4_xs_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream); - -void native_iq4_xs_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream); - -void native_q4_k_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream); - -void native_q4_k_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream); - -void native_q6_k_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream); - -void native_q6_k_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream); - -void native_q4_0_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream); - -void native_q4_0_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream); - -void native_q5_0_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream); - -void native_q5_0_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream); - -void native_q8_0_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream); - -void native_q8_0_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream); - -void native_iq4_nl_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream); - -void native_iq4_nl_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream); - -// Storage/dispatch helpers take stable GGML type IDs, avoiding a ggml runtime -// dependency in the engine: Q4_0=2, Q5_0=6, Q8_0=8, Q3_K=11, Q4_K=12, Q5_K=13, -// Q6_K=14, IQ4_NL=20, IQ4_XS=23, Q2_0=42. Unsupported IDs throw in the byte-count -// and launch helpers; only the -// capability query returns false. -bool native_mmvq_supported(int ggml_type) noexcept; -std::size_t native_mmvq_weight_bytes(int ggml_type, int n_in, int n_out); -void native_mmvq(int ggml_type, const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/native_moe.hpp b/include/strata/kernels/native_moe.hpp deleted file mode 100644 index 34760ef..0000000 --- a/include/strata/kernels/native_moe.hpp +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once -#include - -namespace strata::kernels { -// Configure before constructing/capturing sessions. Existing captures keep their -// selected kernels; changing this flag does not rewrite an existing graph. -void native_moe_combine_set_enabled(bool enabled); -bool native_moe_combine_enabled(); - -// Pinned CUDA weighted-reduction contract for one token, k in [1, 15]. -// The backend fuses k=2..15; k=1 is its ordinary multiply/contiguous/add path. -// parts: k contiguous F32 rows of n_embd; weights: k F32 values. The first -// product rounds to F32, following products accumulate with FMA in expert order, -// and optional shared is added once afterward. Shared is not router weighted. -// Requires a nonnull ordered stream and disjoint output. No allocation or sync. -void native_moe_combine(const float* parts, const float* weights, const float* shared, - float* output, int64_t n_embd, int64_t k, void* stream); -/// n_tok rows (parts [n,k,N], weights [n,k], shared/output [n,N]) in one launch, each as the single call. -void native_moe_combine_multi(const float* parts, const float* weights, const float* shared, float* output, - int64_t n_embd, int64_t k, int n_tok, void* stream); -} diff --git a/include/strata/kernels/native_ple_postops.hpp b/include/strata/kernels/native_ple_postops.hpp deleted file mode 100644 index 97c4990..0000000 --- a/include/strata/kernels/native_ple_postops.hpp +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once -#include "strata/kernels/ple.hpp" - -namespace strata::kernels { - -// Fixed qwen4exp single-token geometry: embd=2560, streams=4, history=9, -// convolution kernel=4/dilation=3. All buffers are caller-owned and capture-safe. -struct NativePlePostopsBuffers { - float* key; // 10240, normalized projected key - float* query; // 10240, temporary normalized hidden; may equal normalized - float* gate; // 4 - float* gated; // 10240 - float* normalized; // 10240, append this to history AFTER this function - float* conv; // 10240 - float* result; // 10240, may equal hidden exactly -}; - -// Matches pinned llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d CUDA -// build_ple AFTER the two projections. Only norm_key/query/conv and conv1d_f16 -// fields of weights are used. Gamma is full [2560,4]; history is row-fastest -// [9,10240], and F16 taps are [4,10240]. Inputs must be finite. -// Require an explicit stream, nonnull aligned pointers and disjoint writable -// spans, with only the two exact aliases documented above allowed. No allocation -// or synchronization; retain every buffer through any captured graph execution. -void native_ple_postops(const float* projected_key, const float* hidden, - const float* value, const float* history, - const PleWeights& weights, const NativePlePostopsBuffers& buffers, - void* stream); - -/// The prompt path: T tokens at once, element for element the arithmetic of T calls of native_ple_postops with -/// the history advanced after each. `key` (T x 10240) holds the projected keys and is normalized in place; -/// `hidden` (T x 10240) becomes the result; `value` T x 2560; `query_norm` (T x 10240, the normalized hidden, then -/// the normalized gated values), `gated` (T x 10240) and `gate` (T x 4) are scratch; `history` (9 rows per -/// channel) is advanced past the T tokens. -void native_ple_postops_batch(float* key, float* hidden, const float* value, float* history, const PleWeights& w, - float* query_norm, float* gated, float* gate, int T, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/native_qsa.hpp b/include/strata/kernels/native_qsa.hpp deleted file mode 100644 index c56eb4d..0000000 --- a/include/strata/kernels/native_qsa.hpp +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once - -namespace strata::kernels { - -// Set before session construction/capture; existing CUDA graphs retain their -// selected kernels. Disabled by default. Integration chooses the call sites. -void native_qsa_set_enabled(bool enabled); -bool native_qsa_enabled(); - -// Pinned single-token CUDA F32 arithmetic from llama.cpp -// 3cf03257f219afbe7334045ff7c6a06ac68c627d. No allocation or synchronization; -// both functions require a nonnull caller-owned stream and four-byte alignment. -// Positive dimensions with n_cols*n_rows (or head_dim*n_head) <= INT_MAX. -// Finite inputs and finite intermediate sums/products are caller preconditions. - -// Contiguous input/output [n_cols,n_rows], gamma[n_cols] broadcast over rows. -// Each row has independent RMS statistics. Exact output==input is supported; -// otherwise all three spans must be disjoint. Epsilon must be finite and >= 0; -// epsilon==0 additionally requires a nonzero sum of squares in every row. -// Pinned 256-thread (width<1024) or 1024-thread XOR reduction, (scale*x)*gamma. -void native_qsa_rms_norm_weighted(const float* input, const float* gamma, float* output, - int n_cols, int n_rows, float epsilon, void* stream); - -// attn/output [head_dim,n_head]; q_full [2*head_dim,n_head], each row is -// [query channels, gate channels]. Output is attn*sigmoid(second-half gate). -// Exact output==attn is supported; all other spans must be disjoint. -void native_qsa_gate_apply(const float* attn, const float* q_full, float* output, - int n_head, int head_dim, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/native_qsa_indexer.hpp b/include/strata/kernels/native_qsa_indexer.hpp deleted file mode 100644 index fe66d4b..0000000 --- a/include/strata/kernels/native_qsa_indexer.hpp +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once -#include "strata/kernels/qsa.hpp" -#include "strata/kernels/rope_scaling.hpp" - -namespace strata::kernels { - -// Configure before session construction/capture. Disabled independently of the -// native QSA norm/gate switch; existing captures retain their selected kernels. -void native_qsa_indexer_set_enabled(bool enabled); -bool native_qsa_indexer_enabled(); - -// Pinned F16 raw-key cache / F32 pooling / weighted RMSNorm / text IMRoPE. -// Fixed single-sequence geometry: idx_dim=128, idx_block=4, n_rot=64. -// Uses the existing buffers: tail[3,128] stores half-rounded raw values expanded -// to F32; dead[128] is the repeated-cell0 spare key; pooled[max_cells/4+1,128] -// contains completed blocks followed by the spare; block_pos[1] changes only on -// completion and records that block's first absolute position. -// -// relative_pos_device is a cell index, advancing 0..max_cells-1 (use kStepPos, -// not the absolute RoPE position vector). The sequence is text, -// contiguous, with nonnegative pos_base divisible by four. Clear state before -// starting a new sequence. Completed block b rotates at pos_base+4*b; the spare -// always rotates at zero, including nonzero sequence bases, as in the oracle. -// Under rope scaling (rope_scaling.hpp) the zero angle keeps the spare's -// rotation an identity; YaRN's mscale rides in through cos(0) on both the pooled -// keys and the indexer queries, so selection is unchanged. -// -// Explicit nonnull stream; no allocation or synchronization. All spans must be -// aligned and disjoint, remain valid through replay, and contain finite values; -// raw values must round to finite F16 and epsilon must be finite and positive. -// max_cells is a positive fixed capacity; pos_base+max_cells must fit int32. -// Out-of-range device positions are ignored defensively, not host-validated. -// This adapter does not alter score accumulation, top-k, or finite 1e9 tail bias. -// perf-review C-2: the appends of cells [p0, p0 + n) at once, leaving the buffers exactly as n calls of the -// single append in order would (the prompt path appends a chunk before any query reads the state). raw [n, 128]. -// Host-side positions (not for a captured graph). -void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, int32_t pos_base, const float* gamma, - float epsilon, const QsaIndexerBuffers& b, const QsaShapes& s, int64_t max_cells, - const RopeScaling& scaling, void* stream); - -void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_device, - int32_t pos_base, const float* gamma, float epsilon, - const QsaIndexerBuffers& buffers, const QsaShapes& shapes, - int64_t max_cells, const RopeScaling& scaling, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/native_qsa_score.hpp b/include/strata/kernels/native_qsa_score.hpp deleted file mode 100644 index 9427a77..0000000 --- a/include/strata/kernels/native_qsa_score.hpp +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once -#include "strata/kernels/qsa.hpp" - -namespace strata::kernels { - -// Configure before capture; independent of native key pooling and norm/gate. -void native_qsa_score_set_enabled(bool enabled); -bool native_qsa_score_enabled(); - -// SM120, single contiguous text sequence: F32 pooled[128,max_blocks] and -// query[128,4], four-cell blocks, top-k budget2048. Matches the pinned CUDA MMF -// dispatch with the model's n_kv padded to256 (n_blocks a multiple of64), even -// when only a partial32-row tile is live. This is not the unpadded odd-row -// cuBLAS contract. MMA consumes the same raw F32 register bits as the oracle. -// -// step[kStepCount] is device memory, refreshed before each replay. max_blocks -// must equal max_cells/4+1. Completed pooled rows[0,n_bid) and the spare row -// [n_bid] must be initialized. Writes cell_scores[0,n_kv) only. Applies ReLU -// separately per head, ordered F32 head addition, optional F32 block bias, -// then finite1e9 F32 bias for the incomplete tail; full blocks also receive -// the reference's +0 bias. Does not alter selection, ties, or selected order. -// -// All spans are aligned, disjoint, persistent through replay; inputs finite. -// Explicit nonnull stream. No allocation, host count reads, or synchronization. -// Invalid device counts suppress writes defensively; callers own count validity. -void native_qsa_score(const float* pooled, const float* query, const float* block_bias, - const QsaShapes& shapes, const int32_t* step, - int64_t max_blocks, int64_t max_cells, - float* cell_scores, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/native_rope.hpp b/include/strata/kernels/native_rope.hpp deleted file mode 100644 index 95511b8..0000000 --- a/include/strata/kernels/native_rope.hpp +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include "strata/kernels/rope_scaling.hpp" - -namespace strata::kernels { -void native_rope_set_enabled(bool enabled); -bool native_rope_enabled(); - -// Pinned CUDA text-only IMRoPE: F32 rows, 64 rotated channels, equal text positions in all four -// IMRoPE sections. Each device position must be nonnegative. The position buffer remains live -// through graph replay. Supports head_dim 128/256 and exact x==out; partial overlap is rejected. -// Explicit stream required. No allocation or synchronization. -// -// The scaling (rope_scaling.hpp) rides in as the resolved process config: none reproduces the -// original contract exactly, linear/YaRN apply ggml's rope_yarn - the interpolation mix, the -// corr_dims ramp along the pairs, and the mscale magnitude correction folded into cos and sin. -// The struct's knobs are process constants, so kernel arguments baked at graph capture stay valid. -void native_rope_apply(const float* x, float* out, int rows, int head_dim, - int n_rot, const RopeScaling& scaling, const int* positions, void* stream); -} diff --git a/include/strata/kernels/native_router.hpp b/include/strata/kernels/native_router.hpp deleted file mode 100644 index 0511b0b..0000000 --- a/include/strata/kernels/native_router.hpp +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -#include - -namespace strata::kernels { -// Configure before session capture. Existing graphs retain their selected kernels. -// This experiment is off by default and does not modify the legacy router. -void native_router_set_enabled(bool enabled); -bool native_router_enabled(); - -// Pinned CUDA topk-moe contract for ONE token, 512 experts, top 10, softmax, -// no selection bias, lower normalization clamp 2^-14, and scale 1. -// Reads 512 finite F32 logits; writes 10 I32 IDs and 10 F32 weights. Equal -// computed probabilities select the lower expert index. All spans must be -// four-byte aligned and outputs disjoint from each other and the input. -// Requires a nonnull ordered CUDA stream. No allocation or synchronization. -void native_router_top10(const float* logits, int32_t* ids, float* weights, void* stream); -/// n_tok rows at once (logits [n,512], ids/weights [n,10]); each row exactly as the single call. -void native_router_top10_multi(const float* logits, int32_t* ids, float* weights, int n_tok, void* stream); -} diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp deleted file mode 100644 index a321ea7..0000000 --- a/include/strata/kernels/ngram.hpp +++ /dev/null @@ -1,216 +0,0 @@ -// include/strata/kernels/ngram.hpp - P2.S4: the PLE n-gram hash and the per-layer token table. -// -// Two halves that share nothing but the row indices they exchange: -// -// * `ngram_rows` - the HOST hash. Sixteen row indices per token from the last three token ids, computed -// with 64-bit multiply/xor and no tensor op at all. `qwen4exp.cpp` L1092-1124, where the source says -// outright that it is host-side because "ggml has no int64 and no xor". -// * `PleTable` - the row gather. `per_layer_token_embd.weight` is IQ4_NL and is NOT IN THE PACK: it is -// 51.2e9 elements (28.8 GB) in the ORIGINAL second GGUF shard, and it is the only tensor this engine -// reads from the GGUF rather than from the canonical pack. -// -// THE HASH IS THE ONE PLACE IN THIS MODEL WHERE A WRONG BIT IS SILENTLY PLAUSIBLE. Every one of its -// properties has a rival reading that produces a valid index in range: -// -// * XOR, not sum. Two equal tokens with equal multipliers cancel to zero under XOR and double under sum. -// * `%` vocab_size, not `& (vocab_size-1)`. The vocab sizes are 20000003, 20000023, 20000033, ... - not -// powers of two, so a mask would be a different function. -// * the EOS cut propagates FORWARD: an EOS at any position replaces that position AND every older one. -// * a missing predecessor is `LLAMA_TOKEN_NULL = -1`, tested as `t < 0`. Token id 0 is a REAL token. -// * the token's OWN eos does not cut its own context - only the predecessors are examined. -// -// All of those are asserted observable in `ple_parity.cpp` rather than trusted. -#pragma once - -#include -#include - -namespace strata::kernels { - -// ---- geometry, every value confirmed against the artifact (docs/gguf-metadata.txt) ---- -inline constexpr int NG_N_EMBD = 2560; // n_embd -inline constexpr int PLE_HEAD_DIM = 160; // qwen4exp.embedding_length_per_layer_input -inline constexpr int NGRAM_SIZE = 3; // qwen4exp.ple.ngram_size -inline constexpr int HEADS_PER_NGRAM = 8; // qwen4exp.ple.heads_per_ngram -inline constexpr int PLE_N_HEADS = (NGRAM_SIZE - 1) * HEADS_PER_NGRAM; // 16 -inline constexpr int PLE_CONV_KERNEL = 4; // qwen4exp.ple.conv_kernel -inline constexpr int32_t PLE_EOS_TOKEN_ID = 248044; -inline constexpr int NG_HC = 4; // hyper_connection.count -inline constexpr int NG_HC_DIM = NG_HC * NG_N_EMBD; // 10240 -inline constexpr int NG_HIST = (PLE_CONV_KERNEL - 1) * NGRAM_SIZE; // 9 -inline constexpr int32_t TOKEN_NULL = -1; // LLAMA_TOKEN_NULL -inline constexpr float NG_RMS_EPS = 1e-6f; - -// The table: [160, 320001536] IQ4_NL. ne0 = 160 is the FAST axis, so one row is 160 contiguous elements = -// 5 blocks of 32 at 18 bytes = 90 bytes. The head-slowest flatten then makes 16 rows exactly n_embd = 2560. -inline constexpr uint64_t PLE_TABLE_ROWS = 320001536ull; -inline constexpr int PLE_ROW_BYTES = (PLE_HEAD_DIM / 32) * 18; // 90: an IQ4_NL row -inline constexpr int PLE_ROW_BYTES_FP8 = PLE_HEAD_DIM; // 160: an F8_E4M3 row, one byte a value -inline constexpr int PLE_ROW_BYTES_MAX = PLE_ROW_BYTES_FP8; - -/// The artifact's own hash constants, transcribed from `docs/gguf-dump-shard1.txt`: -/// -/// layer_multipliers = [23703573157769, 20109073645365, 8052911324071] -/// head_vocab_sizes = [20000003, 20000023, ...] 16 entries, NOT an arithmetic sequence -/// head_offsets = [0, 20000003, 40000026, ...] the running sum of head_vocab_sizes -/// -/// `ref/ngram.py::selftest` calls its own copies "synthetic but STRUCTURALLY REAL"; they are in fact -/// `20000003 + 10*i` for the vocab sizes, which the artifact's are not (20000003, 20000023, 20000033 - the -/// differences are 20, 10, ...). A selftest is free to use whatever constants it likes, but a PARITY test -/// against the artifact must use these, and the difference is recorded because it is exactly the kind of -/// thing that gets copied from the reference into an engine. -struct PleConsts { - uint64_t mult[NGRAM_SIZE]; - uint64_t vocab[PLE_N_HEADS]; - uint64_t offset[PLE_N_HEADS]; -}; -PleConsts ple_artifact_consts(); - -/// `mixed_n = (ctx[0]*m[0]) ^ (ctx[1]*m[1]) ^ ... ^ (ctx[n-1]*m[n-1])` in uint64. -/// -/// Exposed separately so a test can assert the XOR STRUCTURE directly rather than only its consequences. -uint64_t ngram_mixed(const int64_t* ctx, const uint64_t* mult, int n); - -/// The sixteen row indices per token. `qwen4exp.cpp` L1092-1124. -/// -/// tokens (n_tokens,) the ubatch's own tokens -/// prev (n_tokens, 2) predecessors OLDEST FIRST, `TOKEN_NULL` where there is none -/// out (n_tokens, 16) row indices into the PLE table -/// -/// The window is built once per token and then only its PREFIXES are used, which is what makes the bigram -/// heads (0..7) and the trigram heads (8..15) agree about the recent history. -void ngram_rows(const int32_t* tokens, const int32_t* prev, int n_tokens, const PleConsts& c, uint32_t* out); - -/// The IQ4_NL codebook: `{-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113}`, -/// which is `kvalues_iq4nl` from `ggml-common.h` L1121 and also the manifest's `codebooks.IQ4NL`. -/// -/// There is NO `-8` in this version of ggml. Some releases of `dequantize_row_iq4_nl` subtract 8 from the -/// codebook value; at 3cf03257 they do not, and the difference would shift every one of the 51.2e9 elements. -int iq4nl_code(int code); - -/// One 90-byte row -> 160 floats. The canonical rule `value = cb[code] * scale + offset` with offset 0, -/// because IQ4_NL has no min term (`has_offset` is false in the manifest). -/// -/// THE NIBBLE ORDER IS SPLIT-HALF, NOT INTERLEAVED, and that is the trap here. `dequantize_row_iq4_nl` is -/// y[j] = d * kvalues[qs[j] & 0xf]; -/// y[j + QK4_NL/2] = d * kvalues[qs[j] >> 4]; -/// so byte j carries elements j and j+16 - NOT 2j and 2j+1, which is the natural reading and which produces -/// a perfectly plausible embedding of the wrong 160 values. -void iq4nl_dequant_row(const uint8_t* row, float* out160); - -/// One FP8 row -> 160 floats: each byte an E4M3 value (the "fn" variant: no infinities, 0x7F/0xFF are NaN), times the -/// table's one scale. This is the table as Qwen3.8-Flash-Next ships it (`...ngram_embedding.shard_k`, F8_E4M3, and -/// `weight_scale`), kept byte for byte by tools/ple_fp8_pack.py; IQ4_NL is 8% off it per row. -void fp8_e4m3_dequant_row(const uint8_t* row, float scale, float* out160); - -/// How the table's rows are read (plan v0.3 P2). `Direct` is the default: unbuffered 4 KiB reads from the SSD, -/// so the table never occupies RAM or the OS file cache. `Mmap` is the earlier memory-mapped path, kept as the -/// A/B arm; it returns the same bytes. -/// -/// NEVER KEEP THE SHARD MAPPED WHILE READING IT DIRECT: a live section on the same file serializes the unbuffered -/// reads (311 -> 1,575 us per token, bench/results/2026-09-23-p2-ssd-direct). Direct mode drops its own mapping -/// after the header parse; nothing else in the process may hold one. -enum class PleIo { Direct, Mmap }; - -struct PleIoOptions { - PleIo mode = PleIo::Direct; - uint32_t max_inflight = 256; ///< outstanding SSD reads (decode needs 16; a prompt chunk saturates the SSD at 256) - uint64_t cache_rows = 1u << 20; ///< bounded row cache: 1,048,576 rows x 90 B ~ 95 MB; 0 disables - bool io_thread = true; ///< reads submitted by a worker thread, not the caller - /// Mmap mode only (`--ple-io ram`): lock the whole mapped table in RAM at open, so no SSD read ever sits on - /// the prompt or token path. Needs RAM for the full table. POSIX only (mlock); `locked()` reports the outcome. - bool lock = false; - /// Direct mode with the I/O worker only: keep the SSD awake while rows are asked for - one page of the table - /// after this long without a read (0 = off), until `keepalive_window_s` after the last request for rows - /// (see PleReader::set_keepalive). - double keepalive_ms = 0; - double keepalive_window_s = 60; -}; - -/// The PLE table. Held by pointer-to-impl so this header does not drag `` into every -/// translation unit that wants the hash. -class PleTable { -public: - PleTable(); - ~PleTable(); - PleTable(const PleTable&) = delete; - PleTable& operator=(const PleTable&) = delete; - - /// Open with an explicit I/O mode. The two-argument `open` below is the default (Direct). - bool open(const std::string& gguf_path, std::string& err, const PleIoOptions& io); - - /// The split the plan asks for: `issue` as soon as the token id is known, `collect` just before layer 1 - /// needs the rows. `gather` is `issue` followed by `collect`. In Mmap mode `issue` only prefetches. - bool issue(const uint32_t* rows16); - bool collect(float* out2560, std::string& err); - /// Non-blocking prefetch of 16 rows for one token into the reader's row cache while the GPU is busy. - void prefetch_rows(const uint32_t* rows16); - void wait_prefetches(); - /// Plan v0.3 P5: the rows of `n_tokens` tokens (16 each, `rows` token-major) into `out` (2560 floats per token), - /// as ONE reader request - page dedupe and sort across the whole batch, the reader's full queue depth. Not - /// while a single-token `issue` is pending. The mapped mode gathers row by row. - bool gather_batch(const uint32_t* rows, size_t n_tokens, float* out, std::string& err); - - /// Fault injection (Direct mode): every row read completes no earlier than `us` after issue. - void set_injected_delay_us(double us); - - /// Maps the ORIGINAL second GGUF shard read-only. The tensor's data does NOT start at file offset 0: - /// the manifest's `shard2_tensor.offset` is relative to the GGUF's DATA SECTION, and the header before it - /// is 192 bytes. Reading at 0 would silently decode the header plus 192 bytes of shifted rows - still - /// plausible IQ4_NL, which is why the reader takes the offset from a real GGUF parse (`GgufFile`, the - /// project's validated reader) and checks that the tensor exactly fills the rest of the file. - bool open(const std::string& gguf_path, std::string& err); - void close(); - bool is_open() const; - /// True when `PleIoOptions::lock` was asked for and mlock succeeded (false: pages only pre-touched). - bool locked() const; - uint64_t rows() const; - /// "IQ4_NL" or "F8_E4M3" (a GGUF from tools/ple_fp8_pack.py: type I8, strata.ple.format = f8_e4m3). - const char* format() const; - - /// 16 row indices -> 2560 floats. The gathered rows are flattened HEAD-SLOWEST: row h's 160 values - /// occupy `out[h*160, (h+1)*160)`, which is what `ggml_get_rows` does and what makes the result a plain - /// n_embd-wide vector for the block that consumes it. - void gather(const uint32_t* rows16, float* out2560) const; - - /// One row -> 160 floats, for diagnostics and for the parity test's oracle comparison. - void read_row(uint32_t row, float* out160) const; - - /// Bytes actually touched since `open`, for the "how often is it not ready" measurement P2.S4 asks for. - uint64_t bytes_read() const; - - /// One line of reader statistics (Direct mode), e.g. for --stats. Empty in Mmap mode. - std::string io_report() const; - PleIo mode() const; - -private: - struct Impl; - Impl* impl_ = nullptr; -}; - -// ================================ THE PLE GATHER'S PREFETCH, AND ITS A/B ARM ================================ -// -// `gather` issues its sixteen row reads as sixteen SEPARATE page faults into a 26.8 GB mapping, which measured -// **2.10-2.61 ms per token** and is second only to the layer loop among the token's avoidable terms. The table -// is 90 B per row, so the sixteen rows are 1,440 B - 0.5 MB/s, which is latency and not bandwidth, and it is -// because the sixteen pages are taken one at a time. `PrefetchVirtualMemory` issues them in one call. -// -// **THIS SWITCH EXISTS SO THE CLAIM CAN BE MEASURED RATHER THAN ASSERTED.** Cross-build comparisons in this -// project have repeatedly turned out to be machine drift - `LAYERS` alone moves 48.9 -> 52.3 between runs of -// one binary - so the two arms are alternated inside one session. Off is `--no-ple-prefetch`. -void ple_prefetch_enable(bool on); -bool ple_prefetch_enabled(); - -// ---- NOTE ON `madvise(MADV_RANDOM)` ------------------------------------------------------------------ -// P2.S4 asks for `madvise(MADV_RANDOM)` on the mapping, and on Linux that is exactly right: a token gathers -// 16 rows scattered over 28.8 GB, so read-ahead is pure waste and would evict useful pages. -// -// THERE IS NO LINUX, SO THERE IS NO MADV_RANDOM HERE. Windows has no equivalent of the advice - the closest -// is `FILE_FLAG_RANDOM_ACCESS` at CreateFile time, which suppresses the cache-manager's read-ahead for the -// whole handle, and `PrefetchVirtualMemory` for the positive case. `GgufFile` opens with neither, so this -// build gets the DEFAULT sequential read-ahead on a random access pattern. Saying so is the point: a -// comment claiming MADV_RANDOM here would be a comment about code that does not run. On Linux the advice -// belongs in `GgufFile::open`, which this module does not own. -// ------------------------------------------------------------------------------------------------------ - -} // namespace strata::kernels diff --git a/include/strata/kernels/ple.hpp b/include/strata/kernels/ple.hpp deleted file mode 100644 index 76ae789..0000000 --- a/include/strata/kernels/ple.hpp +++ /dev/null @@ -1,123 +0,0 @@ -// include/strata/kernels/ple.hpp - P2.S4: the PLE block's GPU half (`build_ple`, qwen4exp.cpp L1206-1293). -// -// One token, sixteen gathered rows of 160 -> a residual-stack update: -// -// key = grouped_norm(ple_key @ emb) hc_dim, per-stream RMS then a [n_embd,hc] gamma -// query = grouped_norm(hidden, ple_norm_query) -// value = ple_value @ emb n_embd -// s[c] = sum_d(key[c]*query[c]) / sqrt(n_embd) -// gate[c] = sigmoid(sign(s) * sqrt(max(|s|, 1e-6))) signed square root, then sigmoid -// gated[c] = value * gate[c] value broadcast over the hc streams -// normalized= grouped_norm(gated, ple_norm_conv) <-- THE CONV INPUT -// conv = sum_k kW[k][c] * padded[hist + t - (kern-1-k)*dil][c] -// out = hidden + gated + silu(conv) -// -// **`normalized` IS THE CONV INPUT, AND `ref/ngram.py` SAYS OTHERWISE.** Its `ple_block` docstring calls -// `terms` "the padded gated values", but the source pads `normalized` - the grouped_norm of the gated values, -// not the gated values themselves - and `ple_layer_xcheck.cpp` L107-112 builds it that way from ggml. The -// reference computes `normalized` and then ignores it, passing `terms` in from the caller, so its own code -// does not contradict its docstring and nothing catches it. This header takes the HISTORY OF NORMALIZED -// ROWS, which is what the state actually is. -// -// WHERE THE WEIGHTS LIVE, and the two different layouts in play. `ple_conv1d.weight` has manifest shape -// [4, 10240] with ne0 = 4 fast, so ggml's flat index is `k + 4*c`; `ref/ngram.py`'s `kernel` is a (4, 10240) -// numpy array whose flat index is `k*10240 + c`. They are transposes, and the source's own view -// (`ggml_view_2d(tWc, 1, hc_dim, nb[1], k*nb[0])`) confirms which is meant. `ple_key` and `ple_value` are -// [2560, n] with ne0 = 2560 fast, which IS the reference's row-major orientation. -#pragma once - -#include - -namespace strata::kernels { - -/// Opt in to pinned CUDA BF16/F32 MMVF for the PLE value projection only (default false). -/// Configure before session capture; captured graphs retain their selected projection kernels. -void ple_set_native_bf16(bool enabled); -bool ple_native_bf16_enabled(); - -/// Opt in to pinned CUDA postprojection norms, gate, convolution and residual -/// arithmetic (default false). Set before capture; existing graphs keep their -/// selected kernels. Independent of the key/value projection options. -void ple_set_native_postops(bool enabled); -bool ple_native_postops_enabled(); - -/// Weights of the single PLE layer (`ple.layers = [1]`). `blk.1.*` in the pack. -/// -/// key_codes / key_scales `ple_key.weight` S2, [n_embd, hc_dim], code_bias -1, group 64. -/// The pack stores `scales_fp16: true`, and every S-form kernel in this project -/// (including `s2_gemv_q8`) takes scales as F32 - so the LOADER widens them once, -/// as it already must for the experts. Recorded because "the manifest says fp16" -/// and "the kernel wants float" is a silent 2x-read if nobody says which wins. -/// value_bf16 `ple_value.weight` BF16 as raw bits, [n_embd, n_embd] -/// norm_key/query/conv F32 [hc_dim], NO (1+w) folding - `ref/gdn.py` records the same for `ssm_norm` -/// conv1d_f16 `ple_conv1d.weight` F16, GGML-NATIVE `kW[k + kern*c]` -struct PleWeights { - const uint8_t* key_codes = nullptr; // hc_dim * (n_embd/4) bytes - const float* key_scales = nullptr; // hc_dim * (n_embd/64) floats - const uint16_t* value_bf16 = nullptr; // n_embd * n_embd - const float* norm_key = nullptr; // hc_dim - const float* norm_query = nullptr; // hc_dim - const float* norm_conv = nullptr; // hc_dim - const uint16_t* conv1d_f16 = nullptr; // PLE_CONV_KERNEL * hc_dim, flat index k + 4*c - - /// Optional unchanged GGUF Q2_0 [2560,10240] key projection. Nonnull data - /// requires type 42 and caller-owned native_q8_1_bytes(2560) device scratch, - /// disjoint from the PLE workspace, inputs, weights and exported outputs. - /// Use an explicit ordered stream and retain both buffers through graph - /// execution. Null data preserves the canonical key projection. - const void* key_native_data = nullptr; - int key_native_type = -1; - void* key_native_q8_1 = nullptr; - /// Plan v0.3 P6: the IQ model files keep `ple_key` in BF16 ([n_embd, hc_dim], `w[o*n_embd+i]`); when set it - /// replaces both key paths above. - const uint16_t* key_bf16 = nullptr; -}; - -/// Everything the block produces, in the order `ple_layer_xcheck`'s oracle writes it. Any pointer may be -/// null; the caller that only wants the result passes nothing else. Having the intermediates is what makes -/// the parity test able to say WHICH stage diverged instead of only that the sum did. -/// Every nonnull output region, including result, must be disjoint from the block's entire scratch region. -/// result may alias hidden. The block rejects scratch/output overlap before launching any work. -struct PleOut { - float* key = nullptr; // hc_dim - float* value = nullptr; // n_embd - float* gate = nullptr; // hc - float* gated = nullptr; // hc_dim - float* normalized = nullptr; // hc_dim - float* conv = nullptr; // hc_dim - float* result = nullptr; // hc_dim -}; - -/// One token. `emb` is the 2560-wide gathered n-gram embedding, `hidden` the hc_dim residual stack, and -/// `hist_rows` the NG_HIST previous NORMALIZED rows, oldest first (the caller owns that cache). -/// -/// `hist_rows` IS ROW-FASTEST: `hist_rows[row + NG_HIST*channel]`. That is not a choice - it is -/// `ggml_reshape_3d(state, d_conv-1, conv_channels, n_seqs)`, so ne0 = the history row varies fastest, and -/// `ple_layer_xcheck.cpp` L79-83 records the transposed reading failing ggml's own assert. -/// -/// The block does NOT write back to the history: the caller keeps ownership of its state and this stays a -/// pure function of its inputs, which is what makes the chunked-versus-single-shot property testable. -/// Bytes the caller must hand `ple_block` as its workspace: five `hc_dim` buffers (key, query, norm, -/// gated, conv), one `n_embd` (value) and one `hc` (gate), plus the Q8 activation image and the BF16 -/// embedding copy. **THE WORKSPACE IS THE CALLER'S BECAUSE THIS FUNCTION IS CAPTURED**: it used to -/// `cudaMalloc` three times and `cudaStreamSynchronize` once per call, and inside a graph both are errors - -/// `ple_block: scratch: operation not permitted when stream is capturing`. Same defect, same fix as -/// `shared_expert`. -uint64_t ple_block_scratch_bytes(); - -void ple_block(const float* emb, const float* hidden, const float* hist_rows, const PleWeights& w, - PleOut& out, void* scratch, void* stream); - -void ple_block_projected(const float* projected_key, const float* projected_value, const float* hidden, - const float* hist_rows, const PleWeights& w, PleOut& out, void* scratch, void* stream); - -/// Advance the row-fastest normalized history by one token: hist[r,c] = old_hist[r+1,c], then append -/// normalized[c] at row NG_HIST-1. One thread owns each channel, making the in-place shift well-defined. -/// hist and normalized must be nonnull, disjoint device regions of NG_HIST*NG_HC_DIM and NG_HC_DIM floats. -/// Async on stream, allocation-free and capture-safe. Throws on null or overlapping regions. -void ple_history_advance(float* hist, const float* normalized, void* stream); - -/// Whether the CUDA path is available. The host hash and the table read work without it; the block does not. -bool ple_block_available(); - -} // namespace strata::kernels diff --git a/include/strata/kernels/q8_1_finite.hpp b/include/strata/kernels/q8_1_finite.hpp deleted file mode 100644 index 7826dbc..0000000 --- a/include/strata/kernels/q8_1_finite.hpp +++ /dev/null @@ -1,33 +0,0 @@ -// include/strata/kernels/q8_1_finite.hpp - #606: the q8_1 activation block's scale and sum, kept finite. -// -// A q8_1 block stores its scale d = amax / 127 and the sum of its 32 raw activations as fp16. A sum past 65504 (one -// massive-activation dimension among 32 values is enough) rounds to inf, and d does past amax = 8.3M; the dot -// products then read inf * 0 = NaN, and a NaN in the residual ends as one token repeated (ggml-org/llama.cpp#23606 -// is the same defect). Clamped to the largest finite half, such a block gives an approximate product instead of NaN, -// and the values are held to the int8 range they then exceed. Every block that was finite before is stored bit for -// bit as before: values in (65504, 65520) round to 65504 anyway, and a finite block's |x / d| is at most 127. A NaN -// stays NaN (the comparisons are false for it), so STRATA_DBG_NAN still sees one. -#pragma once - -#include - -namespace strata::kernels { - -constexpr float kHalfMax = 65504.0f; - -__device__ __forceinline__ float q8_1_finite(const float v) { - return fabsf(v) > kHalfMax ? copysignf(kHalfMax, v) : v; -} - -/// The block's quantized value of `xi` for the (finite) scale `d`; `amax` = 0 is an all-zero block. -__device__ __forceinline__ int8_t q8_1_quant(const float xi, const float d, const float amax) { - if (amax == 0.0f) return 0; - const float q = roundf(xi / d); - return (int8_t) (q > 127.0f ? 127.0f : q < -127.0f ? -127.0f : q); -} - -__device__ __forceinline__ half2 q8_1_ds(const float d, const float sum) { - return make_half2(__float2half(q8_1_finite(d)), __float2half(q8_1_finite(sum))); -} - -} // namespace strata::kernels diff --git a/include/strata/kernels/qsa.hpp b/include/strata/kernels/qsa.hpp deleted file mode 100644 index 863fc55..0000000 --- a/include/strata/kernels/qsa.hpp +++ /dev/null @@ -1,393 +0,0 @@ -// include/strata/kernels/qsa.hpp - the QSA (full-attention) layer's cache, indexer and attention, P2.S2. -// -// Spec of record: `ref/qsa.py` (whose own selftest carries eleven PROPERTY checks) and `ref/model.py::_qsa` / -// `_indexer` / `_attend`, transcribed from `build_layer_attn` / `build_attn_qsa` in the source. The -// projections are NOT here: `attn_q`, `attn_k`, `attn_v`, `attn_output`, `indexer.q_proj` and -// `indexer.k_proj` are the existing `s_gemv`/`s2_gemv` kernels, exactly as `gdn_step` leaves them. What lives -// here is everything BETWEEN the projections: -// -// kv_append the new token's K and V into the paged cache -// indexer_key_append the raw indexer tail, and the pooling that fires on block completion -// qsa_index per-CELL indexer scores: Relu per head, sum over heads, + bias, mapped by cell_block -// topk_512 the selection: the `width` largest cells, ties by ascending index, returned ascending -// kv_gather selected cells through the PAGE TABLE into a contiguous scratch -// qsa_attend softmax GQA over the scratch -// qsa_gate_apply `attn * sigmoid(gate)` and the round to the fp16 activation `attn_output` consumes -// -// DECODE ONLY, and that is a deliberate scope statement rather than an omission. `ref/qsa.py::indexer_scores` -// has no mask parameter and says why: "The causal part of the mask is already satisfied: every cached cell -// precedes the query at decode." The plan's `qsa_index` bullet asks for a "block-causal mask", and at decode -// its entire content is the TAIL -> SPARE SLOT mapping (`cell_block`), which is implemented here and tested. -// The per-query form - a query at position i may only see blocks with `block_start + r - 1 <= i`, plus the tail -// tokens - is a PREFILL property: `phases/phase-5-prefill-and-context-reuse.md` L73 builds it as a -// [chunk x blocks] GEMM with per-row top-k. Adding a mask flag here that decode cannot exercise would be a -// parameter with no observable behaviour, and this project has already been bitten by checks that cannot see -// the thing they claim to check. -// -// ============================================================================================ -// **THIS WHOLE API IS NOT YET CAPTURABLE, AND IT IS NOT OBVIOUS WHICH PARTS ARE NOT.** -// -// A CUDA graph bakes kernel ARGUMENTS in at capture time. Any argument that CHANGES PER TOKEN is therefore -// frozen at its first-token value on replay - silently, because the graph still runs, still produces finite -// output, and still looks correct. Auditing this header for that property (round 211-212) found FIVE entry -// points, not one: -// -// kv_append int64_t pos every token the new cell's position -// qsa_index int64_t n_bid every token completed blocks -// qsa_index int64_t n_kv every token cached cells -// topk_512 int64_t n_kv every token cached cells -// kv_gather int64_t n_ids every token = qsa_selection_width(n_kv, s) -// qsa_attend int64_t n_ids every token as above -// indexer_key_append int64_t pos FIXED now takes `const int32_t* pos_dev` -// -// WHAT A CAPTURED LAYER WOULD ACTUALLY DO, and it is worse than a crash: `kv_append` would write EVERY token to -// position 0, `qsa_index` and `topk_512` would score exactly one cell, `kv_gather` would gather one cell, and -// attention would be over a single cell for the whole sequence. Finite, plausible, and indistinguishable from -// "the model has no context" - a symptom that would be blamed on the KV cache, the selection, or the weights. -// -// THE FIX IS ONE DEVICE BUFFER, NOT SIX SIGNATURES. Every one of these values is a pure function of the -// current position and the geometry, so they belong together in a small device-resident step state that is -// written once per token: -// -// step[0] = pos step[1] = n_kv = pos+1 -// step[2] = n_bid step[3] = width = qsa_selection_width(n_kv, s) -// -// Each kernel reads the entries it needs, every argument list becomes constant across tokens, and the whole -// QSA path captures. Writing it as six separate pointer parameters would leave six places to forget and no -// single thing to check. -// ============================================================================================ -// -// ---- LAYOUTS. Every one of these is a runtime buffer and not a weight, so the layout is a free choice - but -// it must be WRITTEN DOWN, because the alternatives index the same numbers and a mix-up is silent. -// -// K/V CACHE: FP16, paged, `[page][kv_head][page_size][head_dim]` with head_dim fastest. The plan says "FP16 -// first" and fp16 is also what makes 32K of context fit: 12 layers x 2 heads x 256 dims x 2 (K and V) x 2 B x -// 32768 = 805 MiB, against 1.6 GiB in f32. The page granule is coarse (the shape's `page_size`) for the -// reason `Memory/Qwen-5070-engine-campaign/src/plans/paged-kv-cache.md` L146-170 gives: this engine serves a -// handful of sequences and not hundreds, so fine granularity buys nothing and costs per-token indirection. The -// physical row for logical cell `t` and head `h` is -// -// page = table[t / page_size]; (page * n_head_kv + h) * page_size + (t % page_size) -// -// i.e. ONE HEAD's worth of consecutive cells is contiguous within a page. That is the property attention -// wants; the alternative (cell-major inside the page) makes a cell's two heads contiguous instead, which is -// the property `kv_append` wants and nowhere near as valuable. **Nothing outside this header may assume the -// mapping**: `qsa_attend` reads a gathered scratch and never a pool, and the test runs the same fixture at -// page_size 1, 4 and 512 with a permuted page table and requires the attention output to be IDENTICAL, so the -// granule cannot leak into the result. -// -// INDEXER KEYS: FP32, not fp16 and not the plan's INT8. These carry no tolerance anywhere in the contract: -// `docs/capture-format.md` L127 makes `indexer_ids` an EXACT key, because a different selected cell is a -// different attention input. The key is a pooled MEAN of four raw keys followed by a norm and a rotation, so -// an fp16 store perturbs every score by ~2^-11 relative, and the selection boundary is exactly where that -// matters. The cost of fp32 is 512 B per block per layer = 128 B/token/layer = 1.5 KiB/token over the 12 QSA -// layers, i.e. 50 MiB at 32K: cheap next to a correctness contract. The plan's INT8 indexer key is a Phase 3 -// optimisation and it has to be justified by a measured selection-flip rate against this baseline. -// -// The RAW tail is fp32 for the same reason and because it is only `idx_block - 1` rows. -#pragma once - -#include -#include - -namespace strata::kernels { - -/// Geometry of one QSA layer. The real artifact: n_head 24, n_head_kv 2, head_dim 256, n_rot 64, -/// idx_n_head 4, idx_dim 128, idx_block 4, idx_top_k 2048, freq_base 1e7, rms_eps 1e-6. -struct QsaShapes { - int64_t n_head = 0; ///< query heads (24). n_head must be a multiple of n_head_kv - int64_t n_head_kv = 0; ///< key/value heads (2). The q -> kv map is `q / (n_head/n_head_kv)`, NOT `q % kv` - int64_t head_dim = 0; ///< 256, and must be a multiple of 4 - int64_t n_rot = 0; ///< 64 rotated dims of head_dim (and of idx_dim), NEOX pairs - int64_t idx_n_head = 0; ///< indexer query heads (4) - int64_t idx_dim = 0; ///< indexer key width (128) - int64_t idx_block = 0; ///< r = 4: the indexer pools one key per 4 cells - int64_t idx_top_k = 0; ///< 2048 cells of selection budget - int64_t page_size = 0; ///< KV page granule in CELLS; 1 is a legal unpaged configuration -}; - -/// The real artifact's geometry, so no caller transcribes it by hand. -inline QsaShapes qsa_real_shapes() { - QsaShapes s; - s.n_head = 24; s.n_head_kv = 2; s.head_dim = 256; s.n_rot = 64; - s.idx_n_head = 4; s.idx_dim = 128; s.idx_block = 4; s.idx_top_k = 2048; - // one page = one indexer block (4 cells): the granule KV streaming keeps resident (kv_stream.hpp). The readers - // resolve a row per cell anyway, so the page size costs them nothing (measured: identical output and speed). - s.page_size = 4; - return s; -} - -/// The one legal RMSNorm epsilon for this artifact (`attention.layer_norm_rms_epsilon`). -inline float qsa_rms_eps() { return 1e-6f; } -/// `rope.freq_base`, the DEFAULT frequency base. The artifact ships no `rope.scaling` keys, so the -/// process's rope scaling starts at none - the runtime configuration lives in `rope_scaling.hpp` -/// (`rope_scaling_set`, once at startup, before the table is built and any graph captured), and this -/// constant is what that config's `freq_base` defaults to and what CLI `--rope-freq-base` overrides. -inline double qsa_freq_base() { return 1e7; } - -/// DENSE attention (Qwen3.6-35B-A3B, docs/QWEN36-35B-A3B.md 3.3): the full-attention layers have no indexer, so -/// every cell is selected every token. The signal is the three indexer widths ZERO TOGETHER, which is what the -/// one builder (`strata/core/qsa_shapes.hpp`) writes for a geometry without an indexer; a shape with some of them -/// zero is half set up and `qsa_shapes_valid` refuses it, so the same predicate decides here and in the kernels' -/// guard. Under it the selection width is `n_kv`, the capacity is the state's `max_cells` (`qsa_selection_cap`), -/// and the attention kernels take a null `ids` as the identity. -inline bool qsa_dense(const QsaShapes& s) { return s.idx_n_head == 0 && s.idx_dim == 0 && s.idx_top_k == 0; } - -/// What every kernel's geometry guard checks (`qsa.cu`'s `validate`, which exits on a refusal): the head counts, -/// `n_rot`, the page size, and either a full indexer geometry or a dense one - never a half-set shape. The test -/// calls this; the kernels call the exiting form. -bool qsa_shapes_valid(const QsaShapes& s, char* why, size_t why_len); - -/// The selection width: `min(n_kv, idx_top_k + idx_block - 1)`; `n_kv` itself for dense attention. -/// -/// The `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 -/// per-token argument is frozen at its first-token value on replay - silently, because the graph still runs and -/// still produces finite output. Six entry points used to take one of these as a host scalar; every one of -/// them now reads it from here instead, which makes every argument list constant across tokens. -/// -/// WHAT IT PREVENTS, concretely: with `pos` frozen, `kv_append` writes every token to cell 0, `qsa_index` and -/// `topk_512` score one cell, `kv_gather` gathers one cell, and attention runs over a single cell for the whole -/// sequence. Finite, plausible, and indistinguishable from "the model does not use its context". -/// -/// The four entries are NOT independent - `n_kv = pos+1` and `width = qsa_selection_width(n_kv, s)` - which is -/// exactly why they live in one buffer with one writer: `qsa_step_write` computes all four from `pos`, so a -/// caller cannot update one and forget another. -/// -/// It is written by a plain H2D copy of four int32, which IS capturable and re-reads its source at replay -/// (`bench/micro/pinned_capture.cu` case B) - so the same buffer works in a captured graph and in a direct -/// launch. -enum QsaStep : int { - kStepPos = 0, ///< the new cell's sequence position - kStepNKv = 1, ///< pos + 1: how many cells are in the cache - kStepNBid = 2, ///< n_kv / idx_block: how many blocks have COMPLETED - kStepWidth = 3, ///< qsa_selection_width(n_kv, s): how many cells the selection returns (n_kv when dense) - kStepCount = 4, -}; - -/// `step` is (kStepCount,) int32 DEVICE memory. Pointers to it are passed to the entry points below; it is -/// allocated by the caller (it is per-sequence state, not scratch). -/// -/// Returns the bytes one step buffer needs, so a caller sizing an arena does not transcribe `kStepCount`. -inline uint64_t qsa_step_bytes() { return sizeof(int32_t) * (uint64_t) kStepCount; } - -/// Fills a HOST array of `kStepCount` int32 from `pos`, so a caller can upload it in one copy. Keeping the -/// arithmetic here rather than at the call site is the point of the buffer: `n_kv` and `width` are derived, -/// and a caller computing them by hand is a caller who can compute them differently. -void qsa_step_fill(int32_t* host_step, int64_t pos, const QsaShapes& s); - - -/// One token's K and V into the paged FP16 cache, at logical cell `pos`. -/// -/// k_pool, v_pool `[page][kv_head][page_size][head_dim]` fp16, page_size*n_pages cells each -/// page_table (n_pages,) i32: logical page -> physical page. NOT assumed to be the identity -/// kcur, vcur (n_head_kv, head_dim) f32. `kcur` must ALREADY be normed and rotated - V is never rotated -/// -/// The fp32 -> fp16 conversion is `f16_from_f32` (see f16_bits.hpp) and not `__float2half`. -void kv_append(uint16_t* k_pool, uint16_t* v_pool, const int32_t* page_table, int64_t pos, - const float* kcur, const float* vcur, const QsaShapes& s, void* stream); - -/// The selected cells through the page table into a contiguous scratch. -/// -/// ids (n_ids,) i32, logical cells, ASCENDING and unique as `topk_512` returns them -/// k_scratch etc (n_ids, n_head_kv, head_dim) fp16, written in full -/// -/// A cell that is not gathered does not exist for `qsa_attend`, which is how the top-k mask is realised: the -/// source fills the kq mask with -inf and leaves the selected cells at zero, so an unselected cell has weight -/// exactly zero even when it would score highest (`ref/qsa.py` PROPERTY 8 tests precisely that). -void kv_gather(const uint16_t* k_pool, const uint16_t* v_pool, const int32_t* page_table, const int32_t* ids, - int64_t n_ids, const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream); - -/// WHERE THE INDEXER'S PER-SEQUENCE STATE LIVES. One set per QSA layer per sequence. -/// -/// tail (idx_block - 1, idx_dim) f32 the RAW tail: cells of the block being filled, slot = pos % idx_block -/// dead (idx_dim,) f32 the spare slot's key, = rms_norm(raw key of cell 0), CONSTANT -/// pooled (max_cells/idx_block + 1, idx_dim) f32 block b at row b, the spare slot at row n_bid -/// block_pos (1,) i32 scratch: the kernel writes the completed block's first-cell -/// position here so the rotation can read it ON THE DEVICE -/// -/// **Every pointer in this struct is a DEVICE pointer**, and so are every other pointer this header's entry -/// points take: `rope_neox_apply` indexes its cos/sin table and its position array on the device, so a host -/// scalar passed as `pos` is an illegal access rather than a convenience. `block_pos` exists for exactly that -/// reason - the rotation position is derived from the host's `pos`, so it has to be handed to the device -/// through memory, which is also the only form a CUDA graph can replay. -/// -/// The spare slot MOVES: it is at row `n_bid`, and `n_bid` grows by one on every block completion. It is also -/// constant in value, because it is derived from cell 0's raw key and `rope_neox(., 0)` is the identity - which -/// is what makes a tail of three keys sufficient. A design that pooled only from the tail could not produce -/// this key at all after the first block. -struct QsaIndexerBuffers { - float* tail = nullptr; - float* dead = nullptr; - float* pooled = nullptr; - int32_t* block_pos = nullptr; -}; - -/// Append one raw indexer key (IDX_DIM wide, fp32, NEVER normed and NEVER rotated - `ref/qsa.py` L201-210) and -/// run the pooling if this cell COMPLETES a block. -/// -/// `pooled[b] = rope_neox(rms_norm(mean(raw[b*r .. b*r+r-1]), w_k_norm), pos of cell b*r)` for b = pos/r on a -/// completion, and the spare slot `pooled[n_bid] = rope_neox(rms_norm(raw[0], w_k_norm), 0)`. The rotation -/// position is the block's FIRST cell, which `ref/qsa.py` PROPERTY 4 pins and the test re-pins: rotating at the -/// block's LAST cell keeps every shape and every magnitude. -/// -/// **`pos_dev` IS A DEVICE POINTER AND THIS FUNCTION IS CAPTURABLE.** It used to take `int64_t pos` as a host -/// scalar, and a CUDA graph bakes kernel ARGUMENTS in at capture time - so a captured call would have replayed -/// the FIRST token's position forever: `slot = pos % idx_block` would never advance, no block would ever -/// complete, the indexer would keep pooling cells 0-3, and the selection would stay pinned to the first block. -/// Not a crash and not a small error - a plausible attention output over the wrong cells. Worse than a stale -/// POINTER, which this project's pitfalls list already warns about, because a stale pointer tends to fault while -/// a stale VALUE looks like a working graph. -/// -/// It could not be fixed by swapping the scalar for a pointer alone: `pos` was ALSO read on the host, to decide -/// whether to run the completion rotation at all and which pooled row to rotate. So the rotation moved INTO -/// the pooling kernel, which is why this now takes `cos_tab`/`sin_tab` and `n_rot`, and why `block_pos` is kept -/// only as a readable record of the rotation position rather than as the input to a second launch. -/// -/// `pos_base` IS THE SEQUENCE'S FIRST CELL'S POSITION, so cell j sits at position `pos_base + j`. The kernel -/// cannot derive it: `QsaCache.pos` is what the reference rotates by, and equating a cell's position with its -/// index is only right for a sequence that starts at 0. The test runs the fixture at `pos_base = 100`, where -/// the two readings are 514% apart. `pos_base` is CONSTANT for a sequence, so unlike `pos_dev` it is safe to -/// bake into a graph. -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); - -/// Per-CELL indexer scores, `n_kv = pos + 1` of them, fp32. -/// -/// pooled (n_bid + 1, idx_dim) block keys, the spare slot last, as `indexer_key_append` maintains them -/// q_idx (idx_n_head, idx_dim) ALREADY normed and rotated by the caller -/// bias (n_bid + 1,) or null optional additional per-block bias -/// -/// score[j] = bias[cb] + sum_h Relu(dot(pooled[cb], q_idx[h])), cb = min(j / r, n_bid) -/// score[j] += 1e9f for incomplete-tail cells (j >= (n_kv / r) * r). -/// The tail bias matches llama.cpp's causal decode input and applies even when bias is null. -/// Completed blocks receive no tail bias; the step API derives this from each replay's n_kv. -/// -/// The Relu is PER HEAD and the sum is over heads AFTERWARDS: `relu(sum_h dot_h)` is the rival reading, and it -/// is a different number whenever any head's dot is negative. Flipping one query head's sign can never lower -/// the score, which is the property the test asserts. There is NO softmax and NO 1/sqrt(d) here. -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); - -/// The largest `qsa_selection_width(n_kv)` cells of `cell_scores`, ascending, into `ids`. -/// -/// Ties are broken by ASCENDING INDEX. ggml does not specify that, and `ref/qsa.py` is explicit about it so a -/// mismatch is at least diagnosable; the host test compares against `np.lexsort((arange, -scores))`, which is -/// the same rule, implemented independently of the kernel's threshold search. -/// -/// `cap` is the caller's buffer size in ids and must be >= the width; the kernel writes EXACTLY `width` and -/// refuses rather than truncating. The `-1` padding that `docs/capture-format.md` L66-73 describes is the -/// capture writer's job, not this kernel's: the padded width is a property of the run, not of one token. -/// -/// `n_kv` must be <= 32768 (`kTopkMaxCells`): the selection runs in ONE block, which is what makes the -/// ascending tie rule deterministic without a second pass over global memory. Phase 3 replaces this with a -/// 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); - -/// Softmax GQA over ONLY the gathered cells. `q` is (n_head, head_dim) f32, already normed and rotated. -/// -/// scores[j] = dot(k[j][q / (n_head/n_head_kv)], q[h]) / sqrt(head_dim) -/// w = softmax_j(scores) -/// attn[h] = sum_j w[j] * v[j][q / (n_head/n_head_kv)] -/// -/// The q -> kv head map is INTEGER DIVISION (`ggml-cpu/ops.cpp` L8729: `iv2 = iq2 / rv2`), not `q % n_head_kv` -/// - with 24 and 2 the two give [0 x12, 1 x12] and [0,1,0,1,...], and both produce a well-formed result. -/// -/// `attn` is (n_head, head_dim) f32 and NOT yet gated; `weights`, when non-null, is (n_head, n_ids) f32, which -/// is what `docs/capture-format.md`'s `L{n}.qsa_scores` records. Produced here rather than recomputed by the -/// caller so the capture cannot drift from the attention it claims to describe. An EMPTY `ids` is legal and -/// gives a zero `attn` (no selected cell has no softmax to take). -void qsa_attend(const float* q, const uint16_t* k_scratch, const uint16_t* v_scratch, int64_t n_ids, - const QsaShapes& s, float* attn, float* weights, void* stream); - -/// `attn *= sigmoid(gate)` in f32, then ONE round to fp16 for the `attn_output` GEMV. -/// -/// q_full (n_head, 2*head_dim) f32 the raw `attn_q` projection, BEFORE any norm -/// gate = q_full[h][head_dim + d] - the SECOND half of each head's 2*head_dim block -/// out (n_head, head_dim) fp16 -/// -/// The split is NOT element-interleaved (`ref/qsa.py` PROPERTY 10 pins that: `q = per_head[:, :head_dim]`, -/// `gate = per_head[:, head_dim:]`), and the rounding happens AFTER the multiply so there is one rounding -/// rather than two. SIGMOID, not SiLU: this artifact's QSA gate is a sigmoid. -void qsa_gate_apply(const float* attn, const float* q_full, const QsaShapes& s, uint16_t* out, void* stream); - -/// THE SAME MULTIPLY WITHOUT THE fp16 ROUND, for the caller whose weight wants Q8_K. -/// -/// `attn_output` is a K-quant (Q4_K/Q5_K/Q6_K in every QSA layer of this artifact) and its `vec_dot_type` is -/// **Q8_K, not fp16** - `docs/activation-contract.md` is explicit, and the measured cost of getting it wrong is -/// 0.66-1.41% per GEMV against a 1e-3 tolerance, which is above what Gate C1 allows. The fp16 form exists -/// because that is what the engine did first; this one exists because that was a gap, and the caller quantizes -/// to Q8_K between the two calls. -/// -/// The arithmetic is IDENTICAL to `qsa_gate_apply`'s up to the last step, and the multiply is in double in both -/// - so switching between them changes exactly one rounding, which is the point. -void qsa_gate_apply_f32(const float* attn, const float* q_full, const QsaShapes& s, float* out, void* stream); - -// ================= THE CAPTURABLE ENTRY POINTS ================= -// -// These take the per-token counts from `step` AND size every launch from a CONSTANT capacity, which is the two -// things a CUDA graph requires. The host-scalar entry points above are thin wrappers over these: they fill a -// module-level step buffer and pass this token's counts as the capacities, so they behave exactly as before and -// stay convenient for a direct launch or a test. -// -// **THE LAYER MUST USE THESE.** The wrappers are correct for a direct launch and WRONG inside a graph: their -// grid and their shared size change per token, and a graph bakes both in. A captured `qsa_index` launched for -// one block leaves every other pooled row unscored; a captured `qsa_attend` sized for one cell reads past its -// shared buffer once the sequence grows. Both failures are silent. -// -// The kernels already guard for the surplus: `qsa_index_kernel` returns for `b > n_bid`, `kv_gather_kernel` -// returns past its device `n_ids`, and `qsa_attend_kernel` handles an empty selection itself. So passing a -// capacity LARGER than this token needs is correct, not merely safe. - -/// `max_blocks` must be at least `(max_cells / idx_block) + 2`. -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); - -/// `cap` must be `qsa_selection_width(kTopkMaxCells, s)` - the largest width the kernel can ever write. -void topk_512_step(const float* cell_scores, const QsaShapes& s, int64_t cap, const int32_t* step, - int32_t* ids, void* stream); - -/// `max_ids` must be the CAPACITY of `k_scratch`/`v_scratch` in ids. -void kv_gather_step(const uint16_t* k_pool, const uint16_t* v_pool, const int32_t* page_table, - const int32_t* ids, const int32_t* step, int64_t max_ids, const QsaShapes& s, - uint16_t* k_scratch, uint16_t* v_scratch, void* stream); - -/// `max_ids` must be at least the largest selection the geometry can produce, because it sizes the SHARED -/// memory the softmax works in. -void qsa_attend_step(const float* q, const uint16_t* k_scratch, const uint16_t* v_scratch, - const int32_t* step, int64_t max_ids, const QsaShapes& s, float* attn, float* weights, - void* stream); - -struct KvHostPools; // kv_stream.hpp - -/// The cell's position comes from `step`, so this is the form a graph may contain. With a host copy (KV streaming) -/// the cell is written there too, and to VRAM only if its block is resident. -void kv_append_step(uint16_t* k_pool, uint16_t* v_pool, const int32_t* page_table, const int32_t* step, - const float* kcur, const float* vcur, const QsaShapes& s, void* stream, - const KvHostPools* host = nullptr); - -} // namespace strata::kernels diff --git a/include/strata/kernels/qsa_decode_attn.hpp b/include/strata/kernels/qsa_decode_attn.hpp deleted file mode 100644 index 1bfc0fe..0000000 --- a/include/strata/kernels/qsa_decode_attn.hpp +++ /dev/null @@ -1,79 +0,0 @@ -// include/strata/kernels/qsa_decode_attn.hpp - plan v0.3 P3/P7: split-K decode attention over the selected cells. -// -// The first attention kernel runs one block per query head (24 blocks on a 48-SM part), reads each key row with one -// thread (uncoalesced) and walks every selected cell serially for the values; at a 4K context (2,051 selected -// cells) that costs ~0.3-0.5 ms per QSA layer. This one reads the KV POOLS directly through the page table and the -// selection ids (no gather copy), in chunks of CHUNK cells per block, and serves all `n_head / n_head_kv` query -// heads that share a KV head from one read of the chunk: -// -// grid (min(ceil(cap / 64), 128), n_head_kv): s = q.k * scale for G heads x 64 cells per sub-chunk, the -// running max m and sum l, acc = p . V -> one partial per block -// grid (n_head): merge the partials with the usual log-sum-exp rescale -// -// 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 -#include - -namespace strata::kernels { - -struct QsaAttnPools { - const uint16_t* k_pool = nullptr; ///< fp16 [page][kv_head][page_size][head_dim], or null when int8 - const uint16_t* v_pool = nullptr; - const int8_t* k_q = nullptr; ///< int8 codes, same layout - const int8_t* v_q = nullptr; - const uint16_t* k_scale = nullptr; ///< fp16 [page][kv_head][page_size][head_dim / 64] - const uint16_t* v_scale = nullptr; - const uint8_t* k_q4 = nullptr; ///< q4_0 block_q4_0 [page][kv_head][page_size][head_dim / 32 * 18] - const uint8_t* v_q4 = nullptr; - const int32_t* page_table = nullptr; -}; - -/// The query heads per KV head the kernels are instantiated for, from the geometry: 2, 8 or 12, else 0 with the -/// refusal in `why` (naming the heads). The entry points below call this and exit(1) on 0. -int qsa_attn_group(const QsaShapes& s, char* why, size_t why_len); -/// Whether `G` is a built group AND the geometry is `n_head == G * n_head_kv`: a 16-head model asked for G = 12 -/// is refused here by name, never run mis-indexed (the negative test of docs/QWEN36-35B-A3B.md section 6, step 3). -bool qsa_attn_group_check(const QsaShapes& s, int G, char* why, size_t why_len); - -/// Blocks per KV head for `cap` cells: `ceil(cap / 64)` for a sparse shape (the kernel before Qwen3.6, at any -/// capacity: the MTP drafter's ring runs it at its window), `min(ceil(cap / 64), 128)` for a dense one. The scratch -/// holds one partial per block. -int64_t qsa_decode_attn_chunks(int64_t cap, const QsaShapes& s); - -/// Scratch floats per query row for `cap` selected cells: `chunks(cap, s) * n_head * 258 + 64` (partial -/// accumulators, maxima and sums). Dense: bounded at 528,448 floats (2.02 MiB) at 16 heads for any cap >= 8,192. -/// Sparse: the previous formula, unchanged. -uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s); - -/// `ids` (cap,) i32 or NULL for the identity selection (every cell up to step[kStepWidth]). -void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* step, - int64_t cap, const QsaShapes& s, float* scratch, float* attn, void* stream); - -/// Plan v0.3 P5: `n_q` queries at once, each with its own selection: q [n_q, n_head, 256], ids [n_q, cap] or NULL -/// (the identity for every query), steps [n_q, kStepCount], attn [n_q, n_head, 256]; scratch is `n_q` times the -/// single-query size. -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 diff --git a/include/strata/kernels/qsa_prompt_attn.hpp b/include/strata/kernels/qsa_prompt_attn.hpp deleted file mode 100644 index 2391aae..0000000 --- a/include/strata/kernels/qsa_prompt_attn.hpp +++ /dev/null @@ -1,32 +0,0 @@ -// include/strata/kernels/qsa_prompt_attn.hpp - perf-review D-1: the prompt path's QSA attention on tensor cores. -// -// `qsa_decode_attn_batch` serves a prompt one query at a time with the decode kernel: FP32 dot products with a warp -// reduction per head and cell, 64-cell chunks whose partial sums go through global scratch to a second (merge) -// kernel. At 32K that is 21% of the prompt (5.6 s of 26 s on a 5070, Q2_0, int8 KV), and it is limited by -// instruction issue, not memory (~150 GB/s of logical reads, 3.4 TFLOP/s). -// -// This kernel keeps the same per-query selection (no masking, no union) and reads the same pools, but: -// * one block per (query, KV head) walks all its selected cells in chunks of 32 with an online softmax: no -// split-K scratch and no merge kernel; -// * q.k and p.v are m16n8k16 FP16 MMAs with FP32 accumulation over the 12 query heads of the KV head (+4 pad rows); -// * the stored values enter exactly: int8 codes are exact in FP16 and their per-64 scales are applied in FP32 -// (to the q.k partial of each 64-dim group, and folded into p for p.v); FP16 KV is used as is; -// * q and p are split into FP16 hi + lo parts (two MMAs each), so they keep ~22 bits: the result differs from -// the FP32 kernel by summation order and the exp2 rounding, not by an FP16 cast. -// Not bitwise equal to `qsa_decode_attn_batch`; `qsa_prompt_attn_parity` bounds the difference and the prompt -// quality gate (needles, teacher-forced top-1) checks it end to end. Q4_0 KV (mode 4): each block's codes enter -// exactly as int8 and its scale (one per 32 values) in FP32, as int8 KV's do (STRATA_PROMPT_ATTN_Q4=0: the old kernel). -#pragma once - -#include "strata/kernels/qsa_decode_attn.hpp" - -#include - -namespace strata::kernels { - -/// Same arguments and output as `qsa_decode_attn_batch` minus the scratch. Returns false (nothing launched) when the -/// geometry is not 24 heads / 2 KV heads / 256: the caller then uses the old kernel. -bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, - int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/qsa_select.hpp b/include/strata/kernels/qsa_select.hpp deleted file mode 100644 index 3150816..0000000 --- a/include/strata/kernels/qsa_select.hpp +++ /dev/null @@ -1,57 +0,0 @@ -// include/strata/kernels/qsa_select.hpp - plan v0.3 P5/P7: the QSA indexer's block scores and top-k selection, -// for many queries at once and at long context. -// -// The per-token path scores every pooled block with one FP64 block per row (qsa_index_kernel) and selects with a -// single-block kernel that makes 32 bit-serial passes over every CELL (topk_kernel): ~0.1-0.2 ms per query at 32K, -// once per QSA layer and token - 1-2 ms of a decode token and most of a 32K prompt's time. Here: -// -// qsa_block_scores : one warp per (query, block), FP32; relu per indexer head, summed; block n_bid (the -// incomplete tail) scores the `dead` key and gets +1e9 when it has cells - which is exactly -// what the per-token path reads there, because pooled[n_bid] holds `dead` at that time (in -// a chunk it may already hold a block completed later, so it is not read). -// qsa_block_topk : one block per query; a 4-pass radix select over the query's n_bid + 1 blocks, each -// weighted by its cell count, then the cells emitted in ascending order with ties to the -// lowest index - the same selection as topk_kernel, over a quarter of the elements. On sm_90+ -// a call of up to 16 queries runs it on a cluster of 8 CTAs per query: the same ids. -// -// Queries carry their own step record (pos, n_kv, n_bid, width) as everywhere else in QSA. -#pragma once - -#include "strata/kernels/qsa.hpp" - -#include - -namespace strata::kernels { - -/// scores [nq, max_blocks]; q_idx [nq, idx_n_head, idx_dim] (normed and rotated); steps [nq, kStepCount]. -void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq, - int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, - int64_t active_blocks = -1); ///< perf-review C-1: > 0 launches only this many blocks (the - ///< batch's largest n_bid + 1; not for a captured graph) - -/// The same scores on tensor cores (3xTF32, FP32-level accuracy but another summation order: not bitwise; the tail -/// block n_bid is the warp kernel's arithmetic). For the prompt path; false (nothing launched) on another geometry. -/// On AMD it is the gfx12 (RDNA4) WMMA kernel (a three-way bf16 split, six products); false on any other AMD target. -bool qsa_block_scores_tc(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq, - int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks); - -/// ids [nq, cap] (cells, ascending); `cap` >= the largest selection width. -void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, - const QsaShapes& s, int32_t* ids, void* stream, - int64_t active_blocks = -1); ///< > 0: no query of the call has more than this many blocks (n_bid + 1; - ///< the same contract as qsa_block_scores's). The register kernel is - ///< chosen by this, not by the capacity max_blocks (a long - ///< --max-context otherwise sends every short prompt to the slow one). - ///< CUDA uses the bound only on sm_75; HIP keeps its existing policy. - ///< Omit it for captured graphs whose context can grow after capture. -/// The same ids on a thread-block cluster of 8 CTAs per query (sm_90+, CUDA; S19). qsa_block_topk takes it for calls -/// of up to 16 queries unless STRATA_QSA_CLUSTER=0. False (nothing launched) where it cannot run: HIP, a card or a -/// build below sm_90, or a capacity whose keys do not fit one cluster's shared memory. Capturable. -bool qsa_block_topk_cluster(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, - const QsaShapes& s, int32_t* ids, void* stream); -/// The original kernel (256 threads, one shared histogram, keys read from memory on every radix pass), for tests and -/// STRATA_TOPK_OLD=1: the same ids. -void qsa_block_topk_ref(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, - const QsaShapes& s, int32_t* ids, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/quantize_act.hpp b/include/strata/kernels/quantize_act.hpp deleted file mode 100644 index 49d858b..0000000 --- a/include/strata/kernels/quantize_act.hpp +++ /dev/null @@ -1,58 +0,0 @@ -// include/strata/kernels/quantize_act.hpp - activation quantization, host-callable (P2.S2). -// -// `ggml_mul_mat` converts src1 (the ACTIVATION) to the weight's `vec_dot_type` before the dot product. The -// CPU expert path already does this (`bench/micro/cpu_s2.cpp`, int8 + vpdpbusd, parity 1.461e-06); the GPU -// kernels take FP16 activations. Leaving the two inconsistent means the same token computes different -// numbers for different experts, so this is the GPU half of the same rule. -// -// Q2_0 -> Q8_0 is the case that matters most: the routed experts are all Q2_0, which is 31.64 GiB of the 38 -// GiB pack. Q8_K is the OTHER HALF of `VEC_DOT_TYPE` (Q3_K/Q4_K/Q5_K/Q6_K/IQ4_XS) and covers 2.89 GiB of -// dense weights - the attention projections and `ssm_out`, i.e. the numerically sensitive ones. -// -// `docs/activation-contract.md` records the decision that BOTH must exist and be used: an FP16 activation -// against a quantized weight disagrees with the oracle by 0.6-0.9%, which is 6-9x P2.S2's 1e-3 tolerance. -#pragma once - -#include - -namespace strata::kernels { - -// x (n floats) -> ggml's block_q8_0 layout: 34 bytes per 32 elements, { fp16 d ; int8 qs[32] }. -// n must be a multiple of 32. `stream` may be null, in which case the call synchronises. -void quantize_q8_0(const float* x, uint8_t* blocks, int64_t n, void* stream); - -// **R4.2h: THE SAME BLOCKS, PLUS THE CPU's fp32 SCALE - and the CPU's rounding rule with it.** The engine -// computes each routed expert twice (misses on the CPU through `act_quant_q8_1`, hits on the GPU through -// `quantize_q8_0`) and the two disagreed: `ActQ::scale` is fp32 while a `block_q8_0` stores fp16 `d`, which is -// **4.761e-04 relative on 80 of 80 chunks** (`bench/micro/act_quant_parity.cu`). This variant exists so the -// hit path can use the CPU's multiplier. Writes `blocks[n/32 * 34]` and `scales[n/32]`; `scales` must not be -// null. `quantize_q8_0` is unchanged and still matches ggml's bytes, which is what `moe_hit_parity` checks. -void quantize_q8_0_scaled(const float* x, uint8_t* blocks, float* scales, int64_t n, void* stream); - -// The inverse, for round-trip checks: each element becomes `q * d16`. -void dequant_q8_0(const uint8_t* blocks, float* x, int64_t n, void* stream); - -// x (n floats) -> ggml's block_q8_K layout: 292 bytes per 256 elements -// { float d ; int8_t qs[256] ; int16_t bsums[16] } -// n must be a multiple of 256. `stream` may be null, in which case the call synchronises. -// -// This is `quantize_row_q8_K_ref` (ggml-quants.c L2768) transcribed, including the two things that look like -// mistakes and are not: -// -// * the scale is `-127/max`, NOT `-128/max`. The source carries the `-128` version COMMENTED OUT with the -// note that IQ2_XXS needs the change for an awkward AVX implementation. Getting this wrong is a 0.79% -// scaling error - the same order as the quantisation step, so it yields a working-looking activation that -// ggml never sees. It cost round 120. -// * `max` is the SIGNED value at the position of the largest magnitude, so a POSITIVE max gives a NEGATIVE -// iscale and the `+max` element maps to -127 while the `-max` element maps to +127. -// -// The rounding is `nearest_int`, which is round-half-to-EVEN via the 12582912.0f magic number - not -// `roundf`'s half-away-from-zero. They differ only on exact ties, i.e. almost never on real data, which is -// precisely why the wrong one would survive any amount of end-to-end testing; the parity test constructs -// exact ties on purpose. -void quantize_q8_K(const float* x, uint8_t* blocks, int64_t n, void* stream); - -// The inverse: each element becomes `d * qs[j]`, with `d = 1/iscale` stored as f32. -void dequant_q8_K(const uint8_t* blocks, float* x, int64_t n, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/rope.hpp b/include/strata/kernels/rope.hpp deleted file mode 100644 index 45e54fa..0000000 --- a/include/strata/kernels/rope.hpp +++ /dev/null @@ -1,64 +0,0 @@ -// include/strata/kernels/rope.hpp - NEOX partial RoPE, host-callable (P2.S2). -// -// Pairing is NEOX: (i, i + n_rot/2), NOT the adjacent pair (2i, 2i+1). The rotation is PARTIAL - only the -// first n_rot of head_dim are touched, 64 of 256 in this artifact - and the tail passes through. -// -// The cos/sin table is built on the HOST in float64 (see src/kernels/cuda/rope.cu for why) and the kernel is -// a pure rotation over it. The table depends on (n_rot, theta, position) and not on the token, so it is worth -// caching; `build_rope_table` fills `max_pos` positions of `n_rot/2` pairs each. -// -// ROPE SCALING RIDES IN THE TABLE, NOT IN THE KERNEL. The kernels below read cos/sin values and -// cannot tell a scaled table from an unscaled one - with scaling on, the scaled angles (and YaRN's -// mscale magnitude correction, folded into the same values) simply ARE the table. That is why -// neither `rope_neox_apply` nor the indexer's pooling kernel takes any scaling argument: the config -// enters once, here, at build time (`rope_scaling.hpp`). -#pragma once - -#include - -#include "strata/kernels/rope_scaling.hpp" - -#if defined(__CUDACC__) || defined(__HIPCC__) -#define STRATA_ROPE_HD __host__ __device__ -#else -#define STRATA_ROPE_HD -#endif - -namespace strata::kernels { - -/// ONE NEOX PAIR: `(a, b) -> (a*c - b*s, a*s + b*c)`. -/// -/// This exists so the pairing and the sign convention live in ONE place. `rope_neox_apply` walks a whole row -/// with it, and `indexer_key_append`'s pooling kernel uses it to rotate the single pooled row it has just -/// written - two call sites that MUST agree, because the indexer's key is compared against query scores -/// downstream and a mismatched rotation produces a well-formed key pointing the wrong way. -/// -/// It is `__host__ __device__` (the `f16_bits.hpp` pattern) rather than device-only so a host-side reference in -/// a test can call THE SAME function instead of transcribing it. A transcription is exactly how the pairing -/// convention gets written down wrong. -/// -/// In-place is safe: the caller writes both outputs from the two inputs it read, and under NEOX no two pairs -/// share an element (`i` pairs with `i + n_rot/2`, so the halves are disjoint). -STRATA_ROPE_HD inline void rope_neox_pair(float a, float b, float c, float s, float& oa, float& ob) { - oa = a * c - b * s; - ob = a * s + b * c; -} - -void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, float* sin_tab); - -/// The same table under the process's rope scaling (rope_scaling.hpp). For `RopeScalingType::None` -/// this IS the five-argument builder above - the parity test holds the two to be bit-identical - and -/// for linear/YaRN the scaled angles (YaRN's mscale included) replace them. The math is ggml's, -/// transcribed; see the header of `rope_scaling.hpp` for what arrives from where. -void build_rope_table(int n_rot, const RopeScaling& scaling, int max_pos, float* cos_tab, float* sin_tab); - -// `x` and `out` are (rows, head_dim) and `pos` is (rows,) - one position per row, so a batch of heads at -// different sequence positions is one call. `cos_tab`/`sin_tab` are (max_pos, n_rot/2). `out` may equal `x`. -// -// **`pos` IS A DEVICE ARRAY, NOT A HOST SCALAR**, and that is a graph-capture requirement rather than a style -// choice: a CUDA graph bakes kernel arguments in at capture time, so a host scalar position would replay the -// first token's value forever. See the same note on `indexer_key_append` in `qsa.hpp`. -void rope_neox_apply(const float* x, float* out, int64_t rows, int head_dim, int n_rot, const float* cos_tab, - const float* sin_tab, const int* pos, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/rope_scaling.hpp b/include/strata/kernels/rope_scaling.hpp deleted file mode 100644 index b494ddc..0000000 --- a/include/strata/kernels/rope_scaling.hpp +++ /dev/null @@ -1,193 +0,0 @@ -// include/strata/kernels/rope_scaling.hpp - rope scaling: extending the context past the trained one. -// -// WHAT IT IS. The artifact's RoPE is trained over `orig_ctx` positions (the artifact ships no -// `rope.scaling` keys, so this is a pure runtime feature). Scaling re-uses positions past that by -// rescaling the rotation angles. Three types, the llama.cpp set: -// -// none freq_scale 1, no correction - today's behaviour, exactly -// linear Position Interpolation: angles shrunk by 1/factor - every position fits again, all -// frequencies compressed uniformly -// yarn YaRN: high-frequency pairs keep their trained angles (extrapolate), low-frequency -// pairs are interpolated, and the pairs in between blend - plus a magnitude correction -// `mscale` that keeps the attention temperature where training put it -// -// THE MATH IS GGML'S, TRANSCRIBED, NOT RE-DERIVED. `third_party/llama.cpp` is vendored and is the -// numerical contract (the same standing `native_rope.cu` declares): ramp, correction dims, the -// interpolation mix and the mscale formula below are line-for-line that source, with the MIT -// attribution at each helper. The one deliberate deviation is bookkeeping: ggml's device kernel -// speaks in even dim indices (`i0`) and halves them inside the ramp, while every Strata rope kernel -// speaks in PAIR indices - so `rope_yarn_ramp` here takes the pair index and compares it against -// `corr_dims` directly. Same numbers, one less division per call site. -// -// HOW IT REACHES THE ROPE. Two forms, one config: -// -// - the TABLE path (the default decode path, the indexer's pooled key) never changes its kernels: -// scaling is baked into the cos/sin contents by `build_rope_table`, which the parity test checks -// bit-exactly against a float64 reference; -// - the ANALYTIC paths (`--native-rope`, the native indexer, prefill) get the resolved constants -// as kernel arguments. -// -// **PROCESS CONSTANTS, SET ONCE BEFORE CAPTURE.** A CUDA graph bakes kernel ARGUMENTS at capture -// time, so the scaling must be fixed before `session_init` captures the layers - which is exactly -// the constraint the per-token values already respect by living in device memory (`st.pos_dev`). -// `rope_scaling_set()` is called once from the engine's startup, after CLI and GGUF defaults meet, -// before any graph exists. There is deliberately no way to change it mid-process: the K already in -// the cache is stored POST-RoPE, so a mid-run change would mix two scalings in one cache. -#pragma once - -#include - -#if defined(__CUDACC__) || defined(__HIPCC__) -#define STRATA_ROPE_SCALING_HD __host__ __device__ -#else -#define STRATA_ROPE_SCALING_HD -#endif - -namespace strata::kernels { - -enum class RopeScalingType { None, Linear, YaRN }; - -/// The float32 constants the ANALYTIC rotation kernels take (`rope_scaled_angle`'s arguments). The defaults are -/// the identity: freq_scale 1, no correction, magnitude 1 - with them the helper computes `cosf(theta) * 1.0f` -/// on `1.0f * theta`, which is exactly today's unscaled `cosf(theta)` bit for bit. -struct RopeKernelArgs { - float freq_scale = 1.0f; - float corr_low = 0.0f; - float corr_high = 0.0f; - float ext_factor = 0.0f; - float attn_factor = 1.0f; -}; - -/// The one rope configuration, as the CLI flag family and the (future) GGUF rope keys resolve to. -/// -/// Default-constructed this is EXACTLY today's engine: freq_scale 1, mscale 1, no correction. That -/// identity is a regression gate, not a coincidence - the parity test compares the default's table -/// against the pre-scaling builder bit for bit. -struct RopeScaling { - RopeScalingType type = RopeScalingType::None; - double freq_base = 1e7; ///< `rope.freq_base` (the value pinned by `qsa_freq_base()`) - double factor = 1.0; ///< `--rope-scale`: how far past the trained context the run goes - double freq_scale_in = 0; ///< `--rope-freq-scale`: the raw ggml knob; 0 = 1/factor - double orig_ctx = 262144; ///< `--yarn-orig-ctx`: the context the model was trained over - double ext_factor = 0; ///< `--yarn-ext-factor`: correction depth; 0 = off, 1 = full YaRN - double attn_factor = 1.0; ///< `--yarn-attn-factor`: extra magnitude scale (ggml's attn_factor) - double beta_fast = 32.0; ///< `--yarn-beta-fast` - double beta_slow = 1.0; ///< `--yarn-beta-slow` - - /// The angle shrink. ggml's `freq_scale`: 1 means "the trained angles", 1/factor squeezes - /// `factor` positions into the trained range. - double freq_scale() const { - if (type == RopeScalingType::None) return 1.0; - return freq_scale_in > 0 ? freq_scale_in : 1.0 / factor; - } - - /// The magnitude correction. ggml's `rope_yarn` multiplies cos and sin by this; the log term - /// rides on `ext_factor != 0` (not on the type), exactly as that source has it. With the - /// default knobs YaRN factor F gives `1 + 0.1*ln(F)` - YaRN's temperature correction. - double mscale() const { - if (ext_factor == 0) return attn_factor; - return attn_factor * (1.0 + 0.1 * std::log(1.0 / freq_scale())); - } - - /// The correction window, in PAIR indices: below `out[0]` pairs extrapolate (keep the trained - /// angles), above `out[1]` they interpolate, in between they blend. Transcribed from ggml's - /// `ggml_rope_yarn_corr_dims` (see the derivation comment at `rope_yarn_corr_dim` below). - void corr_dims(int n_rot, double out[2]) const { - const double start = std::floor(rope_yarn_corr_dim(n_rot, orig_ctx, beta_fast, freq_base)); - const double end = std::ceil(rope_yarn_corr_dim(n_rot, orig_ctx, beta_slow, freq_base)); - out[0] = start < 0 ? 0 : start; - out[1] = end > (double) (n_rot - 1) ? (double) (n_rot - 1) : end; - } - - /// The analytic kernels' constants. `none` returns the identity constants WHATEVER the other knobs hold - - /// the table builder ignores them for `none` too, so the two rotation forms cannot disagree there, and an - /// unscaled run computes exactly what it computed before scaling existed. Linear/YaRN: ggml's `rope_yarn` - /// arguments (`attn_factor` is the raw knob; the helper applies the log term when correcting). - RopeKernelArgs kernel_args(int n_rot) const { - RopeKernelArgs a; - if (type == RopeScalingType::None) return a; - double cd[2]; - corr_dims(n_rot, cd); - a.freq_scale = (float) freq_scale(); - a.corr_low = (float) cd[0]; - a.corr_high = (float) cd[1]; - a.ext_factor = (float) ext_factor; - a.attn_factor = (float) attn_factor; - return a; - } - -private: - /// ggml/src/ggml.c: "Apparently solving `n_rot = 2pi * x * base^((2 * max_pos_emb) / n_dims)` - /// for x, we get `corr_dim(n_rot) = n_dims * log(max_pos_emb / (n_rot * 2pi)) / (2 * log(base))`". - /// float64 rather than ggml's float32: the table path computes in float64 and is held to a - /// bit-exact float64 reference, so its inputs are float64 too. - static double rope_yarn_corr_dim(int n_dims, double n_ctx_orig, double n_rot, double base) { - return (double) n_dims * std::log(n_ctx_orig / (n_rot * 2.0 * 3.14159265358979323846)) / - (2.0 * std::log(base)); - } -}; - -/// The ramp between extrapolation (1) and interpolation (0). -/// -/// ggml/src/ggml-cuda/rope.cu `rope_yarn_ramp`: `1 - clamp(y, 0, 1)` with -/// `y = (i0 / 2 - low) / max(0.001, high - low)`. ggml passes the even dim index `i0`; this takes -/// the pair index (ggml's `i0/2`) so Strata's pair-indexed kernels don't re-derive the mapping. The -/// 0.001 floor on the denominator is ggml's, kept verbatim: `corr_dims` can produce low == high. -STRATA_ROPE_SCALING_HD inline float rope_yarn_ramp(float low, float high, int pair) { - const float y = ((float) pair - low) / (high - low > 0.001f ? high - low : 0.001f); - const float clamped = y < 0.0f ? 0.0f : (y > 1.0f ? 1.0f : y); - return 1.0f - clamped; -} - -/// The scaled angle for one pair, float32, the ANALYTIC paths' contract (pinned ggml arithmetic). -/// -/// Takes `theta_extrap` - the position times that pair's trained `inv_freq` - and returns the angle -/// to take cos/sin of, with ggml's mscale already folded in. `mscale_in` must be `attn_factor` -/// (ggml's kernels receive the raw knob and apply the log term here, where it is per-pair constant; -/// this helper keeps that shape so the native path reads against ggml line by line). -STRATA_ROPE_SCALING_HD inline void rope_scaled_angle(float theta_extrap, float freq_scale, float corr_low, - float corr_high, float ext_factor, float mscale_in, - int pair, float& cos_out, float& sin_out) { - // The interpolation, always applied; the correction mixed in on top (ggml-cuda/rope.cu rope_yarn). - float theta = freq_scale * theta_extrap; - float mscale = mscale_in; - if (ext_factor != 0.0f) { - const float ramp_mix = rope_yarn_ramp(corr_low, corr_high, pair) * ext_factor; - theta = theta * (1.0f - ramp_mix) + theta_extrap * ramp_mix; - // "Get n-d magnitude scaling corrected for interpolation" - the log term only when correcting. - mscale *= 1.0f + 0.1f * logf(1.0f / freq_scale); - } - cos_out = cosf(theta) * mscale; - sin_out = sinf(theta) * mscale; -} - -/// The ONE validity rule for a resolved configuration, shared by the engine's startup check and every rotation -/// site that takes the struct, so a bad knob cannot pass one site and trip (or silently NaN) another. Returns -/// nullptr when the configuration is usable, else what is wrong. Every value is tested with `std::isfinite` -/// FIRST: a NaN passes every `<`/`<=` range comparison, which is how a `--rope-scale nan` would otherwise slip -/// through. `none` passes with any knob values - the knobs are inert there (the resolution resets them). -inline const char* rope_scaling_invalid(const RopeScaling& s) { - if (!std::isfinite(s.freq_base) || s.freq_base <= 1.0) return "the frequency base must be a finite value above 1"; - if (s.type == RopeScalingType::None) return nullptr; - if (!std::isfinite(s.factor) || s.factor < 1.0) return "the scaling factor must be a finite value >= 1"; - if (!std::isfinite(s.freq_scale_in) || s.freq_scale_in < 0.0) - return "the frequency scale must be finite and positive (0 = 1/factor)"; - const double fs = s.freq_scale(); - if (!std::isfinite(fs) || fs <= 0.0) return "the resolved frequency scale must be a finite positive value"; - if (!std::isfinite(s.orig_ctx) || s.orig_ctx < 1.0) return "the original (trained) context must be finite and > 0"; - if (!std::isfinite(s.ext_factor) || s.ext_factor < 0.0) return "the YaRN ext factor must be finite and >= 0"; - if (!std::isfinite(s.attn_factor) || s.attn_factor <= 0.0) return "the attention factor must be finite and > 0"; - if (!std::isfinite(s.beta_fast) || s.beta_fast <= 0.0 || !std::isfinite(s.beta_slow) || s.beta_slow <= 0.0) - return "the YaRN betas must be finite and > 0"; - if (!std::isfinite(s.mscale()) || s.mscale() <= 0.0) return "the resolved magnitude correction must be finite and > 0"; - return nullptr; -} - -/// The process's one rope configuration. Set it ONCE at startup, after the CLI and the model file -/// have agreed on the values and BEFORE `session_init` (which builds the rope table and captures the -/// graphs); read it at table build time and when launching the analytic kernels. Plain storage, no -/// atomics: one writer on the startup thread, every reader after it. -void rope_scaling_set(const RopeScaling& scaling); -const RopeScaling& rope_scaling(); - -} // namespace strata::kernels diff --git a/include/strata/kernels/router_top10.hpp b/include/strata/kernels/router_top10.hpp deleted file mode 100644 index e10295e..0000000 --- a/include/strata/kernels/router_top10.hpp +++ /dev/null @@ -1,26 +0,0 @@ -// include/strata/kernels/router_top10.hpp - the MoE router, host-callable (P2.S2). -// -// logits (n_tokens, n_expert) -> the top-k experts per token with renormalised weights. Semantics are -// `ref/moe.py::router`'s: softmax over ALL experts, stable descending argsort (ties break by index), gather, -// then renormalise with ggml's 2**-14 lower clamp. -// -// The BF16 GEMV that PRODUCES the logits is a separate kernel and is not here; this handles the routing only, -// which is why `logits` is taken as an f32 buffer the caller has already filled. -#pragma once - -#include - -namespace strata::kernels { - -// `stream` may be null, in which case the call synchronises before returning. `ids` is (n_tokens, k) int32 and -// `weights` is (n_tokens, k) f32, both device pointers. k must be <= 64. -void router_top10(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights, - void* stream); - -/// Tests (S6, HIP only): one router kernel by name - 0 the portable kernel, 1 the AMD fast kernel (the default there -/// for 64 < n_expert <= 512, k <= 32; bitwise the same results), 2 the fast kernel forced onto its serial-sum path. -/// False (nothing launched) on CUDA builds or outside that geometry. -bool router_top10_variant(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights, - void* stream, int variant); - -} // namespace strata::kernels diff --git a/include/strata/kernels/s2_expert_grouped.hpp b/include/strata/kernels/s2_expert_grouped.hpp deleted file mode 100644 index af6f52f..0000000 --- a/include/strata/kernels/s2_expert_grouped.hpp +++ /dev/null @@ -1,131 +0,0 @@ -// include/strata/kernels/s2_expert_grouped.hpp - R4's GPU expert tier. -// -// **WHAT THIS IS FOR.** The CPU expert pool is the engine's largest single cost - 663.6 MB of expert bytes per -// token at ~40 GB/s = 16.2 ms on a ~53 ms token - and `test_expert_pool` measures the pipeline hiding -// **1.055 ms of 19.035**. The CPU work is 96% exposed because the residual chain is strictly serial, so the -// only way past it is to stop reading those bytes on the CPU: put experts in VRAM and compute them on the GPU. -// -// **WHY GROUPED, AND WHY THAT WORD IS THE WHOLE DESIGN.** A layer routes ten experts. The obvious -// implementation is a loop over hits calling the per-matrix kernel, and it is wrong by arithmetic: five -// launches per expert at ~6.45 hits and 48 layers is **~1,550 launches per token**, which at a real-stream -// launch cost of ~3.6 us is 5.6 ms - most of the 10.4 ms the tier is supposed to save. So the hits are grouped -// into ONE launch per projection: -// -// 1. `gu_kernel` n_hits x 2 x FF rows - gate and up, together -// 2. `swiglu_kernel` n_hits x FF - silu(gate) * up -// 3. `quantize_q8_0` (the existing one) - the down weight's own activation contract -// 4. `down_kernel` n_hits x H rows -// -// **four launches per layer, not five per expert.** -// -// `h_layer` held-out is **0.0456** - only 4.6% of (layer, token) pairs have all ten experts resident - so this -// cannot be a per-layer grouped kernel with a fixed grid, and the hit list is passed **as data** so the caller -// can keep one captured graph per layer with the maximum grid and a device-side count. -#pragma once - -#include - -namespace strata::kernels { - -/// Bytes of caller-owned scratch `moe_hit_grouped_s2` needs for `n_hits` experts. -/// -/// Two regions: the gate/up activations (`n_hits x 2 x FF` floats) and the quantized intermediate -/// (`n_hits x (FF/32) x 34` bytes). Carved from the caller's arena rather than allocated - a `cudaMalloc` -/// on the token path is forbidden by P2.T10 and illegal during stream capture, and this is called from both. -uint64_t moe_hit_grouped_scratch_bytes(int64_t n_hits, int64_t n_embd, int64_t n_ff); - -/// **ONE GROUPED EXPERT EVALUATION.** For each hit `h` in `[0, n_hits)`, evaluates the expert held in -/// `blob_base + slot_index[h] * blob_bytes` against `x_q8_0` and writes `n_embd` floats to -/// `out + dst_index[h] * n_embd`. -/// -/// * `blob_base` the device slot arena; slot `s` starts at `blob_base + s * blob_bytes` -/// * `slot_index` `n_hits` `int32_t` slot indices on the DEVICE, so the caller can change which experts are -/// resident without recapturing anything -/// * **`dst_index` where each hit's answer goes, also on the device and also `n_hits` long.** -/// -/// **THIS IS NOT A CONVENIENCE - IT IS WHAT LETS THE TWO HALVES MEET.** A layer routes ten -/// experts and only some are resident, so the CPU produces the misses at their ROUTED indices -/// (the router's order is what `moe_combine` weights against) and the GPU produces the hits in -/// whatever order the cache happens to hold them. Writing the hits sequentially would land -/// them on the misses' rows; `dst_index` puts hit `h`'s answer on the row its expert was routed -/// to, so the CPU can zero the hit rows, the GPU can fill them, and `moe_combine` needs no -/// change at all. -/// * `x_q8_0` `(n_embd/32)` `block_q8_0`, 34 bytes each, from `quantize_q8_0` -/// * `scratch` `moe_hit_grouped_scratch_bytes(n_hits, n_embd, n_ff)`, caller-owned -/// * `out` `(k, n_embd)` floats - the SAME buffer the misses were written into -/// * **`x_scales` R4.2h, OPTIONAL, and null keeps the previous behaviour exactly.** When non-null it is -/// `n_embd/32` **fp32** activation scales from `quantize_q8_0_scaled`, and they REPLACE the -/// block's fp16 `d` as the activation multiplier - for the gate/up projection and for the -/// intermediate's own quantization in step 3. -/// -/// **THIS EXISTS BECAUSE A HIT AND A MISS MUST PRODUCE THE SAME NUMBER.** The CPU pool -/// multiplies by the fp32 `ActQ::scale` (`cpu/expert.cpp:92`); this kernel read fp16 `d` out -/// of the `block_q8_0`. `bench/micro/act_quant_parity.cu` measured the gap with both real -/// implementations linked: **80 of 80 chunks differ, max relative 4.761e-04** - 2^-11, pure -/// fp16 rounding - which is why enabling the cache changed the generated tokens. Pass null -/// and this is bit-for-bit the kernel `moe_hit_parity` has always checked at 6.279e-08. -/// -/// **THE BLOB LAYOUT IS `expert.hpp`'s AND IS NOT RESTATED HERE.** Gate/up codes are interleaved by row -/// (`2r` = gate, `2r+1` = up), the down codes follow, and each plane's scales are fp16 - which is the ONE -/// difference from `s_gemv_q8`'s S-forms, whose scales are fp32. That difference is why this is a separate -/// kernel rather than a call into the dense path. -void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index, - int64_t n_hits, int64_t blob_bytes, const uint8_t* x_q8_0, void* scratch, float* out, - void* stream, const float* x_scales = nullptr); - -/// Experimental CPU-order implementation. Eight CUDA lanes reproduce the CPU VNNI accumulator lanes, -/// fused multiply-add order, separate correction, and final horizontal reduction. The input must use -/// the CPU quantization contract and fp32 scales. SiLU uses accurate CUDA expf, which can differ from -/// the CPU math library by last bits. End-to-end correctness must be checked against the C1 oracle. -/// Validate both intermediate quantization and final outputs. -/// Optional gate_up_trace receives [all gates | all ups] before SiLU, for parity diagnostics only. -/// Plan v0.3 P4 token graph: the hit path with NO host step. `moe_hit_select` builds this layer's hit list -/// from the routed `ids` and the static residency row (`res_row[e]` = slot or -1) into `slot`/`dst`/`count` -/// (device); `moe_hit_grouped_s2_dev` is `moe_hit_grouped_s2` sized for `cap` hits that reads the real count -/// from `d_count`; `moe_hit_add` adds each hit's row of `hit_out` into `parts` (rows the CPU left at zero). -void moe_hit_select(const int32_t* ids, const int32_t* res_row, int k, int n_expert, int32_t* slot, int32_t* dst, - int32_t* count, void* stream); -void moe_hit_grouped_s2_dev(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index, - const int32_t* d_count, int64_t cap, int64_t blob_bytes, const uint8_t* x_q8_0, - void* scratch, float* out, void* stream, const float* x_scales); -void moe_hit_add(float* parts, const float* hit_out, const int32_t* dst, const int32_t* count, int64_t cap, - int64_t n_embd, void* stream); -/// Plan v0.3 P6 verify window: `moe_hit_select` over `n` <= 128 routed entries (T tokens x k, flattened), and the -/// hit kernel with one activation PER TOKEN - entry `dst` reads token `dst / k_per_token`'s rows of `x_q8_0` -/// ((n_embd/32)*34 bytes each) and `x_scales` (n_embd/32 floats each). Per hit, bitwise `moe_hit_grouped_s2_dev`. -/// Plan v0.3 P6: routed experts GROUPED. Group g's blob is at device address grp_ptr[g] (a VRAM slot, or a mapped -/// host blob the kernel reads over PCIe); its entries are [grp_start[g], grp_start[g+1]) with ent_tok (the token -/// whose activation row of x_q8_0/x_scales it reads) and ent_dst (its row of `out`). Each row of a blob is read -/// once for all of its entries. Counts are read from device memory; every entry is bitwise the per-entry kernel. -void moe_grouped_s2(const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups, - const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups, int64_t cap_entries, - const uint8_t* x_q8_0, const float* x_scales, void* scratch, float* out, void* stream); -/// Plan v0.3 P6: the groups for `moe_grouped_s2` when every expert id is resident at base + id * blob (the MTP -/// layer's 512 experts): counts[0] groups, counts[1] entries; entry dst = routing index, tok = index / k_per_tok. -void moe_group_resident(const int32_t* ids, int n, int k_per_tok, const uint8_t* base, int64_t blob, - unsigned long long* grp_ptr, int32_t* grp_start, int32_t* counts, int32_t* ent_dst, - int32_t* ent_tok, void* stream); -void moe_hit_select_multi(const int32_t* ids, const int32_t* res_row, int n, int n_expert, int32_t* slot, int32_t* dst, - int32_t* count, void* stream); -void moe_hit_grouped_s2_multi(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index, - const int32_t* d_count, int64_t cap, int64_t blob_bytes, const uint8_t* x_q8_0, - const float* x_scales, int k_per_token, void* scratch, float* out, void* stream); -/// The per-hit kernels (`moe_hit_grouped_s2`, `_dev`, `_multi`) and the grouped ones (`moe_grouped_s2`) -/// were rewritten with bitwise-identical outputs: conflict-free staged activations, `hx` once per chunk, wide loads, -/// two rows per warp. The previous kernels stay for A/B: `STRATA_OLD_GROUPED=1` in the environment selects them, -/// and so does `moe_grouped_select_old(1)`; `0` forces the new ones, `-1` returns to the environment. The environment -/// variable is read once, on first use; the kernel choice is made at each launch (so a captured graph keeps the -/// kernels chosen at capture). Use `moe_grouped_select_old` to switch at runtime. `STRATA_GROUPED_PAIR_MIN_HITS=N` -/// (read once too) keeps the previous per-hit kernels below N hits of capacity; a forced choice overrides it. The -/// new kernels also need 4-byte aligned activations and scratch, and the per-hit ones an 8-byte aligned arena and -/// slot size; otherwise the previous kernels run. -void moe_grouped_select_old(int old); -/// Which kernels the last call of the entry points above launched: 1 = new, 0 = previous, -1 = none since the -/// previous query (the query clears it). For the parity test, which must know the path it compared was taken. -int moe_grouped_last_path(); -void moe_hit_grouped_s2_cpu_order(const uint8_t* blob_base, const int32_t* slot_index, - const int32_t* dst_index, int64_t n_hits, int64_t blob_bytes, - const uint8_t* x_q8_0, void* scratch, float* out, void* stream, - const float* x_scales, float* gate_up_trace = nullptr); - -} // namespace strata::kernels diff --git a/include/strata/kernels/s2_gemv.hpp b/include/strata/kernels/s2_gemv.hpp deleted file mode 100644 index a09b822..0000000 --- a/include/strata/kernels/s2_gemv.hpp +++ /dev/null @@ -1,25 +0,0 @@ -// include/strata/kernels/s2_gemv.hpp - the S2 GEMV, host-callable (P2.S2). -// -// The expert matvec is the hottest thing in the engine: every token runs 48 layers x 10 experts x 3 roles of -// it, against weights that live in DRAM at 31.64 GiB. Layout is `docs/pack-format.md`'s S2: codes packed 4 -// per byte LSB-first, one FP32 scale per 64 elements. GGUF's ne[0] varies fastest, so a tensor is [n_in, -// n_out] with n_in CONTIGUOUS - which is why one thread per output row reads a contiguous run of blocks. -// -// Activations are FP16 per the phase spec ("FP16 activations in"). The OUTPUT here is FP32 rather than FP16: -// the intended FP16 out needs an f32->fp16 conversion, and rather than write one under a parity test that -// would then be testing two new things at once, this step keeps the output width the one that can be checked -// exactly. The FP16 output and its 1e-3 tolerance is the next increment, and this file says so rather than -// leaving a reader to wonder. -#pragma once - -#include - -namespace strata::kernels { - -// y[o] = sum_i fp16(x[i]) * W[i][o], with W in S2 canonical planes. -// `codes` is n_out * (n_in/64) * 16 bytes, `scales` n_out * (n_in/64) floats, `x` n_in uint16 fp16 patterns, -// `y` n_out floats. All device pointers. n_in must be a multiple of 64. -void s2_gemv(const uint16_t* x, const uint8_t* codes, const float* scales, float* y, int64_t n_in, - int64_t n_out); - -} // namespace strata::kernels diff --git a/include/strata/kernels/s2_gemv_q8.hpp b/include/strata/kernels/s2_gemv_q8.hpp deleted file mode 100644 index 9c7beb9..0000000 --- a/include/strata/kernels/s2_gemv_q8.hpp +++ /dev/null @@ -1,22 +0,0 @@ -// include/strata/kernels/s2_gemv_q8.hpp - the S2 GEMV over Q8_0-QUANTIZED activations. -// -// `ggml_mul_mat` converts src1 to the weight's `vec_dot_type`, which for Q2_0 is Q8_0. The other CUDA kernels -// here take FP16 activations, and the CPU expert path already quantizes to int8 - so this is the missing GPU -// half of the same rule, and without it the two paths disagree on the same token. -// -// CORRECTNESS VERSION: the activation is dequantized inside the loop. The speed win here is `__dp4a` (four -// int8 MACs per instruction) and belongs to Phase 3, once the numerics are settled. -#pragma once - -#include - -namespace strata::kernels { - -// `act` (n_in/32) ggml Q8_0 blocks, 34 bytes each, as `quantize_q8_0` produces -// `codes` n_out * (n_in/4) bytes, one 2-bit code byte per quad -// `scales` n_out * (n_in/64) -// `y` n_out floats -void s2_gemv_q8(const uint8_t* act, const uint8_t* codes, const float* scales, float* y, int64_t n_in, - int64_t n_out, int threads_per_row, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/s_gemv.hpp b/include/strata/kernels/s_gemv.hpp deleted file mode 100644 index 340df04..0000000 --- a/include/strata/kernels/s_gemv.hpp +++ /dev/null @@ -1,133 +0,0 @@ -// include/strata/kernels/s_gemv.hpp - the S-family GEMV, host-callable (P2.S2). -// -// ONE kernel for S2, S4 and S8, because `docs/pack-format.md` gives them ONE decode: -// -// value = cb[code] * scale + offset -// -// with a per-TYPE codebook, code bias, group size and offset presence. That uniformity is the point of the -// canonical form - 13 source types collapse to three code widths and a handful of attributes - so the kernel -// takes those attributes as ARGUMENTS rather than being specialised per source type. The manifest already -// carries them per tensor (round 163 added the tests that keep it honest). -#pragma once - -#include - -namespace strata::kernels { - -// Which table turns a code into a number. `Affine` is `code + bias`; `Iq4Nl` is the non-linear -// `kvalues_iq4nl`, which no bias can express - the reason the canonical form carries a codebook at all. -enum class Codebook : int { Affine = 0, Iq4Nl = 1 }; - -struct SForm { - int code_bits = 2; // 2, 4 or 8 - int code_bias = -1; // subtracted from the code IN THE INTEGER DOMAIN before the multiply - int group_elems = 64; // elements per scale (and per offset, when present) - Codebook codebook = Codebook::Affine; - bool has_offset = false; // only the K-quants with a min (Q4_K, Q5_K) have one - - /// WHICH ACTIVATION THIS WEIGHT'S `vec_dot_type` IS: 0 = Q8_0, 1 = Q8_K. - /// - /// **IT IS AN ATTRIBUTE OF THE CANONICAL FORM AND IT CANNOT BE DERIVED FROM THE OTHERS.** Q5_0 and Q5_K - /// are both 8-bit with bias -16 (only `has_offset` differs); IQ4_NL and IQ4_XS are both 4-bit with the - /// IQ4NL codebook and no offset, and differ in NOTHING this struct otherwise holds. So it is CARRIED from - /// the manifest's `source_type` rather than reconstructed - see `docs/activation-contract.md` and the - /// `act_kind` column `tools/pack_index.py` writes. - int act_kind = 0; -}; - -// y[o] = sum_i fp16(x[i]) * W[i][o]. GGUF's ne[0] varies fastest, so a tensor is [n_in, n_out] with n_in -// CONTIGUOUS: row o is a contiguous run of n_in/group_elems groups. -// -// `codes` n_out * (n_in / (8/code_bits)) bytes -// `scales` n_out * (n_in / group_elems) floats -// `offset` the same count as scales, or nullptr when `has_offset` is false -// `y` n_out floats -void s_gemv(const uint16_t* x, const uint8_t* codes, const float* scales, const float* offset, float* y, - int64_t n_in, int64_t n_out, const SForm& form); - -// The same computation with the ROW SPLIT ACROSS THREADS: one block of `threads_per_row` threads per output -// row, each accumulating a strided subset, reduced through shared memory. -// -// WHY BOTH EXIST. `s_gemv` gives one thread per output row, so its parallelism is the OUTPUT WIDTH - and the -// expert gate/up shape is [2560 x 640], which is 640 threads over 48 SMs, 13 per SM. Measured, that -// orientation ran 4.6x slower than [640 x 2560] with identical weights (Memory/LEDGER.md L1). This variant -// makes the parallelism independent of the output width. -// -// It is NOT bit-identical to `s_gemv`: the partial sums are added in a different order, so the parity test -// carries a tolerance for exactly this reason. Both are kept and both are tested, because the naive one is -// the reference the split one is checked against. -void s_gemv_split(const uint16_t* x, const uint8_t* codes, const float* scales, const float* offset, - float* y, int64_t n_in, int64_t n_out, const SForm& form, int threads_per_row); - -// S2 ONLY, with the code load amortised over four consecutive elements (they share one byte) and the -// activation load over four halves (one 64-bit word). S2 is 31.64 GiB of the 38 GiB pack, so it is the kernel -// whose instruction count matters. No `offset` - S2 has none, and a parameter that is always null is a -// parameter that will eventually be passed by mistake. -void s2_gemv_quads(const uint16_t* x, const uint8_t* codes, const float* scales, float* y, int64_t n_in, - int64_t n_out, int threads_per_row); - -// S2 with two further instruction reductions: `x` staged in SHARED memory once per block instead of re-read -// from global by every output row, and the code unpack replaced by a 256-entry constant-memory table of -// float4 (one broadcast load per four elements instead of shifts, masks and an int-to-float convert). -// `stage_x` selects the staging so the two can be measured against each other rather than assumed. -void s2_gemv_fast(const uint16_t* x, const uint8_t* codes, const float* scales, float* y, int64_t n_in, - int64_t n_out, int threads_per_row, bool stage_x); - -// The same computation as `s_gemv_split` but launched on `stream` (a cudaStream_t passed as void*, so this -// header stays free of CUDA types) and WITHOUT synchronising. It exists because the architecture's premise - -// that the expert stream overlaps with the compute that consumes it - cannot be measured through an entry -// point that waits for every stream. The synchronous ones remain the default; this is for the loop that has -// to overlap, and for the test that establishes whether overlapping is worth building. -void s_gemv_split_async(const uint16_t* x, const uint8_t* codes, const float* scales, const float* offset, - float* y, int64_t n_in, int64_t n_out, const SForm& form, int threads_per_row, - void* stream); - -/// THE SAME GEMV OVER **Q8_K** ACTIVATIONS, which is the contract for every K-quant and IQ-quant weight. -/// -/// `docs/activation-contract.md` settles this: `ggml_mul_mat` converts the activation to the weight's -/// `vec_dot_type`, and for Q3_K/Q4_K/Q5_K/Q6_K/IQ4_XS that type is Q8_K - NOT fp16. The two differ by -/// 0.6-0.9% per GEMV against a 1e-3 tolerance, and the K-quants are 2.89 GiB of the dense weights: the -/// attention projections and `ssm_out`, i.e. the numerically sensitive ones. -/// -/// `x` is the block_q8_K layout, 292 bytes per 256 elements: `{ f32 d ; int8_t qs[256] ; int16_t bsums[16] }`. -/// `bsums` is NOT read here - it exists for ggml's AVX2 path - but the STRIDE includes it, so a buffer -/// produced by `quantize_q8_K` can be passed straight in. -/// -/// The activation is dequantized on the fly (`d * qs[i]`), one multiply per element, exactly as the fp16 path -/// does one `__half2float` per element. The weight decode is the SAME code as `s_gemv` - one implementation, -/// because a second decode of the canonical form is a second thing to get wrong. -void s_gemv_q8k(const uint8_t* x_q8k, const uint8_t* codes, const float* scales, const float* offset, - float* y, int64_t n_in, int64_t n_out, const SForm& form, void* stream); - -/// The row-split form, for output widths too small to fill the machine. -/// -/// **THERE IS NO `threads_per_row` HERE, AND THAT IS A FIX RATHER THAN AN OVERSIGHT.** The parameter used to be -/// in this signature and the implementation threw it away - `(void) threads_per_row; // informational` - so a -/// caller reading the declaration reasonably believed it was tunable, and round 224 spent a whole sweep -/// measuring it and concluding from the flat result that the kernel was instruction-bound. The sweep could not -/// have shown anything else: **it was measuring a knob that is not connected.** -/// -/// This form is WARP per output row, which is what the shape wants, and the parameter is gone from the -/// interface so that no one can believe otherwise. `s_gemv_split`/`s_gemv_split_async` DO take threads_per_row -/// and DO use it, if a caller wants to tune that shape. -void s_gemv_q8k_split(const uint8_t* x_q8k, const uint8_t* codes, const float* scales, const float* offset, - float* y, int64_t n_in, int64_t n_out, const SForm& form, void* stream); - -/// THE SAME, OVER A **Q8_0** ACTIVATION - `block_q8_0`, 34 bytes per 32 elements, from `quantize_q8_0`. -/// -/// **THIS IS THE KERNEL THAT WAS MISSING, AND ITS ABSENCE WAS DESCRIBED INCORRECTLY FOR SEVERAL ROUNDS.** The -/// legacy block formats (Q2_0, Q4_0, Q5_0, Q8_0, IQ4_NL) have `vec_dot_type` Q8_0, not Q8_K. Every one of them -/// in this pack except `ffn_down_shexp` is `Q2_0`, whose attributes happen to BE S2's (2 bits, group 64, -/// bias -1) - so `s2_gemv_q8`, which hardcodes those, covered them by coincidence. `ffn_down_shexp` is -/// IQ4_NL/Q4_0/Q5_0/Q8_0 in every layer with **group 32 and bias -16/0/-8**, and its `n_in` is **640**. -/// -/// 640 is a multiple of 32 and NOT of 256, so **Q8_K is structurally impossible for it rather than merely -/// unimplemented** - which is what the "Q8_K is not implemented" note in `shared_expert.hpp` was really -/// pointing at. -/// -/// `n_in` must be a multiple of 32. `group_elems` must be a power of two and a multiple of four, the same two -/// requirements `s_gemv_q8k_split` has and for the same reasons. -void s_gemv_q8_0_split(const uint8_t* x_q8_0, const uint8_t* codes, const float* scales, const float* offset, - float* y, int64_t n_in, int64_t n_out, const SForm& form, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/sampler.hpp b/include/strata/kernels/sampler.hpp deleted file mode 100644 index a740101..0000000 --- a/include/strata/kernels/sampler.hpp +++ /dev/null @@ -1,86 +0,0 @@ -// include/strata/kernels/sampler.hpp - the sampler chain, host-callable (P2.S2). -// -// penalties -> top_k -> top_p -> min_p -> temperature -> pick -// -// llama.cpp's default chain (issue #53): ONE penalties stage, first, and temperature AFTER the truncation filters; -// top_p cuts before min_p. `src/kernels/cuda/sampler.cu` has the details and `sampler_parity` pins them. -#pragma once - -#include -#include -#include - -namespace strata::kernels { - -struct SamplerParams { - int top_k = 20; // sampled path: 1..64 as given; 0 (off) or more than 64 keep the widest list, 64 - float top_p = 0.95f; // 1.0 disables the filter - float min_p = 0.0f; // 0 disables; keeps tokens with p >= min_p * p_max (a prefix of the top_k list) - float temperature = 1.0f; // <= 0 means greedy - int min_keep = 1; // top_p keeps at least this many - int penalty_last_n = 0; // 0 disables; the window over `history` to count occurrences in - float penalty_repeat = 1.0f; - float penalty_freq = 0.0f; - float penalty_present = 0.0f; - uint64_t seed = 0; // drives Philox, which is counter-based on (seed, token index) - uint64_t counter = 0; // absolute draw index of row 0; advance across decode calls - bool greedy = false; -}; - -// logits (n_tokens, n_vocab) -> one sampled token id per row in `out`. -// -// **`logits` AND `out` ARE DEVICE POINTERS.** This is a CUDA kernel launch, not a host function, and nothing -// in the parameter names or the types says so - `const float* logits` reads exactly like a host buffer. -// Measured: passing host memory for `logits` faults inside the kernel with an ILLEGAL MEMORY ACCESS that is -// reported by whatever synchronising call happens NEXT, which will be somewhere else entirely and will name a -// buffer that has nothing to do with it. A sticky async fault does not know where it came from. -// -// `history` is (n_tokens, history_len) int32 - ONE ROW PER TOKEN ROW, at a stride of `history_len` - the most -// recent tokens that row's pick follows, with any unused slots set to -1; only the last `p.penalty_last_n` of -// each row are counted, and ids outside [0, n_vocab) are ignored. Pass nullptr and 0 when no penalties apply. -// A verify window's rows need DIFFERENT histories: row t follows the window's drafts 1..t (`penalty_rows`). -void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len, - const SamplerParams& p, int* out, void* stream); - -// The greedy pick (no penalties) on a thread-block cluster of 8 CTAs per row (sm_90+, CUDA; S19): the same token as -// sample_tokens' one-block argmax, which takes it unless STRATA_ARGMAX_MULTI=0. False (nothing launched) where it -// cannot run: HIP, a card or a build below sm_90. Device pointers; capturable. -bool sample_greedy_cluster(const float* logits, int n_tokens, int n_vocab, int* out, void* stream); - -// ---- COUPLED DRAFT SAMPLING (include/strata/core/coupled_draft.hpp, STRATA_SPEC_COUPLED=1). Device pointers -// throughout; every per-request / per-round value comes from device memory, so the calls can be captured. -// -// The scratch `coupled_draft_sample` needs for `nv` logits (0: too wide for the split merge, coupled cannot run). -size_t coupled_draft_scratch_bytes(int nv); -// A round's inputs: `*params` <- `*mapped_params`, ring[cap - h, cap) <- mapped_hist[cap - h, cap) with h = -// coupled_hist_len(penalty_last_n, cap). `mapped_*` are mapped host memory. -void coupled_draft_stage(const SamplerParams* mapped_params, const int32_t* mapped_hist, SamplerParams* params, - int32_t* ring, int cap, void* stream); -// Draft j of the chain from ONE row of `nv` logits (modified in place: the penalties): the target's chain with -// `*params`, the penalty window ring[cap + j - h, cap + j), Philox counter coupled_draft_counter(step_rec[0]). -// `sub_to_id` / `id_to_sub` map the draft head's subset to token ids and back (null: the whole vocabulary, -// `id_vocab` ids). Writes the token id to *out_id, its probability under the final distribution to *out_prob, and -// the id to ring[cap + j]. -void coupled_draft_sample(float* logits, int nv, const int32_t* sub_to_id, const int32_t* id_to_sub, int id_vocab, - const SamplerParams* params, int32_t* ring, int cap, int j, const int32_t* step_rec, - void* scratch, int32_t* out_id, float* out_prob, void* stream); - -// The penalty-history rows of a verify window, on the host: row t of `out` (T rows of `h` slots) is the last `h` -// tokens of `tail[0..n_tail)` followed by `window[0..t]`, most recent LAST, -1 in the unused front slots. -// `tail` is what the state consumed before the window, `window[0]` the fed-back token and `window[1..]` the -// drafts: row t is exactly the history plain decode counts when it picks the token after `window[t]`, so drafting -// cannot change which tokens are penalised. Row 0 alone is the single row the engine staged before 0.1.19. -inline void penalty_rows(const int32_t* tail, int64_t n_tail, const int32_t* window, int T, int h, int32_t* out) { - for (int t = 0; t < T; ++t) { - int32_t* row = out + (size_t) t * (size_t) h; - const int64_t avail = n_tail + t + 1; // tail + window[0..t] - const int take = (int) std::min(h, avail); - std::fill(row, row + (h - take), -1); - for (int j = 0; j < take; ++j) { - const int64_t i = avail - take + j; // index into (tail, window) - row[h - take + j] = i < n_tail ? tail[i] : window[i - n_tail]; - } - } -} - -} // namespace strata::kernels diff --git a/include/strata/kernels/shared_expert.hpp b/include/strata/kernels/shared_expert.hpp deleted file mode 100644 index 44b37d8..0000000 --- a/include/strata/kernels/shared_expert.hpp +++ /dev/null @@ -1,103 +0,0 @@ -// include/strata/kernels/shared_expert.hpp - the shared expert, host-callable (P2.S2). -// -// h = silu(x @ gate_shexp.T) * (x @ up_shexp.T) <- SILU ON GATE -// h = h @ down_shexp.T -// g = sigmoid(x @ gate_inp_shexp) one SCALAR per token -// return h * g[:, None] -// -// The result is ADDED to the routed output, not weighted against it. Shape note: `n_ff` for the shared expert -// matches the routed experts' width (640) in this artifact. -// -// The SForm arguments describe canonical planes for the three expert projections and their historical -// CPU-derived activation images (Q8_0 or Q8_K). The default scalar gate separately consumes BF16 activations. -// The opt-in native BF16 gate instead consumes the original F32 activation and uses the pinned CUDA MMVF -// contract. Optional native projection weights select the pinned CUDA Q8_1 MMVQ contract independently. -#pragma once - -#include - -#include "strata/kernels/s_gemv.hpp" - -namespace strata::kernels { - -/// Opt in to pinned CUDA BF16/F32 MMVF and FP32 sigmoid for the shared scalar gate (default false). -/// Configure before session capture; captured graphs retain their selected kernels. -/// In this mode shared_expert requires its optional unrounded x_f32 input. -void shared_expert_set_native_bf16(bool enabled); -bool shared_expert_native_bf16_enabled(); - -/// Optional native GGUF projections. Each supported type with nonnull data -/// replaces only that canonical projection; absent or unsupported entries fall -/// back independently. Any active entry selects pinned FP32 SwiGLU arithmetic. -/// Caller owns device weights and Q8_1 scratch for the largest active input -/// (n_embd for gate/up, n_ff for down), sized by native_q8_1_bytes. All storage -/// must survive graph execution; use one ordered nonnull stream with no overlap. -struct NativeSharedWeights { - int gate_type = -1, up_type = -1, down_type = -1; - const void* gate_data = nullptr; - const void* up_data = nullptr; - const void* down_data = nullptr; - void* q8_1 = nullptr; - const void* x_q8_1 = nullptr; // optional pre-quantized Q8_1 input for gate/up in shared_expert_multi -}; - -/// Bytes of caller-owned scratch `shared_expert` needs. **THE KERNEL USED TO `cudaMalloc` FOUR BUFFERS ON -/// EVERY CALL**, which is two separate violations in one line: `cudaMalloc` is ILLEGAL INSIDE A CAPTURE -/// (`cudaErrorStreamCaptureUnsupported`), so the MoE - and therefore the whole per-layer graph - could not be -/// captured at all; and P2.T10 requires ZERO token-path allocations, which this was. Neither is visible in a -/// test that only checks the output, and the capture test found it in one run. -uint64_t shared_expert_scratch_bytes(int64_t n_ff); - -/// `x_q8_0` and `x_q8k` are the TWO QUANTIZED IMAGES of the same activation, and which one a projection uses is -/// decided per weight by its `SForm::act_kind`. There is no fp16 activation here any more. -/// -/// **THE fp16 PATH WAS A REAL ERROR AND IT WAS DESCRIBED WRONG FOR SEVERAL ROUNDS.** This header used to say -/// the weights "are Q3_K / IQ4_XS / Q5_0 whose `vec_dot_type` is Q8_K, which is not implemented". In fact -/// `ffn_down_shexp` is IQ4_NL/Q4_0/Q5_0/Q8_0/Q2_0 in every layer - **no K-quant at all** - so its contract is -/// Q8_0; and its `n_in` is 640, which is not a multiple of 256, so **Q8_K is structurally impossible for it**. -/// The gate/up weights are Q2_0 on 21 and 13 layers (Q8_0 again) and K-quants on the rest. -/// -/// x_f32 is required for the native BF16 gate or native gate/up projections. -/// Native down reads the unrounded F32 SwiGLU intermediate directly. No allocation occurs. -/// -/// Measured cost of the wrong choice: 0.66-1.41% per GEMV. `s_gemv_q8_0_split` was written for the Q8_0 half -/// (LEDGER L55) and `s2_gemv_q8` already served the Q2_0 half. -void shared_expert(const uint8_t* x_q8_0, const uint8_t* x_q8k, const uint16_t* x_bf16, const SForm& gate_form, - const uint8_t* gate_codes, const float* gate_scales, const float* gate_off, - const SForm& up_form, const uint8_t* up_codes, const float* up_scales, const float* up_off, - const SForm& down_form, const uint8_t* down_codes, const float* down_scales, - const float* down_off, const uint16_t* gate_inp_bf16, float* scratch, float* out, - int64_t n_embd, int64_t n_ff, int tpr, void* stream, const float* x_f32 = nullptr, - const NativeSharedWeights* native = nullptr); - -/// Plan v0.3 P6: the shared expert for `n_tok` <= 8 tokens (a verify window) with all three projections native: -/// multi-column MMVQ, so the weights are read once; every token is bitwise `shared_expert` on that token. -/// `x` (n_tok, n_embd) f32, `x_bf16` the same rounded (only read when the native BF16 gate is off), `gate`/`up` -/// (n_tok, n_ff) scratch, `g` n_tok floats, `out` (n_tok, n_embd). `nw.q8_1` must hold n_tok columns of n_embd. -void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, const NativeSharedWeights& nw, - const uint16_t* gate_inp_bf16, float* gate, float* up, float* g, float* out, int64_t n_embd, - int64_t n_ff, void* stream); - -/// The MoE block's final combination, `ref/moe.py::moe` L156: -/// -/// y = sum over the k routed experts of w[k] * parts[k] + shared -/// -/// `parts` is (k, n_embd) contiguous - one row per SELECTED expert, in the router's own order - and `shared` -/// may be null for a layer with no shared expert. -/// -/// TWO THINGS A READER GETS WRONG HERE, and they are why this is not inlined at the call site: -/// -/// * The ROUTED outputs are router-WEIGHTED; the SHARED output is ADDED PLAIN. `ref/moe.py` L116 says so -/// outright - "router-weighted, not renormalised against it" - and weighting the shared term too is a -/// one-line change that produces a plausible number. -/// * The weights come from `router_top10` ALREADY renormalised (they sum to 1 over the selected experts). -/// Normalising again here would be a second, different normalisation, and it is invisible whenever the -/// router's weights happen to sum near 1 anyway. -/// -/// One thread per output element, k accumulations each; k is 10 at the real geometry. This is where the CPU -/// expert pool's outputs are summed: `ExpertPool` carries a `weight` per job and deliberately does NOT apply -/// it, because the sum has to happen once over all k and not once per worker. -void moe_combine(const float* parts, const float* weights, const float* shared, float* y, int64_t n_embd, - int64_t k, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/kernels/verify_kernels.hpp b/include/strata/kernels/verify_kernels.hpp deleted file mode 100644 index d54c331..0000000 --- a/include/strata/kernels/verify_kernels.hpp +++ /dev/null @@ -1,101 +0,0 @@ -// include/strata/kernels/verify_kernels.hpp - plan v0.3 P6: kernels for the speculative VERIFY window, where T -// tokens (the last accepted token and T-1 drafts) go through a layer at once. -// -// The GDN recurrence is the one piece of state that cannot simply be overwritten by the next window, so its -// kernels come in two halves: -// -// * the verify half reads the conv history and the recurrent state, runs all T tokens in order (bitwise the -// single-token kernels' arithmetic per token) and writes ONLY the per-token outputs - the state is left -// untouched; -// * the commit half, launched once acceptance is known, replays the first `n_keep` tokens from the inputs the -// verify half stored and writes the state. Rejected tokens therefore never touch the state and there is no -// snapshot of the 113 MB recurrent state to keep. -// -// 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 - -namespace strata::kernels { - -inline constexpr int kVerifyMaxT = 8; - -/// For token t of T: conv over [history(3) | qkv_0 .. qkv_t] -> SiLU -> L2 norm of the q/k heads -> h[t]. -/// `history` is NOT written. Bitwise `fused_gdn_conv_l2` per token. -void gdn_conv_l2_multi(const float* history, const float* qkv, const float* conv_w, float* h, int channels, - int qk_heads, float eps, int n_tok, void* stream, int t_begin = 0); -/// history <- the last 3 entries of [history | qkv_0 .. qkv_{n-1}], n = *n_keep (0 leaves it as it was). -void gdn_conv_commit(float* history, const float* qkv, int channels, const int32_t* n_keep, void* stream); -/// alpha/beta for T columns of x (T, n_embd): gate (T, h_v), beta (T, h_v). Bitwise `fused_gdn_ab` per column. -void gdn_ab_multi(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, int n_tok, void* stream); -/// The recurrence + output norm for T tokens (h = (T, conv_channels) as q|k|v, gate/beta (T, h_v), z/y -/// (T, value_dim)). With `n_keep == nullptr` the state is read and NOT written (verify); otherwise the first -/// *n_keep tokens are run and the state is written (commit; `y` may be scratch). Bitwise `fused_gdn_step_norm`, -/// including its output gate `act` (sigmoid for Flash-Next, SiLU for Qwen3.6: `GdnGate`). -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); -/// 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). -void wait_flag_ge(const uint32_t* flag, uint32_t value, void* stream); -/// the GPU's %globaltimer (ns) into buf[i] (a one-thread kernel: the verify window's stage profiler). -void gpu_stamp(unsigned long long* buf, int i, void* stream); - -// ---- perf-review E-6: a layer whose routed experts are all in VRAM needs nothing from the host -/// One group's plan, built on the device when every routed expert of its n*k entries is resident: the host pool's -/// layout (counts | start | dst | tok | pad | ptr | ptr2 | start2, `capx` entries) and order (distinct experts in -/// routing order, their entries ascending), no PCIe groups. *skip = ring when it did, else 0. -void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_layer, int n_expert, - const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan, - long long capx, uint32_t* skip, uint32_t ring, void* stream); -/// wait_flag_ge that also returns when *skip == value (device memory). -void wait_flag_ge_or(const uint32_t* flag, uint32_t value, const uint32_t* skip, void* stream); -/// copy_i32_from_mapped unless *skip == value. -void copy_i32_from_mapped_unless(int32_t* dst, const int32_t* src, long long n, const uint32_t* skip, uint32_t value, - void* stream); -/// copy_from_mapped, or zeros when *skip == value (n a multiple of 4, 16-byte aligned). -void copy_or_zero_from_mapped(float* dst, const float* src, long long n, const uint32_t* skip, uint32_t value, - void* stream); - -/// Rows of the S2/S4/S8 embedding for T token ids read from DEVICE memory; out (T, n). Bitwise `embedding_gather`. -void embedding_gather_dev(const uint8_t* codes, const float* scales, const float* offsets, const int32_t* tokens, - int n_tok, int64_t n, int code_bits, int code_bias, int group_elems, uint64_t row_codes, - uint64_t row_groups, float* out, void* stream); -/// R[t][c][:] = x[t][:] for the hc streams. -void broadcast_streams(const float* x, float* R, int64_t n_embd, int hc, int n_tok, void* stream); -/// dst[:n] = src[(*index) * stride + :n] (index read from device memory; a negative index copies nothing). -void copy_indexed(float* dst, const float* src, int64_t stride, const int32_t* index, int64_t n, void* stream); - -/// Plan v0.3 P6: copy *n (device memory) blobs of `blob_bytes` from mapped host memory (src[k], device aliases) -/// into dst + k * blob_bytes with coalesced 16-byte loads - the PCIe share of a layer's missed experts, staged -/// into VRAM before the grouped expert kernel reads them. Launched for a capacity of `cap` blobs. -void fetch_blobs(const unsigned long long* src, const int32_t* n, uint8_t* dst, int64_t blob_bytes, int cap, void* stream); -/// ptr[k] = base + k * blob_bytes for k < *n (the staged copies `fetch_blobs` made). -void rebase_ptrs(unsigned long long* ptr, const int32_t* n, uint8_t* base, int64_t blob_bytes, void* stream); - -// ---- the MTP draft layer (src/core/mtp.cpp) -/// R[t][c][:] = h[t][c][:] + e[t][:] (the embedding branch added to every stream). -void add_streams_broadcast(const float* h, const float* e, float* R, int64_t n_embd, int hc, int n_tok, void* stream); -/// Every routed expert is resident (slot = expert id): slot[i] = ids[i], dst[i] = i, *count = n. -void ident_hits(const int32_t* ids, int n, int32_t* slot, int32_t* dst, int32_t* count, void* stream); -/// The draft chain's next input: R_dst[:] = R_src[row], tok_dst[0] = ids[row], out[j] = ids[row], with -/// row = *row_dev (device memory). `out` may be mapped host memory. -void mtp_select(const float* R_src, int64_t R_stride, const int32_t* ids, const int32_t* row_dev, float* R_dst, - int32_t* tok_dst, int32_t* out, int j, void* stream, const float* probs = nullptr, - float* out_p = nullptr); -/// dst row i = src row ids[i] (row_bytes each, multiple of 16), for n rows. -void gather_rows(const uint8_t* src, int64_t row_bytes, const int32_t* ids, int64_t n, uint8_t* dst, void* stream); -/// ids[t] = table[ids[t]] for n entries (a subset index back to a token id). -void map_ids(int32_t* ids, const int32_t* table, int n, void* stream); -/// probs[t] = softmax(logits[t])[ids[t]] for n_rows rows of n_vocab (the probability of each row's argmax). -void row_top_prob(const float* logits, int n_rows, int n_vocab, const int32_t* ids, float* probs, void* stream); -/// Dense-attention step records for `n` cells: [cell, cell+1, (cell+1)/4, cell+1] from cells[i] (device memory). -void dense_steps(const int32_t* cells, int n, int32_t* steps, void* stream); -/// A sliding attention window: for `n` step records (kStepCount ints each, n_kv at [1]) the selection becomes the -/// last `window` cells: ids[q * ids_stride + j] = max(0, n_kv - window) + j and the record's width = the count. -void window_ids(int32_t* steps, int n, int window, int32_t* ids, int64_t ids_stride, void* stream); - -} // namespace strata::kernels diff --git a/include/strata/ngram/ple_reader.hpp b/include/strata/ngram/ple_reader.hpp deleted file mode 100644 index 2884817..0000000 --- a/include/strata/ngram/ple_reader.hpp +++ /dev/null @@ -1,100 +0,0 @@ -// include/strata/ngram/ple_reader.hpp - plan v0.3 P2: the n-gram table read straight from the SSD. -// -// The table is 320,001,536 rows of 90 bytes (IQ4_NL, 26.8 GiB) or 160 (FP8 E4M3, 51.2 GB) and is never held in RAM: every row comes from an -// unbuffered 4 KiB read (platform::DirectFile). A token needs 16 rows on 16 different pages, and all 16 depend -// on the token itself, so the only time to hide them is the embedding plus layer 0. Hence the split API: -// -// Ticket t = reader.issue(rows, n, out_raw); // as soon as the token id is known -// ... // embedding, layer 0 -// reader.collect(t); // before layer 1 reads the rows -// -// `issue` also serves prefill: pass all 16 x N rows of a chunk; pages are deduplicated, sorted by offset and -// kept at most `max_inflight` deep, so a chunk's reads can run while the previous chunk computes. -// -// THE ROW CACHE IS NOT THE TABLE. It keeps rows this process has already fetched (90 bytes each, bounded, -// clock eviction). Measured on the frozen corpus (bench/results/2026-09-23-ngram-io): 1M rows (~95 MB) -// would serve up to ~82% of reads; within one long prompt 20-34% of rows recur. Capacity 0 disables it. -#pragma once - -#include "strata/platform/direct_file.hpp" - -#include -#include -#include - -namespace strata::ngram { - -inline constexpr uint32_t ROW_BYTES = 90; ///< an IQ4_NL row; `open` takes the table's own size -inline constexpr uint32_t PAGE = 4096; - -struct ReaderStats { - uint64_t requests = 0; ///< rows asked for - uint64_t cache_hits = 0; ///< rows served from the row cache - uint64_t dedup_rows = 0; ///< rows that shared a page already being read in the same ticket - uint64_t reads = 0; ///< SSD read requests issued - uint64_t bytes = 0; ///< bytes read from the SSD - double wait_us = 0; ///< time `collect` spent blocked - double submit_us = 0; ///< time spent inside the read submission call (non-zero = it blocks) - double read_us_sum = 0; ///< sum of per-read latencies (issue to completion) - uint64_t late_injected = 0; ///< reads delayed by fault injection - uint64_t keepalive_reads = 0; ///< pages read only to keep the SSD awake (not in `reads`, `bytes` or latencies) - double keepalive_us_max = 0; ///< the slowest of them - std::vector read_us; ///< last <= 65,536 read latencies, for percentiles - double percentile(double q) const; -}; - -class PleReader { -public: - struct Ticket { - uint32_t id = 0; - }; - - PleReader(); - ~PleReader(); - PleReader(const PleReader&) = delete; - PleReader& operator=(const PleReader&) = delete; - - /// `table_offset` is the byte offset of row 0 in the file and `n_rows` the row count; both come from a - /// validated GGUF parse (PleTable::open checks the table exactly fills the file from there). - /// `io_thread` (default): a worker thread submits and reaps reads, so `issue` costs the caller no ReadFile - /// calls. false: the caller's thread does it (A/B arm). - /// `row_bytes`: one row's size in the file (90 IQ4_NL, 160 FP8), at most one page. - bool open(const std::string& path, uint64_t table_offset, uint64_t n_rows, uint32_t max_inflight, - uint64_t cache_rows, std::string& err, bool io_thread = true, uint32_t row_bytes = ROW_BYTES); - uint32_t row_bytes() const; - void close(); - bool is_open() const; - - /// Start fetching `n` rows; row i's raw bytes land at `out_raw + row_bytes * i`. `out_raw` must stay valid - /// until `collect` returns. Out-of-range rows produce zero bytes (the mmap path's behaviour). - Ticket issue(const uint32_t* rows, size_t n, uint8_t* out_raw); - - /// Block until every row of the ticket is in `out_raw`. Returns false on an I/O error (message in `err`). - bool collect(Ticket t, std::string& err); - - /// Keep the SSD awake while the table is in use (io_thread mode only; call after `open`): when no read has - /// gone out for `period_ms`, the worker reads one page of the table, until `window_s` after the last `issue`. - /// Some SSDs drop into a power state after ~250 ms without a command and stall the next reads 50-150 ms - /// (a WD_BLACK SN7100 on Windows 11; the NVMe idle timeouts of the power plan did not change it), which in - /// decode happens after a few rounds whose rows all came from the row cache. 0 turns it off (the reader's - /// default; generate turns it on, see STRATA_SSD_KEEPALIVE). A keep-alive read that fails turns it off. - void set_keepalive(double period_ms, double window_s); - - /// Fault injection for tests and for the plan's P2 exit check: every read completes no earlier than - /// `delay_us` after it was issued. 0 disables. - void set_injected_delay_us(double delay_us); - - /// Read with no ticket in flight (the worker updates these while reads are outstanding; with the keep-alive - /// on it may also be counting a keep-alive read - `snapshot` takes a consistent copy). - const ReaderStats& stats() const; - ReaderStats snapshot() const; - void reset_stats(); - uint64_t cache_capacity() const; - uint64_t cache_size() const; - -private: - struct Impl; - Impl* impl_ = nullptr; -}; - -} // namespace strata::ngram diff --git a/include/strata/plan/plan.hpp b/include/strata/plan/plan.hpp deleted file mode 100644 index b974f1f..0000000 --- a/include/strata/plan/plan.hpp +++ /dev/null @@ -1,168 +0,0 @@ -// include/strata/plan/plan.hpp - P1.S9 census + memory planner. -// -// This is the component that makes one binary adapt to the GPU it is running on. The engine has 33.97 GB of -// expert weights (has to live in DRAM and be streamed) and a fixed VRAM budget that has to hold the dense -// weights, the KV cache, the indexer keys, the recurrent state and as many expert-cache slots as remain. -// Every one of those competes, so the plan is an arithmetic result rather than a configuration choice, and -// it must REFUSE rather than silently overcommit. -// -// DERIVATION POLICY. `phases/00-README.md` §2 gives three rows of expected values but no formula, so the -// arithmetic here is derived from the model's geometry and the table is used as a CHECK. Where the two -// disagree the geometry wins and the disagreement is reported - a table transcribed by hand is not a -// specification, and fitting formulas to it would hide exactly the errors this is supposed to catch. -#pragma once - -#include -#include -#include -#include - -namespace strata::plan { - -// ---- model geometry (the real Qwen3.8-Flash-Next artifact) ------------------ -struct Geometry { - int n_layers = 48; - int n_qsa_layers = 12; // layers 3, 7, ... 47 - the full-attention ones - int n_kv_heads = 2; - int head_dim = 256; - int kv_group = 64; // INT8 KV is grouped-64: one fp16 scale per 64 elements - int qsa_block = 4; // the indexer pools one key per 4-token block - /// THE INDEXER'S KEY STORE, and the trap that has now been walked into twice in opposite directions. - /// - /// `indexer.q_proj.weight` is [2560, 512] = **4 QUERY heads** of 128. `indexer.k_proj.weight` is - /// [2560, 128] = **ONE shared KEY head**. The queries are not cached; only the key is. So the cache - /// holds one 128-wide key per TOKEN, pooled to one per `qsa_block`-token block - which - /// `include/strata/kernels/qsa.hpp` states directly: `pooled (max_cells/idx_block + 1, idx_dim)`, and - /// its own note that the fp32 store is "50 MiB at 32K" (12 layers x 8192 blocks x 128 x 4 B = 48 MiB). - /// - /// original indexer_heads(1) * head_dim(256) / 4 = 64 B/token/layer 2x too big - /// round 194 indexer_heads(4) * key_dim(128) / 4 = 128 B/token/layer 4x too big - /// correct key_heads(1) * key_dim(128) / 4 = 32 B/token/layer - /// - /// Round 194 "fixed" this by reading `indexer.head_count = 4` out of the metadata and multiplying by it - - /// right about the metadata, wrong about what was being counted. **A head count in the metadata does not - /// say WHICH tensor it counts.** - int indexer_q_heads = 4; // query heads: they multiply the SCORES, and cost no cache at all - int indexer_key_heads = 1; // k_proj is [n_embd, 128]: ONE shared key head - int indexer_key_dim = 128; // the key width, and the width of the thing that IS cached - - /// GDN geometry. `docs/semantics.md`: `ssm.state_size = 128`, `ssm.time_step_rank = 48` (the v heads), - /// `ssm.conv_kernel = 4`, and `n_embd_r() = (d_conv-1) * (ssm_d_inner + 2*n_group*d_state) = 3 * 10240`. - int ssm_state_size = 128; - int ssm_v_heads = 48; - int ssm_d_conv = 4; - int ssm_conv_channels = 10240; - - /// 36 of the 48 layers are GDN; the rest are QSA. Declared as a derivation rather than a third constant, - /// because a `n_gdn_layers = 36` alongside `n_layers` and `n_qsa_layers` is a third thing to keep in step. - int n_gdn_layers() const { return n_layers - n_qsa_layers; } -}; - -// ---- byte costs ------------------------------------------------------------ -struct Costs { - uint64_t expert_blob = 1382400; // one expert's gate_up+down, codes and scales (architecture §3.2) - uint64_t dense_bytes = 0; // from the manifest: every non-expert tensor, canonical form - uint64_t embd_bytes = 0; // token embedding - uint64_t mtp_bytes = 0; // multi-token-prediction head, when present - uint64_t workspace_bytes = 0; - uint64_t state_bytes = 0; // GDN recurrence + conv history + replay log, per sequence -}; - -// GDN recurrence + conv history, bytes per sequence. DERIVED, for the same reason everything else here is. -// -// This term was MISSING from the plan until round 198: `Costs::state_bytes` exists and `--state` exists, but -// nothing passed it, so the planner was fed zero and quietly planned without it. 36 GDN layers of fp32 state -// is **117.7 MB, or 85 expert cache slots** - not a rounding error. -// -// recurrence (S, h_v, S) fp32 = 128 * 48 * 128 * 4 = 3,145,728 B per layer -// conv history (d_conv-1, C) fp32 = 3 * 10240 * 4 = 122,880 B per layer -// -// It is a FIXED cost and not a cache: it is state, it is resident for the life of a sequence, and it cannot be -// evicted to make room for an expert. A planner that omits it returns a plan it cannot honour, which is the -// failure `DoesNotClose` exists to prevent. -inline uint64_t state_bytes(const Geometry& g) { - const uint64_t per_layer = (uint64_t) g.ssm_state_size * (uint64_t) g.ssm_v_heads * - (uint64_t) g.ssm_state_size * sizeof(float) + - (uint64_t) (g.ssm_d_conv - 1) * (uint64_t) g.ssm_conv_channels * sizeof(float); - return (uint64_t) g.n_gdn_layers() * per_layer; -} - -// INT8 KV + indexer keys, bytes per token. Both terms come from the geometry above and nothing else. -inline uint64_t kv_bytes_per_token(const Geometry& g) { - const uint64_t kv_elems = 2ull * g.n_kv_heads * g.head_dim; // K and V - const uint64_t kv_scales = (kv_elems / (uint64_t)g.kv_group) * 2; // fp16 scale per group - const uint64_t per_layer = kv_elems * 1 + kv_scales; // INT8: one byte per element - // indexer: ONE cached key per block, `idx_dim` wide, SHARED across the query heads. See the note on - // `indexer_key_heads` above - this term has been wrong in both directions and the derivation is why. - const uint64_t idx_layer = - (uint64_t) g.indexer_key_heads * (uint64_t) g.indexer_key_dim / (uint64_t) g.qsa_block; - return (uint64_t)g.n_qsa_layers * (per_layer + idx_layer); -} - -// ---- the plan -------------------------------------------------------------- -struct Plan { - uint64_t max_context = 0; - uint64_t kv_bytes = 0; // KV + indexer keys at max_context - uint64_t state_bytes = 0; // GDN recurrence + conv history - FIXED, not evictable - uint64_t cache_bytes = 0; // what is left for expert cache slots - uint64_t cache_slots = 0; - uint64_t vram_budget = 0; - uint64_t vram_used = 0; - uint64_t dram_experts = 0; // the whole expert arena, streamed - std::vector notes; -}; - -// Thrown when the requested context and the fixed costs cannot both fit. A planner that returns a plan it -// cannot honour is worse than one that fails, because the failure then happens at token 4000 instead of at -// startup. -struct DoesNotClose : std::runtime_error { - explicit DoesNotClose(const std::string& w) : std::runtime_error(w) {} -}; - -// The VRAM budget that the KV cache and the expert cache share. This is the one number taken from -// `00-README.md` §2 rather than derived: the table's three rows all leave `KV + cache` constant, and that -// constant is what the planner is dividing. Expressed in bytes, decimal, matching how the table rounds. -inline uint64_t vram_pool_bytes() { - return 5943000000ull; -} - -inline Plan make_plan(uint64_t max_context, const Geometry& g, const Costs& c, - uint64_t pool = vram_pool_bytes()) { - Plan p; - p.max_context = max_context; - p.vram_budget = pool; - p.kv_bytes = kv_bytes_per_token(g) * max_context; - p.state_bytes = c.state_bytes; - p.dram_experts = c.dense_bytes + c.embd_bytes; // costs that never enter the pool - - const uint64_t fixed = c.dense_bytes + c.embd_bytes + c.mtp_bytes + c.workspace_bytes + c.state_bytes; - if (p.kv_bytes + fixed > pool) { - throw DoesNotClose("max-context " + std::to_string(max_context) + " needs " + - std::to_string(p.kv_bytes + fixed) + " B of the " + std::to_string(pool) + - " B VRAM pool; reduce --max-context"); - } - p.cache_bytes = pool - p.kv_bytes - fixed; - p.cache_slots = p.cache_bytes / c.expert_blob; - p.vram_used = pool - p.cache_bytes % c.expert_blob; // slot remainder is unusable, not free - if (p.cache_slots == 0) { - throw DoesNotClose("no room for even one expert cache slot at max-context " + - std::to_string(max_context)); - } - return p; -} - -inline std::string to_string(const Plan& p) { - auto gb = [](uint64_t b) { return std::to_string(b / 1e9); }; - std::string s; - s += "memory plan --max-context " + std::to_string(p.max_context) + "\n"; - s += " KV + indexer keys " + gb(p.kv_bytes) + " GB\n"; - s += " recurrent state " + gb(p.state_bytes) + " GB (GDN recurrence + conv history, NOT evictable)\n"; - s += " expert cache " + gb(p.cache_bytes) + " GB (" + std::to_string(p.cache_slots) + - " slots of 1,382,400 B)\n"; - s += " VRAM pool " + gb(p.vram_budget) + " GB\n"; - s += " expert arena (DRAM) " + gb(p.dram_experts) + " GB\n"; - for (const std::string& n : p.notes) s += " note: " + n + "\n"; - return s; -} - -} // namespace strata::plan diff --git a/include/strata/plan/vram_plan.hpp b/include/strata/plan/vram_plan.hpp deleted file mode 100644 index 3775e9e..0000000 --- a/include/strata/plan/vram_plan.hpp +++ /dev/null @@ -1,178 +0,0 @@ -// include/strata/plan/vram_plan.hpp - the VRAM planner's arithmetic, as a pure function (Qwen3.6 port, step 2). -// -// docs/QWEN36-35B-A3B.md section 4.2, in order: the fixed set first (the non-expert weights, the drafter, the KV -// cache for the requested context, the session, the CUDA context, the reserve, the prompt buffers unless prefill -// borrows cache slots); when it does not fit, the context is lowered toward the floor (131,072), and below the -// floor the start refuses with the numbers and the smaller file's name - never a silently shorter context; every -// remaining byte becomes expert slots; then the RAM tier from the available RAM minus a headroom; whatever is left -// stays mapped from the model file on disk. KV streaming is not a lever for this model: dense attention reads -// every cell, so the KV stays in VRAM (3.3 item 6). -// -// Header-only and GPU-free on purpose: the engine feeds it `cudaMemGetInfo` (clamped by --vram-cap) and the file's -// census, the unit test (tests/core/vram_plan_test.cpp) feeds it the study's table 4.1 and checks table 4.3, and -// `strata-plan` can print it for any budget. The slot count is at the MEAN blob: the engine's per-layer sizing -// (generate.cpp, `sized_slots`) prices the same bytes at each profile entry's own blob and lands within a few slots -// of it; the table's ladder is at the mean, so the check is at the mean. -#pragma once - -#include -#include -#include - -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 diff --git a/include/strata/platform/direct_file.hpp b/include/strata/platform/direct_file.hpp deleted file mode 100644 index c59eb91..0000000 --- a/include/strata/platform/direct_file.hpp +++ /dev/null @@ -1,60 +0,0 @@ -// include/strata/platform/direct_file.hpp - plan v0.3 P1/P2: unbuffered asynchronous file reads. -// -// The n-gram table (26.8 GiB) stays on the SSD and must never occupy RAM, including the OS file cache. A memory -// map cannot promise that; an unbuffered read can. On Windows this is FILE_FLAG_NO_BUFFERING | OVERLAPPED with -// an I/O completion port; on Linux, O_DIRECT preads. Both issue the reads from a small thread pool (submit only -// queues), so many reads are in flight: STRATA_IO_THREADS sets its size (default 4 on Windows, 16 on Linux). -// -// Contract of every read: offset, length and buffer address are multiples of `alignment()` (4096 here). -// Reads past end of file return the bytes that exist; `Completion::bytes` says how many. -#pragma once - -#include -#include - -namespace strata::platform { - -struct Completion { - uint64_t tag = 0; ///< the caller's tag from `submit` - uint32_t bytes = 0; ///< bytes transferred (short only at end of file) - bool ok = false; -}; - -class DirectFile { -public: - DirectFile(); - ~DirectFile(); - DirectFile(const DirectFile&) = delete; - DirectFile& operator=(const DirectFile&) = delete; - - bool open(const std::string& path, std::string& err); - void close(); - bool is_open() const; - uint64_t size() const; - static constexpr uint32_t alignment() { return 4096; } - - /// Queue one read. Returns false (and sets `err`) if the request could not be queued; a queued request - /// always produces exactly one completion. - bool submit(uint64_t offset, void* buffer, uint32_t length, uint64_t tag, std::string& err); - - /// Wait for up to `max` completions; returns how many were written to `out`. `timeout_ms` < 0 waits - /// forever; 0 polls. A `wake()` shows up as one completion with tag `WAKE_TAG`. - int wait(Completion* out, int max, int timeout_ms); - - /// Make a thread blocked in `wait` return (thread-safe). Used to hand it newly queued work. - static constexpr uint64_t WAKE_TAG = ~0ull; - void wake(); - - /// Allocation helpers for aligned read buffers (page-aligned, never touched by the cache manager). - static void* alloc_aligned(size_t bytes); - static void free_aligned(void* p); - -private: - struct Impl; - Impl* impl_ = nullptr; -}; - -/// Monotonic time in microseconds, for latency accounting. -double now_us(); - -} // namespace strata::platform diff --git a/include/strata/platform/hip_compat/cublas_v2.h b/include/strata/platform/hip_compat/cublas_v2.h deleted file mode 100644 index fe8ea15..0000000 --- a/include/strata/platform/hip_compat/cublas_v2.h +++ /dev/null @@ -1,26 +0,0 @@ -// cublas_v2.h for a STRATA_ENABLE_HIP build: the cuBLAS names src/prefill/gemm.cu uses, on hipBLAS. -#pragma once -#include "strata_hip.h" -#ifndef HIPBLAS_V2 -#define HIPBLAS_V2 -#endif -#include - -#define cublasHandle_t hipblasHandle_t -#define cublasStatus_t hipblasStatus_t -#define CUBLAS_STATUS_SUCCESS HIPBLAS_STATUS_SUCCESS -#define cublasCreate hipblasCreate -#define cublasDestroy hipblasDestroy -#define cublasSetStream hipblasSetStream -#define cublasGemmEx hipblasGemmEx -#define CUBLAS_OP_N HIPBLAS_OP_N -#define CUBLAS_OP_T HIPBLAS_OP_T -#define CUBLAS_GEMM_DEFAULT HIPBLAS_GEMM_DEFAULT -#define CUBLAS_COMPUTE_32F HIPBLAS_COMPUTE_32F -#define CUDA_R_32F HIP_R_32F -#define CUDA_R_16F HIP_R_16F -#define CUDA_R_16BF HIP_R_16BF -// rocBLAS picks its own math and workspace; the NVIDIA-only knobs are accepted and ignored -#define CUBLAS_DEFAULT_MATH 0 -#define cublasSetMathMode(handle, mode) HIPBLAS_STATUS_SUCCESS -#define cublasSetWorkspace(handle, ptr, bytes) HIPBLAS_STATUS_SUCCESS diff --git a/include/strata/platform/hip_compat/cuda_fp16.h b/include/strata/platform/hip_compat/cuda_fp16.h deleted file mode 100644 index 4cd2d3c..0000000 --- a/include/strata/platform/hip_compat/cuda_fp16.h +++ /dev/null @@ -1,2 +0,0 @@ -#pragma once -#include "strata_hip.h" diff --git a/include/strata/platform/hip_compat/cuda_runtime.h b/include/strata/platform/hip_compat/cuda_runtime.h deleted file mode 100644 index 4cd2d3c..0000000 --- a/include/strata/platform/hip_compat/cuda_runtime.h +++ /dev/null @@ -1,2 +0,0 @@ -#pragma once -#include "strata_hip.h" diff --git a/include/strata/platform/hip_compat/math_constants.h b/include/strata/platform/hip_compat/math_constants.h deleted file mode 100644 index b00d57b..0000000 --- a/include/strata/platform/hip_compat/math_constants.h +++ /dev/null @@ -1,4 +0,0 @@ -// math_constants.h for a STRATA_ENABLE_HIP build: the CUDART_* constants the tree uses. -#pragma once -#define CUDART_INF_F __builtin_huge_valf() -#define CUDART_NAN_F __builtin_nanf("") diff --git a/include/strata/platform/hip_compat/strata_hip.h b/include/strata/platform/hip_compat/strata_hip.h deleted file mode 100644 index b0de6c4..0000000 --- a/include/strata/platform/hip_compat/strata_hip.h +++ /dev/null @@ -1,295 +0,0 @@ -// strata_hip.h - the CUDA runtime/cuBLAS names Strata uses, mapped onto HIP/hipBLAS for AMD GPUs (gfx906). -// -// This directory is put FIRST on the include path of a STRATA_ENABLE_HIP build only; its `cuda_runtime.h`, -// `cuda_fp16.h` and `cublas_v2.h` include this header instead of the NVIDIA ones, so the engine's sources stay -// one tree. The mapping list follows llama.cpp's ggml-cuda/vendors/hip.h (MIT) where the two overlap. -// -// The warp contract: every Strata kernel is written for a 32-lane warp. gfx906 runs 64-lane wavefronts, so -// here a CUDA warp is a LOGICAL 32-lane half of a wavefront: every shuffle defaults to width 32 (a -// `__shfl_down_sync(m, v, 1)` at lane 31 must not read lane 32), `__ballot_sync` returns the 32-bit mask of the -// caller's own half, and `__syncwarp` is a wavefront barrier plus an LDS fence. That keeps every kernel's -// arithmetic, lane mapping and reduction order exactly as on NVIDIA; wave64-native rewrites of the hot kernels -// are separate, measured changes. -#pragma once - -#ifndef HIP_DISABLE_WARP_SYNC_BUILTINS -#define HIP_DISABLE_WARP_SYNC_BUILTINS 1 -#endif -#include -#include - -#include -#include - -#define STRATA_HIP_GFX906 1 - -// ---- runtime: types and constants ------------------------------------------------------------------------ -#define cudaError_t hipError_t -#define cudaSuccess hipSuccess -#define cudaErrorNotReady hipErrorNotReady -#define cudaErrorMemoryAllocation hipErrorOutOfMemory -#define cudaErrorStreamCaptureUnsupported hipErrorStreamCaptureUnsupported -#define cudaErrorPeerAccessAlreadyEnabled hipErrorPeerAccessAlreadyEnabled -#define cudaStream_t hipStream_t -#define cudaEvent_t hipEvent_t -#define cudaGraph_t hipGraph_t -#define cudaGraphExec_t hipGraphExec_t -#define cudaGraphNode_t hipGraphNode_t -#define cudaDeviceProp hipDeviceProp_t -#define cudaMemcpyKind hipMemcpyKind -#define cudaMemcpyHostToDevice hipMemcpyHostToDevice -#define cudaMemcpyDeviceToHost hipMemcpyDeviceToHost -#define cudaMemcpyDeviceToDevice hipMemcpyDeviceToDevice -#define cudaMemcpyDefault hipMemcpyDefault -#define cudaStreamNonBlocking hipStreamNonBlocking -#define cudaStreamCaptureModeThreadLocal hipStreamCaptureModeThreadLocal -#define cudaStreamCaptureModeRelaxed hipStreamCaptureModeRelaxed -#define cudaStreamCaptureModeGlobal hipStreamCaptureModeGlobal -#define cudaStreamCaptureStatus hipStreamCaptureStatus -#define cudaStreamCaptureStatusNone hipStreamCaptureStatusNone -#define cudaStreamCaptureStatusActive hipStreamCaptureStatusActive -#define cudaEventDisableTiming hipEventDisableTiming -#define cudaEventDefault hipEventDefault -#define cudaHostAllocDefault hipHostMallocDefault -#define cudaHostAllocPortable hipHostMallocPortable -#define cudaHostAllocMapped hipHostMallocMapped -#define cudaHostAllocWriteCombined hipHostMallocWriteCombined -#define cudaHostRegisterDefault hipHostRegisterDefault -#define cudaHostRegisterPortable hipHostRegisterPortable -#define cudaHostRegisterMapped hipHostRegisterMapped -#define cudaHostRegisterReadOnly hipHostRegisterReadOnly -#define cudaDeviceScheduleSpin hipDeviceScheduleSpin -#define cudaDeviceScheduleYield hipDeviceScheduleYield -#define cudaDeviceScheduleBlockingSync hipDeviceScheduleBlockingSync -#define cudaDeviceMapHost hipDeviceMapHost -#define cudaFuncAttributeMaxDynamicSharedMemorySize hipFuncAttributeMaxDynamicSharedMemorySize -#define cudaDevAttrMultiProcessorCount hipDeviceAttributeMultiprocessorCount -#define cudaDevAttrClockRate hipDeviceAttributeClockRate -#define cudaDevAttrComputeCapabilityMajor hipDeviceAttributeComputeCapabilityMajor -#define cudaDevAttrComputeCapabilityMinor hipDeviceAttributeComputeCapabilityMinor -#define cudaDevAttrMaxSharedMemoryPerBlockOptin hipDeviceAttributeSharedMemPerBlockOptin -#define cudaDevAttrMemoryClockRate hipDeviceAttributeMemoryClockRate -#define cudaDevAttrGlobalMemoryBusWidth hipDeviceAttributeMemoryBusWidth - -// ---- runtime: functions ---------------------------------------------------------------------------------- -#define cudaGetErrorString hipGetErrorString -#define cudaGetErrorName hipGetErrorName -#define cudaGetLastError hipGetLastError -#define cudaPeekAtLastError hipPeekAtLastError -#define cudaGetDevice hipGetDevice -#define cudaSetDevice hipSetDevice -#define cudaGetDeviceCount hipGetDeviceCount -#define cudaGetDeviceProperties hipGetDeviceProperties -// The shared-memory opt-in limit: some HIP versions report 0 for it on GCN cards; the real ceiling there is -// the plain per-block limit (64 KB of LDS on gfx906). -inline hipError_t strata_device_get_attribute(int* v, hipDeviceAttribute_t a, int dev) { - hipError_t e = hipDeviceGetAttribute(v, a, dev); - if (e == hipSuccess && a == hipDeviceAttributeSharedMemPerBlockOptin && *v <= 0) - e = hipDeviceGetAttribute(v, hipDeviceAttributeMaxSharedMemoryPerBlock, dev); - return e; -} -#define cudaDeviceGetAttribute strata_device_get_attribute -#define cudaDeviceSynchronize hipDeviceSynchronize -#define cudaDeviceCanAccessPeer hipDeviceCanAccessPeer -#define cudaDeviceEnablePeerAccess hipDeviceEnablePeerAccess -#define cudaDriverGetVersion hipDriverGetVersion -#define cudaRuntimeGetVersion hipRuntimeGetVersion -#define cudaSetDeviceFlags hipSetDeviceFlags -#define cudaMalloc hipMalloc -#define cudaFree hipFree -#define cudaMemGetInfo hipMemGetInfo -#define cudaMemcpy hipMemcpy -#define cudaMemcpyAsync hipMemcpyAsync -#define cudaMemcpyPeerAsync hipMemcpyPeerAsync -#define cudaMemcpy2DAsync hipMemcpy2DAsync -#define cudaMemset hipMemset -#define cudaMemsetAsync hipMemsetAsync -// Mapped host memory is how the GPU and the CPU talk inside a running graph (the doorbells, the CPU experts' -// results, the verify flags): a kernel spins on a word the CPU writes, and the CPU on a word the kernel writes. -// On AMD that needs FINE-GRAINED (coherent) memory - coarse-grained host memory may sit in the GPU's L2 for the -// whole kernel and the spin never sees the other side. So every mapped allocation is made coherent here. -inline hipError_t strata_host_alloc(void** p, size_t bytes, unsigned int flags) { - if (flags & hipHostMallocMapped) flags |= hipHostMallocCoherent; - return hipHostMalloc(p, bytes, flags); -} -template inline hipError_t strata_host_alloc(T** p, size_t bytes, unsigned int flags) { - return strata_host_alloc(reinterpret_cast(p), bytes, flags); -} -#define cudaHostAlloc strata_host_alloc -#define cudaMallocHost(ptr, size) hipHostMalloc(ptr, size, hipHostMallocDefault) -#define cudaFreeHost hipHostFree -#define cudaHostRegister hipHostRegister -#define cudaHostUnregister hipHostUnregister -#define cudaHostGetDevicePointer hipHostGetDevicePointer -#define cudaStreamCreate hipStreamCreate -#define cudaStreamCreateWithFlags hipStreamCreateWithFlags -#define cudaStreamDestroy hipStreamDestroy -#define cudaStreamSynchronize hipStreamSynchronize -#define cudaStreamQuery hipStreamQuery -#define cudaStreamWaitEvent hipStreamWaitEvent -#define cudaStreamBeginCapture hipStreamBeginCapture -#define cudaStreamEndCapture hipStreamEndCapture -#define cudaStreamIsCapturing hipStreamIsCapturing -#define cudaLaunchHostFunc hipLaunchHostFunc -#define cudaEventCreate hipEventCreate -#define cudaEventCreateWithFlags hipEventCreateWithFlags -#define cudaEventDestroy hipEventDestroy -#define cudaEventRecord hipEventRecord -#define cudaEventQuery hipEventQuery -#define cudaEventSynchronize hipEventSynchronize -#define cudaEventElapsedTime hipEventElapsedTime -#define cudaGraphLaunch hipGraphLaunch -#define cudaGraphUpload hipGraphUpload -#define cudaGraphDestroy hipGraphDestroy -#define cudaGraphExecDestroy hipGraphExecDestroy -#define cudaGraphGetNodes hipGraphGetNodes -#define cudaGraphNodeType hipGraphNodeType -#define cudaGraphNodeGetType hipGraphNodeGetType -#define cudaGraphNodeTypeKernel hipGraphNodeTypeKernel -#define cudaGraphNodeTypeMemcpy hipGraphNodeTypeMemcpy -#define cudaGraphNodeTypeMemset hipGraphNodeTypeMemset -#define cudaKernelNodeParams hipKernelNodeParams -#define cudaGraphKernelNodeGetParams hipGraphKernelNodeGetParams -inline hipError_t cudaFuncGetName(const char** name, const void*) { *name = nullptr; return hipErrorNotSupported; } -#define cudaFuncSetAttribute(fn, attr, val) hipFuncSetAttribute(reinterpret_cast(fn), attr, val) -#define cudaMemcpyToSymbol(sym, src, ...) hipMemcpyToSymbol(HIP_SYMBOL(sym), src, __VA_ARGS__) - -// CUDA 12 has a 3-argument cudaGraphInstantiate(exec, graph, flags) and the older 5-argument one; HIP spells -// the first hipGraphInstantiateWithFlags. Both are used in the tree. -inline hipError_t cudaGraphInstantiate(hipGraphExec_t* exec, hipGraph_t graph, unsigned long long flags) { - return hipGraphInstantiateWithFlags(exec, graph, flags); -} -inline hipError_t cudaGraphInstantiate(hipGraphExec_t* exec, hipGraph_t graph, hipGraphNode_t* err_node, - char* log, size_t log_size) { - return hipGraphInstantiate(exec, graph, err_node, log, log_size); -} -// cudaInitDevice(dev, deviceFlags, flags): initialise a device and its scheduling flags WITHOUT making it the -// current device (CUDA's contract; the layer split relies on it - a changed current device put GPU 0's expert -// cache on GPU 1). -inline hipError_t cudaInitDevice(int device, unsigned int device_flags, unsigned int /*flags*/) { - int prev = 0; - hipError_t e = hipGetDevice(&prev); - if (e != hipSuccess) return e; - e = hipSetDevice(device); - if (e != hipSuccess) return e; - if (hipSetDeviceFlags(device_flags) != hipSuccess) (void) hipGetLastError(); // context already active - return hipSetDevice(prev); -} - -// ---- device side ----------------------------------------------------------------------------------------- -#if defined(__HIP_DEVICE_COMPILE__) || defined(__HIPCC__) - -// Logical 32-lane warps (see the header comment). The width argument, when given, wins. -#define __shfl_sync(mask, var, lane, ...) __shfl(var, lane, STRATA_SHFL_W(__VA_ARGS__)) -#define __shfl_up_sync(mask, var, delta, ...) __shfl_up(var, delta, STRATA_SHFL_W(__VA_ARGS__)) -#define __shfl_down_sync(mask, var, delta, ...) __shfl_down(var, delta, STRATA_SHFL_W(__VA_ARGS__)) -#define __shfl_xor_sync(mask, var, lanemask, ...) __shfl_xor(var, lanemask, STRATA_SHFL_W(__VA_ARGS__)) -// STRATA_SHFL_W() -> 32, STRATA_SHFL_W(w) -> w -#define STRATA_SHFL_W(...) STRATA_SHFL_W_I(dummy, ##__VA_ARGS__, STRATA_SHFL_W_GIVEN, STRATA_SHFL_W_DEFAULT)(__VA_ARGS__) -#define STRATA_SHFL_W_I(d, a, b, ...) b -#define STRATA_SHFL_W_GIVEN(w) (w) -#define STRATA_SHFL_W_DEFAULT(...) 32 -#define __all_sync(mask, pred) __all(pred) -#define __any_sync(mask, pred) __any(pred) - -static __device__ __forceinline__ unsigned int strata_ballot32(int pred) { - const unsigned long long b = __ballot(pred); - return (unsigned int) (b >> (__lane_id() & 32u)); -} -#define __ballot_sync(mask, pred) strata_ballot32(pred) -#define __activemask() ((unsigned int) (__ballot(1) >> (__lane_id() & 32u))) - -static __device__ __forceinline__ void strata_syncwarp() { - __builtin_amdgcn_fence(__ATOMIC_RELEASE, "wavefront"); - __builtin_amdgcn_wave_barrier(); - __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "wavefront"); -} -#define __syncwarp(...) strata_syncwarp() - -// __nanosleep(ns): s_sleep counts 64 clocks per unit (~40 ns at the 1.7 GHz shader clock); a spin loop only -// needs "back off a little", not an exact time. -static __device__ __forceinline__ void strata_nanosleep(unsigned int ns) { - if (ns >= 400) __builtin_amdgcn_s_sleep(8); - else __builtin_amdgcn_s_sleep(1); -} -#define __nanosleep(ns) strata_nanosleep(ns) -#define __trap() __builtin_trap() - -// __dp4a(a, b, c): signed 8-bit dot product plus accumulator; gfx906 has v_dot4_i32_i8. -static __device__ __forceinline__ int strata_dp4a(int a, int b, int c) { -#if defined(__gfx906__) || defined(__gfx908__) || defined(__gfx90a__) || defined(__gfx942__) || defined(__GFX11__) || defined(__GFX12__) - return __builtin_amdgcn_sdot4(a, b, c, false); -#else - const int8_t* va = reinterpret_cast(&a); - const int8_t* vb = reinterpret_cast(&b); - return c + va[0] * vb[0] + va[1] * vb[1] + va[2] * vb[2] + va[3] * vb[3]; -#endif -} -static __device__ __forceinline__ unsigned int strata_dp4a(unsigned int a, unsigned int b, unsigned int c) { - const uint8_t* va = reinterpret_cast(&a); - const uint8_t* vb = reinterpret_cast(&b); - return c + va[0] * vb[0] + va[1] * vb[1] + va[2] * vb[2] + va[3] * vb[3]; -} -#define __dp4a strata_dp4a - -// SIMD-in-a-word byte ops (CUDA semantics: __vsub4 wraps per byte, __vsubss4 saturates, __vcmp*4 give 0xff) -typedef int8_t strata_i8x4 __attribute__((ext_vector_type(4))); -typedef uint8_t strata_u8x4 __attribute__((ext_vector_type(4))); -static __device__ __forceinline__ unsigned int strata_vsub4(unsigned int a, unsigned int b) { - const strata_u8x4 va = __builtin_bit_cast(strata_u8x4, a); - const strata_u8x4 vb = __builtin_bit_cast(strata_u8x4, b); - return __builtin_bit_cast(unsigned int, (strata_u8x4) (va - vb)); -} -static __device__ __forceinline__ int strata_vsubss4(int a, int b) { - const strata_i8x4 va = __builtin_bit_cast(strata_i8x4, a); - const strata_i8x4 vb = __builtin_bit_cast(strata_i8x4, b); - return __builtin_bit_cast(int, (strata_i8x4) __builtin_elementwise_sub_sat(va, vb)); -} -static __device__ __forceinline__ unsigned int strata_vcmpeq4(unsigned int a, unsigned int b) { - const strata_u8x4 va = __builtin_bit_cast(strata_u8x4, a); - const strata_u8x4 vb = __builtin_bit_cast(strata_u8x4, b); - strata_u8x4 c; -#pragma unroll - for (int i = 0; i < 4; ++i) c[i] = va[i] == vb[i] ? 0xff : 0x00; - return __builtin_bit_cast(unsigned int, c); -} -static __device__ __forceinline__ unsigned int strata_vcmpne4(unsigned int a, unsigned int b) { - return ~strata_vcmpeq4(a, b); -} -#define __vsub4(a, b) ((int) strata_vsub4((unsigned int) (a), (unsigned int) (b))) -#define __vsubss4(a, b) strata_vsubss4((int) (a), (int) (b)) -#define __vcmpeq4(a, b) strata_vcmpeq4((unsigned int) (a), (unsigned int) (b)) -#define __vcmpne4(a, b) strata_vcmpne4((unsigned int) (a), (unsigned int) (b)) - - -// __fmul_rn / __fadd_rn / __fsub_rn: on NVIDIA these are never contracted into an FMA (that is their point - the -// engine uses them where a result must match a reference bit for bit). HIP spells them as plain operators, which -// clang's default -ffp-contract=fast-honor-pragmas may fuse. The pragma keeps each one a separate rounding. -static __device__ __forceinline__ float strata_fmul_rn(float a, float b) { -#pragma clang fp contract(off) - return a * b; -} -static __device__ __forceinline__ float strata_fadd_rn(float a, float b) { -#pragma clang fp contract(off) - return a + b; -} -static __device__ __forceinline__ float strata_fsub_rn(float a, float b) { -#pragma clang fp contract(off) - return a - b; -} -#define __fmul_rn(a, b) strata_fmul_rn((a), (b)) -#define __fadd_rn(a, b) strata_fadd_rn((a), (b)) -#define __fsub_rn(a, b) strata_fsub_rn((a), (b)) - - -// __byte_perm(x, y, s): HIP's own version builds an 8-byte array and indexes it - the array lands in SCRATCH -// memory, and every IQ4 codebook lookup went through it (a 0.9 MB IQ4_NL GEMV took 290 us, ~3 GB/s). gfx906 has -// v_perm_b32, which selects bytes of {src0:src1} (src1 low) by byte selectors 0-7: the same operation, one -// instruction. CUDA reads the low 3 bits of each of the four low selector nibbles. -static __device__ __forceinline__ unsigned int strata_byte_perm(unsigned int x, unsigned int y, unsigned int s) { - const unsigned int sel = (s & 0x7u) | ((s & 0x70u) << 4) | ((s & 0x700u) << 8) | ((s & 0x7000u) << 12); - return __builtin_amdgcn_perm(y, x, sel); -} -#define __byte_perm(x, y, s) strata_byte_perm((unsigned int) (x), (unsigned int) (y), (unsigned int) (s)) - -#endif // device side diff --git a/include/strata/platform/memory.hpp b/include/strata/platform/memory.hpp deleted file mode 100644 index 202a3bf..0000000 --- a/include/strata/platform/memory.hpp +++ /dev/null @@ -1,46 +0,0 @@ -// include/strata/platform/memory.hpp - plan v0.3 P0.1/P1: keep a large host region resident. -// -// `cudaHostRegister` refuses the 31.6 GiB expert arena on Windows, and an unlocked arena is trimmed under memory -// pressure (the CPU pool then swung 2x between runs). With the n-gram table out of RAM there is headroom to lock -// it instead: raise the process's minimum working set by the region's size, then VirtualLock it (Windows needs -// only SeIncreaseWorkingSetPrivilege, which ordinary accounts hold). Linux: mlock. -#pragma once - -#include -#include - -namespace strata::platform { - -struct LockResult { - bool ok = false; - uint64_t locked_bytes = 0; ///< may be less than requested; the rest stays pageable - std::string note; ///< what was done or why it failed, for the startup print -}; - -/// Lock [p, p + bytes) into physical memory. Partial success is reported, not hidden. -LockResult lock_resident(void* p, uint64_t bytes); - -/// Undo lock_resident for the same region (best effort). -void unlock_resident(void* p, uint64_t bytes); - -/// #243, Windows: the GPU's shared (non-local) memory budget and this process's use of it, from DXGI -/// (IDXGIAdapter3::QueryVideoMemoryInfo, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL) for the adapter whose LUID is the -/// 8 bytes at `luid` (cudaDeviceProp::luid). Page-locked host memory the GPU maps is charged there. False (and -/// `why` says so) when the query is not possible - always elsewhere than Windows. -bool gpu_shared_memory_budget(const void* luid, uint64_t& budget, uint64_t& usage, std::string& why); - -/// The machine's physical RAM in bytes (0 when unknown). -uint64_t total_physical_memory(); - -/// #357/#577: whether the OS file cache could keep the `read_bytes` the expert files are read for, beside -/// `arena_bytes` of RAM held by the engine's own copy of the experts and `margin` for everything else, with `avail` -/// bytes of RAM available. The file tier passes only the expert bytes it really reads from the files (the experts -/// outside its resident RAM copy) and the RAM that copy really holds - not every shard's bytes and the requested -/// budget, which on a 96 GB PC (#577) made the file tier read unbuffered when the cache could keep its reads. -inline bool file_cache_keeps(uint64_t avail, uint64_t arena_bytes, uint64_t read_bytes, - uint64_t margin = 4ull << 30) { - const uint64_t room = avail > arena_bytes + margin ? avail - arena_bytes - margin : 0; - return room >= read_bytes; -} - -} // namespace strata::platform diff --git a/include/strata/platform/robust_read.hpp b/include/strata/platform/robust_read.hpp deleted file mode 100644 index 6ab6a66..0000000 --- a/include/strata/platform/robust_read.hpp +++ /dev/null @@ -1,181 +0,0 @@ -// strata/platform/robust_read.hpp - positional reads that survive a slow or remote file system. -// -// A model on a network store (an S3-backed FUSE mount, NFS) can refuse a read for a moment where a local SSD never -// does: ENOMEM from the mount's own buffer limit when many readers are open at once, EIO or a time-out from the -// link. `read_at` retries those with a growing pause, and through a shared `ReadGate` halves how many readers run -// at once each time one of them is refused. `read_range` loads one contiguous range with several readers, each -// on a handle of its own, because such a store's speed is per stream. -#pragma once - -#if !defined(_WIN32) - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -namespace strata::platform { - -/// `pread`'s signature; the tests pass a function that fails on purpose. -using PreadFn = ssize_t (*)(int, void*, size_t, off_t); - -/// How many readers may be inside a read at once. It starts at the reader count, is halved when the store refuses -/// a read, and climbs back by one after every `kRecover` reads in a row that worked. -class ReadGate { -public: - explicit ReadGate(int readers) : limit_(std::max(readers, 1)), most_(limit_) {} - - /// Waits for a place and returns the limit in force at that moment (what `refused` wants back). - int enter() { - std::unique_lock lk(mu_); - cv_.wait(lk, [&] { return active_ < limit_; }); - ++active_; - return limit_; - } - /// `ok`: the read returned bytes. - void leave(bool ok = true) { - { - std::lock_guard lk(mu_); - --active_; - if (!ok) good_ = 0; - else if (limit_ < most_ && ++good_ >= kRecover) { - ++limit_; - good_ = 0; - } - } - cv_.notify_all(); - } - /// A read that entered under `seen` was refused. Halves the limit once per burst: readers refused together - /// all saw the same limit, and only the first of them lowers it. Returns the new limit, 0 if unchanged. - int refused(int seen) { - std::lock_guard lk(mu_); - if (seen != limit_ || limit_ == 1) return 0; - limit_ = std::max(limit_ / 2, 1); - good_ = 0; - return limit_; - } - int limit() { - std::lock_guard lk(mu_); - return limit_; - } - -private: - std::mutex mu_; - std::condition_variable cv_; - static constexpr int kRecover = 32; - int limit_; - int most_; - int active_ = 0; - int good_ = 0; -}; - -/// The errors a remote store gives for a read that works when asked again. -inline bool read_error_is_transient(int e) { - switch (e) { - case ENOMEM: case EAGAIN: case EIO: case ETIMEDOUT: case ENOBUFS: case EBUSY: case ESTALE: - case ECONNRESET: case ECONNABORTED: case ENETDOWN: case ENETUNREACH: case EHOSTUNREACH: case ENOTCONN: - return true; - default: - return false; - } -} - -inline std::string read_error(const std::string& path, uint64_t off, int e) { - return "cannot read " + path + " at offset " + std::to_string(off) + ": " + - (e == ENODATA ? std::string("the file ends before that") : std::string(std::strerror(e))); -} - -/// Reads exactly `n` bytes at `off`. Returns 0, or the errno of the read that could not be completed: ENODATA if -/// the file ends early, a transient error only after `max_wait_s` seconds of retries without one byte arriving. -inline int read_at(int fd, void* buf, size_t n, uint64_t off, ReadGate& gate, PreadFn pread_fn = ::pread, - double max_wait_s = 120.0) { - size_t done = 0; - double pause = 0.05, waited = 0.0; - while (done < n) { - const int seen = gate.enter(); - const ssize_t got = pread_fn(fd, (uint8_t*) buf + done, n - done, (off_t) (off + done)); - const int e = got < 0 ? errno : 0; - gate.leave(got > 0); - if (got > 0) { - done += (size_t) got; - pause = 0.05; - waited = 0.0; - continue; - } - if (got == 0) return ENODATA; - if (e == EINTR) continue; - if (!read_error_is_transient(e) || waited >= max_wait_s) return e; - const int now = gate.refused(seen); - if (now > 0) - std::fprintf(stderr, "strata: a read was refused (%s); retrying with at most %d reader%s at once for now\n", - std::strerror(e), now, now == 1 ? "" : "s"); - std::this_thread::sleep_for(std::chrono::duration(pause)); - waited += pause; - pause = std::min(pause * 2.0, 5.0); - } - return 0; -} - -/// Loads `bytes` at `off` of `path` into `dst` with up to `readers` readers. With `what`, progress goes to stderr -/// every 4 GiB. False with `err` set on failure. -inline bool read_range(const std::string& path, uint64_t off, uint8_t* dst, uint64_t bytes, int readers, - std::string& err, const char* what = nullptr, PreadFn pread_fn = ::pread, - double max_wait_s = 120.0) { - constexpr uint64_t kChunk = 16ull << 20; - const uint64_t n_chunks = (bytes + kChunk - 1) / kChunk; - readers = (int) std::clamp((uint64_t) std::max(readers, 1), 1, std::max(n_chunks, 1)); - ReadGate gate(readers); - std::atomic next{0}, loaded{0}; - std::atomic bad{false}; - std::mutex err_mu; - const auto t0 = std::chrono::steady_clock::now(); - auto fail = [&](const std::string& m) { - std::lock_guard lk(err_mu); - if (!bad.exchange(true)) err = m; - }; - auto worker = [&]() { - const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC); - if (fd < 0) { - fail("cannot open " + path + ": " + std::strerror(errno)); - return; - } - for (;;) { - const uint64_t c = next.fetch_add(1); - if (c >= n_chunks || bad) break; - const uint64_t at = c * kChunk, n = std::min(kChunk, bytes - at); - const int e = read_at(fd, dst + at, (size_t) n, off + at, gate, pread_fn, max_wait_s); - if (e != 0) { - fail(read_error(path, off + at, e)); - break; - } - const uint64_t was = loaded.fetch_add(n); - if (what != nullptr && (was + n) >> 32 != was >> 32) { - const double s = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - std::fprintf(stderr, "strata: %s: %.0f of %.1f GiB read (%.0f MB/s)\n", what, - (double) (was + n) / 1073741824.0, (double) bytes / 1073741824.0, - s > 0 ? (double) (was + n) / 1e6 / s : 0.0); - } - } - ::close(fd); - }; - std::vector pool; - for (int i = 1; i < readers; ++i) pool.emplace_back(worker); - worker(); - for (auto& t : pool) t.join(); - return !bad; -} - -} // namespace strata::platform - -#endif // !_WIN32 diff --git a/include/strata/prefill/gemm.hpp b/include/strata/prefill/gemm.hpp deleted file mode 100644 index 60d1c71..0000000 --- a/include/strata/prefill/gemm.hpp +++ /dev/null @@ -1,66 +0,0 @@ -// include/strata/prefill/gemm.hpp - plan v0.3 P5: the batched projections of prompt processing. -// -// Every projection of a chunk of T tokens is Y[T, N] = X[T, K] . W[N, K]^T with W row-major (the GGUF / pack layout) -// and FP32 outputs. Weights are BF16 on the device - either already (the pack's BF16 tensors) or dequantized from -// their native GGUF blocks into a reusable scratch (`dequant_bf16`) right before the product - and activations are -// rounded to BF16, which is also what llama.cpp's batched CUDA path does. Tensor-core GEMM through cuBLAS. -#pragma once - -#include -#include -#include - -namespace strata::prefill { - -class Gemm { -public: - Gemm() = default; - ~Gemm(); - Gemm(const Gemm&) = delete; - Gemm& operator=(const Gemm&) = delete; - - /// `scratch_elems`: BF16 elements of the dequantization scratch (the largest weight dequantized at once). - bool init(void* stream, int64_t scratch_elems, std::string& err); - /// The same with caller-owned device buffers (the prompt path borrowing expert-cache slots). - bool init_external(void* stream, uint16_t* scratch, int64_t scratch_elems, void* workspace, size_t ws_bytes, - std::string& err); - - /// Y[T, N] (fp32, row stride ldy) = X[T, K] (bf16, row-major) . W[N, K]^T (bf16, row-major). `beta` = 1 adds. - /// Below sm_80 (no BF16 tensor cores): Volta converts both to FP16 and runs the FP16 tensor-core GEMM (Turing with - /// STRATA_BF16_TC=1), Pascal widens both to fp32 (cublasSgemm); see gemm.cu. - void bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy = 0, - float beta = 0.0f); - - /// Y = X . W^T with both in FP16 (bits). - void f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy = 0, - float beta = 0.0f); - - /// W given as native GGUF blocks of `ggml_type`, dequantized to FP16 in the scratch, X in FP16. - void native(const uint16_t* X, int ggml_type, const void* W_blocks, float* Y, int64_t T, int64_t N, int64_t K, - int64_t ldy = 0, float beta = 0.0f); - - /// Caller-owned buffers only: the scratch and workspace moved (the prompt path laid its buffers out again). - void rebind(uint16_t* scratch, int64_t scratch_elems, void* workspace, size_t ws_bytes); - - uint16_t* scratch() const { return scratch_; } - int64_t scratch_elems() const { return scratch_elems_; } - void* stream() const { return stream_; } - -private: - void* handle_ = nullptr; - void* stream_ = nullptr; - uint16_t* scratch_ = nullptr; - int64_t scratch_elems_ = 0; - void* workspace_ = nullptr; - bool external_ = false; - void* hipblaslt_state_ = nullptr; - // below sm_80: FP16 (Pascal: fp32) copies of a BF16 product's weight and activation slice (Gemm::bf16) - uint16_t* tc_w_ = nullptr; - int64_t tc_w_elems_ = 0; - uint16_t* tc_x_ = nullptr; - int64_t tc_x_elems_ = 0; -}; - - - -} // namespace strata::prefill diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp deleted file mode 100644 index 2606bd6..0000000 --- a/include/strata/prefill/kernels.hpp +++ /dev/null @@ -1,123 +0,0 @@ -// include/strata/prefill/kernels.hpp - plan v0.3 P5: the element-wise and stateful kernels of a prompt chunk. -// -// T tokens at a time, all row-major with the token as the slow index. The arithmetic mirrors the per-token native -// kernels (the decode path), batched; where a step is a recurrence in time (the GDN conv and state, the PLE conv) -// 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" - -#include - -namespace strata::prefill { - -// ---- hyper-connection (n_embd 2560, hc 4, hc_lr 320) -/// xn[t, c*2560 + d] = R[t,c,d] * rsqrt(mean_d R[t,c,:]^2 + eps) * w_norm[c*2560 + d]; also its BF16 image. -/// `xn16_lo` (null: none) takes bf16(x - xn16): W.xn16 + W.xn16_lo is the product with ~16 mantissa bits of x. -void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream, - uint16_t* xn16_lo = nullptr); -/// F-1: gr_norm without its FP32 output: the row scales rs[t*4 + c] and the BF16 image; gr_mix_r then reads R. -void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream, - uint16_t* xn16_lo = nullptr); -/// gr_mix with xn recomputed from R, rs and w_norm exactly as gr_norm computes it (the same bits). -void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16, - int64_t T, void* stream, uint16_t* mixed_h = nullptr, uint16_t* mixed16_lo = nullptr); -/// F-2: gr_write, then gr_norm_rs of the next half (its norm weights) over the rows just written - the same bits as -/// the two calls, without reading R back. -void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps, - float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr); -/// lo16[t, k] = bf16(silu(lo[t, k] / hc)) -void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo = nullptr); -/// mixed[t, d] = mean_c xn[t, c, d] * sigmoid(gated[t, c, d]); FP32, BF16 and FP16 (either image may be null). -void gr_mix(const float* xn, const float* gated, float* mixed, uint16_t* mixed16, int64_t T, void* stream, - uint16_t* mixed_h = nullptr, uint16_t* mixed16_lo = nullptr); -/// R[t, c, d] += bo[t, d] * 2 sigmoid(inj[t, c] / hc) (inj has row stride inj_ld) -void gr_write(float* R, const float* bo, const float* inj, int64_t inj_ld, int64_t T, void* stream); -/// R[t, c, :] = e[t, :] for all four streams (the embedding broadcast). -void gr_broadcast(const float* e, float* R, int64_t T, void* stream); - -// ---- the plain residual block (hc = 1: Qwen3.6). x = rms_norm(R, w) -> mixer -> R += out, per half. -/// mixed[t, :] = R[t, :] * rsqrt(mean R[t, :]^2 + eps) * w over rows of n, with its BF16 and FP16 images (any output -/// may be null); `mixed16_lo` as in gr_norm. -void rms_norm_images(const float* R, const float* w, float eps, float* mixed, uint16_t* mixed16, uint16_t* mixed_h, - int64_t T, int64_t n, void* stream, uint16_t* mixed16_lo = nullptr); -/// R[i] += bo[i] over n values (the residual write of a plain block). -void residual_add(float* R, const float* bo, int64_t n, void* stream); - -// ---- GDN (state 128, 4 taps; the head geometry per model: Flash-Next 48 v heads / 16 k heads / 10240 conv -// channels with the sigmoid(z) output gate, Qwen3.6 32 / 16 / 8192 with SiLU(z)). The kernels are built for those -// two geometries (gdn_geometry_supported); any other stops the process, as the kernels' convention is. The gate is -// the decode kernels' `GdnGate` (strata/kernels/gdn.hpp), from `ModelGeometry::gdn_gate()`: required, no default, so -// the prompt path and the decode path agree by construction. -struct GdnGeom { - int hv; ///< value heads (ssm_v_heads) - int hk; ///< key heads (ssm_k_heads); v-head h uses k-head h % hk - int c; ///< conv channels: 2 * hk * 128 + hv * 128 (q | k | v) - strata::kernels::GdnGate gate; ///< the output gate: Silu (Qwen3.6) or Sigmoid (Flash-Next) -}; -bool gdn_geometry_supported(int hv, int hk, int c); -/// gate[t,h] = softplus(ab[t,h] + dt[h]) * ssm_a[h]; beta[t,h] = sigmoid(ab[t, hv + h]) (ab: [T, 2 hv]) -void gdn_gates(const float* ab, const float* dt, const float* ssm_a, float* gate, float* beta, int64_t T, const GdnGeom& g, - void* stream); -/// The 4-tap causal conv + SiLU over the chunk (history [C][3] in, updated to the chunk's last three inputs), then -/// the L2 norm of the q and k heads of every token. h: [T, C]. -void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, int64_t T, float eps, const GdnGeom& g, - void* stream); -/// The recurrence over the chunk, state in registers; y16[t] = rmsnorm(o) * gamma * gate(z) in FP16 (what the -/// out projection reads; gate = sigmoid or SiLU per `g`); y is FP32 scratch. State: [128 k][hv][128 v] floats. -void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z, - const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, const GdnGeom& g, void* stream); - -// ---- MoE -/// softmax over n_expert, top-k (ties to the lower id), the k weights renormalised (the native router's semantics; -/// k <= 32 and k <= n_expert). 512 and 256 experts take the warp kernel, any other count router_top10. -void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, int64_t k, void* stream); -/// Expert blob (Strata pack layout, Q2_0) -> BF16 matrices: gate/up interleaved [1280, 2560], down [2560, 640]. -void blob_dequant(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream); -/// h16[n, r] = fp16(silu(gu[n, 2r]) * gu[n, 2r + 1]) (the interleaved expert gate/up, rows of 2 n_ff) -void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, int64_t n_ff, void* stream); -/// h16[n, r] = fp16(silu(g[n, r]) * u[n, r]) (the shared expert, gate and up separate, width n_ff) -void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, int64_t n_ff, void* stream); -/// 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); -/// dst[0, n) = src[0, n) in 16-byte loads (both 16-byte aligned; src may be mapped host memory: read over PCIe by -/// the kernel, not queued on a copy engine). -void copy_f32_wide(float* dst, const float* src, int64_t n, void* stream); -/// Gather rows: dst16[i, :] = x16[src[i], :] (n rows of `width` BF16). -void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, int64_t n, int64_t width, void* stream); -/// bo[t, :] = shared[t, :] * sigmoid(sg[t]) + sum_j w[t, j] * D[slot[t, j], :] over j < k, rows of n -void moe_combine(const float* D, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo, - int64_t T, int64_t n, int64_t k, void* stream); - -// ---- QSA helpers -/// In place: x[r, :] = x[r, :] * rsqrt(mean x^2 + eps) * w over rows of `cols` (row stride `ld`). -void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld, float eps, void* stream); -/// NEOX rotary on the first 64 dims of each head: x [T, heads, dim] at positions pos0 + t. The rope -/// scaling (rope_scaling.hpp) rides in as the process config - none is today's arithmetic exactly. -void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, - const strata::kernels::RopeScaling& scaling, void* stream); -/// q_full [T, n_head, 512] (q | gate per head) -> q [T, n_head, 256] -void split_q(const float* q_full, float* q, int64_t T, int64_t n_head, void* stream); -/// attn[t, h, d] *= sigmoid(q_full[t, h, 256 + d]) -> out16 (fp16 bits: the o-projection is quantized) -void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, int64_t n_head, void* stream); - -/// 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. -/// K, V: [T, 2, 256]. -void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const int32_t* page_table, int64_t page_size, - uint16_t* k_pool, uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, - void* stream, const strata::kernels::KvHostPools* host = nullptr, - const strata::kernels::KvHostPools* stage = nullptr); - -/// fp32 -> fp16 bits and fp32 -> bf16, n elements (the two activation images of the prompt GEMMs). -void to_f16(const float* x, uint16_t* y, int64_t n, void* stream); -void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream, uint16_t* ylo = nullptr); -/// y = fp32(fp16(x)): what an FP16 store of x would read back (the FP16 indexer-key experiment) -void round_f16(const float* x, float* y, int64_t n, void* stream); -/// Expert blob -> FP16 (Q2_0 values are exact in FP16). -void blob_dequant_f16(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream); - -} // namespace strata::prefill diff --git a/include/strata/prefill/moe_fused.hpp b/include/strata/prefill/moe_fused.hpp deleted file mode 100644 index a18590f..0000000 --- a/include/strata/prefill/moe_fused.hpp +++ /dev/null @@ -1,64 +0,0 @@ -// include/strata/prefill/moe_fused.hpp - #136 (prompt speed): the routed experts of a Q2_0 pack in the prompt path on -// Strata's own int8 tensor-core kernels, opt-in with STRATA_PF_FUSED=1 (NVIDIA sm_80 and newer; sm_75 and HIP: MMQ). -// -// The MMQ path (moe_mmq.hpp) per MoE layer: a host sync to group the (token, k) pairs by expert, a gather of each -// expert into a 16-expert group buffer, then per group the q8_1 activations of every routed slot, gate/up, SwiGLU, -// the q8_1 of H and down - five passes over per-slot buffers. Here: -// - the activations are rounded to int8 once per TOKEN (not per slot), with a scale per 32 values; -// - the grouping (counts, offsets, the rows of each expert, a list of 64-row tiles) runs on the GPU from the -// router's ids, so the host never waits for the routing; -// - one launch per batch of up to kMaxBatch experts reads each expert where it already is (a resident cache slot -// or a slot of the streamed ring: a pointer per expert, no gather) - gate/up with SwiGLU and the int8 rounding -// of H in its epilogue, then down into the per-slot rows the existing combine reads. -// The 2-bit codes are unpacked in registers and multiplied with mma.sync m16n8k32 (s8 x s8 -> s32); Q2_0's offset -// (w = d * (q - 1)) is folded into the activation blocks' sums. The numbers differ from MMQ's (another int8 -// rounding of the activations and of H) by about as much as MMQ differs from FP32 (tests/cuda/prefill_fused_moe_test). -#pragma once - -#include -#include - -namespace strata::prefill::fused { - -/// Routed rows (token, k pairs of one expert) per tile. -constexpr int kTileRows = 64; -/// Experts per launch: their blob pointers travel in the launch's parameters (1 KB). -constexpr int kMaxBatch = 128; - -/// This build has the kernels (a CUDA build; HIP and builds without MMQ do not). -bool built(); -/// built(), and the current device is sm_80 or newer (mma.sync with s8 operands at m16n8k32). -bool available(); -/// available(), unless STRATA_PF_FUSED=0 (read once): the Q2_0 pack's fused experts, on by default since 0.1.36. -bool enabled(); -/// STRATA_PF_FUSED=1 given explicitly, and available(): the native IQ packs' fused kernels (opt-in). -bool requested(); - -/// Bytes of `rows` activation rows of `cols` values (a multiple of 64) in the kernels' int8 form: per 64 values 64 -/// codes and {d, c} of each half (c = -(1.5 * 2^23 + the half's code sum), what the epilogue adds back). -size_t act_bytes(int64_t rows, int64_t cols); -/// Bytes of the grouping tables for `n` routed rows over `n_expert` experts. -size_t group_bytes(int64_t n, int n_expert); - -/// x [rows][cols] FP32 -> `xa` (act_bytes(rows, cols)). -void quantize_act(const float* x, int64_t rows, int64_t cols, void* xa, void* stream); - -/// The routing `ids` [n = tokens * k] -> per expert its rows (counts, offsets, the 64-row tile list, in `scratch`, -/// group_bytes(n, n_expert)), `slot[i]` = the row of pair i (the row of the per-slot outputs the combine reads) and -/// `src[row]` = its token (i / k). The order of the rows within an expert is not fixed; no output depends on it. -void group(const int32_t* ids, int64_t n, int k, int n_expert, void* scratch, int32_t* slot, int32_t* src, - void* stream); - -/// Experts [e0, e1) of one layer (e1 - e0 <= kMaxBatch); blob[e - e0]: the Strata Q2_0 blob of expert e on the -/// device (16-byte aligned), read only for an expert with rows. -struct Batch { - int e0 = 0, e1 = 0; - const uint8_t* blob[kMaxBatch] = {}; -}; -/// The batch's products: gate/up from `xa` (quantize_act of the layer's input, [tokens][2560]) through the rows -/// `src` of `group`, SwiGLU, H as int8 into `ha` (act_bytes(n, 640)), down into `dm` [n][2560] FP32 at the rows of -/// `group`. `n`: the layer's routed rows (tokens * k), which bounds the launch grid. -void experts(const Batch& b, int n_expert, int64_t n, const void* scratch, const void* xa, const int32_t* src, void* ha, - float* dm, void* stream); - -} // namespace strata::prefill::fused diff --git a/include/strata/prefill/moe_fused_iq.hpp b/include/strata/prefill/moe_fused_iq.hpp deleted file mode 100644 index 2ee1818..0000000 --- a/include/strata/prefill/moe_fused_iq.hpp +++ /dev/null @@ -1,43 +0,0 @@ -// include/strata/prefill/moe_fused_iq.hpp - #136: the fused int8 prompt experts (moe_fused.hpp) for the native GGUF -// packs (tools/iq_pack.py: an expert is its raw GGUF slices [gate rows | up rows | down rows], formats per layer in -// expert_layout().fmt), opt-in with the same STRATA_PF_FUSED=1 (NVIDIA sm_80 and newer; sm_75 and HIP: MMQ). -// -// The grouping on the GPU (fused::group), the per-expert pointers (fused::Batch: a cache slot or a ring slot, no -// gather) and the launch shape are the Q2_0 path's. What differs is the load stage: the i-quant blocks are decoded to -// int8 in shared memory before the mma (codebook and sign lookups, as llama.cpp's MMQ load_tiles does), with the -// block's scale per 32 (or per 16: IQ2_XS, IQ2_S, multiplied at m16n8k16) beside them. The activations and H are -// int8 per 32 values in their natural order here (quantize_act_native), not the Q2_0 path's permuted one. -// -// Covered: gate/up IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S, IQ4_XS; down Q2_0, IQ4_NL - every layer of the IQ2_XS, -// IQ3_XXS and IQ3_S packs but the IQ1_M ones (which MMQ does not cover either). Other layers keep MMQ. -#pragma once - -#include "strata/prefill/moe_fused.hpp" - -#include -#include - -namespace strata::prefill::fused { - -/// One layer's native expert geometry (cpu::NativeFmt's fields the kernels read). The widths are the model's -/// (Flash-Next 2560 / 640, Qwen3.6 2048 / 512): n_embd a multiple of 256, n_ff of 64, and 2 n_ff a multiple of 256. -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. -bool native_supported(int gu_type, int d_type); - -/// x [rows][cols] FP32 -> `xa` (act_bytes(rows, cols)): int8 per 32 values in natural order, the native kernels' form. -void quantize_act_native(const float* x, int64_t rows, int64_t cols, void* xa, void* stream); - -/// experts() for native blobs: b.blob[e - e0] is the native blob of expert e (gate at 0, up at g.up_off, down at -/// g.down_off; 2-byte aligned). `xa` from quantize_act_native; H in `ha` (act_bytes(n, 640)); down into `dm` at the -/// rows of `group`. -void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n, const void* scratch, const void* xa, - const int32_t* src, void* ha, float* dm, void* stream); - -} // namespace strata::prefill::fused diff --git a/include/strata/prefill/moe_mmq.hpp b/include/strata/prefill/moe_mmq.hpp deleted file mode 100644 index 0859dca..0000000 --- a/include/strata/prefill/moe_mmq.hpp +++ /dev/null @@ -1,88 +0,0 @@ -// include/strata/prefill/moe_mmq.hpp - prompt-speed plan step 2b: the prompt path's experts through llama.cpp's MMQ -// kernels (ggml-cuda mmq.cuh, MIT): the weights stay quantized and the activations are rounded to q8_1, the -// products run on int8 tensor cores. The dequantize-to-FP16 + cuBLAS path wrote ~10 MB of FP16 per expert and -// multiplied in FP16; this reads the ~1.4-2 MB expert once. A group of experts is gathered into one buffer -// (`gather_*`, one launch per expert as its blob arrives) and multiplied in one launch per product. -#pragma once - -#include -#include - -namespace strata::prefill::mmq { - -/// This build has the MMQ path (the ggml sources were available to the build). -bool built(); -/// MMQ covers this ggml type (the i-quants and Q2_0 the packs use, Q8_0, and in a CUDA build with STRATA_MMQ_KQUANTS -/// the Q4_K / Q5_K / Q5_1 of Unsloth's UD-Q4_K_XL; IQ1_M is not covered). -bool supported(int ggml_type); -/// #420: `supported`, and on every visible GPU llama.cpp's MMQ has a tile for this type and a weight matrix of -/// `w_rows` rows that fits the card's shared memory - the same test its tile choice makes, which aborts the process -/// ("J_best=0") when nothing fits. false (said once per type) keeps that product on the non-MMQ path. -bool fits(int ggml_type, int64_t w_rows); -/// Bytes of one expert's gate+up ([2*n_ff, n_embd]) or down ([n_embd, n_ff]) weights in `ggml_type`. -size_t matrix_bytes(int ggml_type, int64_t rows, int64_t cols); -/// Bytes of `rows` activation rows of `cols` values quantized for MMQ (the row padded to 512 values). -size_t q8_bytes(int64_t rows, int64_t cols); - -/// q8_1 activations for MMQ against weights of `ggml_type`: row i of the output is row ids[i] of x (or row i when -/// ids is null); `x` has `ld` floats per row. -void quantize(const float* x, const int32_t* ids, void* xq, int ggml_type, int64_t cols, int64_t ld, int64_t rows, - void* stream); - -/// One launch over n experts whose weights lie `expert_bytes` apart from `w`: for expert e, the activation rows -/// [bounds[e], bounds[e+1]) of `xq` (bounds on the device, n+1 entries) times its [w_rows, w_cols] matrix into -/// dst rows of the same indices (`ld_dst` floats apart, via `ids`: dst row = ids[row], an identity table works). -/// `total_rows`: the rows of xq; `max_rows`: the most rows one expert has (the launch grid). -struct Product { - const void* w = nullptr; - int type = -1; - int64_t w_rows = 0, w_cols = 0; - size_t expert_bytes = 0; - int n = 0; - const void* xq = nullptr; - const int32_t* bounds = nullptr; - const int32_t* ids = nullptr; - int64_t total_rows = 0, max_rows = 0; - float* dst = nullptr; - int64_t ld_dst = 0; -}; - -/// The launch context (llama.cpp's MMQ keeps a small scratch pool for its stream-k fixup). One per prompt path. -class Context { -public: - Context(); - ~Context(); - Context(const Context&) = delete; - Context& operator=(const Context&) = delete; - void run(const Product& p, void* stream); - -private: - void* ctx_ = nullptr; -}; - -/// A GGUF-native expert (gate at `gate`, up at `up`, down at `down`, each its GGUF rows) into a group buffer's -/// slot: gate rows then up rows at `gu_dst`, down at `d_dst`. -void gather_native(const void* gate, const void* up, size_t gu_half_bytes, const void* down, size_t d_bytes, - void* gu_dst, void* d_dst, void* stream); -/// gather_native for an MMQ group's experts [first, n) in ONE launch: expert q's blob (`blob[q]`; gate at +0, up at -/// +up_off, down at +down_off) to gu_dst + q * gu_stride and d_dst + q * d_stride - the same bytes as one gather_native -/// each. Every pointer, offset and size 16-byte aligned (false otherwise: nothing launched, gather one at a time). -constexpr int kGatherGroupMax = 16; -struct GatherGroup { - const uint8_t* blob[kGatherGroupMax] = {}; - int first = 0, n = 0; -}; -bool gather_native_group(const GatherGroup& g, size_t up_off, size_t gu_half_bytes, size_t down_off, size_t d_bytes, - void* gu_dst, size_t gu_stride, void* d_dst, size_t d_stride, void* stream); -/// A Strata-pack Q2_0 expert blob (codes and fp16 scales in separate planes, gate/up rows interleaved) into GGUF -/// Q2_0 blocks: gate/up [1280, 2560] at `gu_dst` (rows stay interleaved), down [2560, 640] at `d_dst`. Same values. -void gather_strata_q2(const uint8_t* blob, void* gu_dst, void* d_dst, void* stream); - -/// h[r, k] = silu(gate) * up of GU rows [2 n_ff wide]: interleaved (gate 2k, up 2k+1: the Strata pack) or split -/// (gate k, up n_ff + k: GGUF). FP32 out (the down product's quantizer reads floats). -void swiglu(const float* gu, float* h, int64_t rows, int64_t n_ff, bool interleaved, void* stream); - -/// dst[i] = i for i < n (the identity row map MMQ's MoE mode writes through). -void iota(int32_t* dst, int64_t n, void* stream); - -} // namespace strata::prefill::mmq diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp deleted file mode 100644 index 9b6a03e..0000000 --- a/include/strata/prefill/prefill.hpp +++ /dev/null @@ -1,195 +0,0 @@ -// include/strata/prefill/prefill.hpp - plan v0.3 P5: batched prompt processing. -// -// The prompt's positions [pos0, pos0 + n) are processed in chunks of `chunk` tokens through all 48 layers, leaving -// the session state (GDN recurrence and conv state, QSA KV pools and indexer, PLE history) where the token path -// would have left it; the decode loop then continues with the next token. Per layer: the projections are -// tensor-core GEMMs (quantized weights dequantized to FP16 on the fly, BF16 weights as they are), the recurrences -// walk the chunk inside one kernel, and the routed experts are grouped by expert: resident ones are read from the -// VRAM tier, the others streamed from the host arena through a pinned ring on a copy stream. -// -// Requires the native weights (`--native`): every quantized projection must carry its GGUF blocks. -#pragma once - -#include "strata/core/expert_cache.hpp" -#include "strata/core/expert_source.hpp" -#include "strata/core/layer.hpp" -#include "strata/core/session.hpp" -#include "strata/core/weights.hpp" - -#include -#include -#include -#include -#include - -namespace strata::core { class PeerExperts; } - -namespace strata::prefill { - -struct PrefillStats { - int64_t tokens = 0; - int64_t chunks = 0; - double ms_total = 0; - double ms_experts_host = 0; ///< host time staging non-resident experts - int64_t experts_streamed = 0; ///< expert blobs copied host -> device - int64_t experts_dma = 0; ///< ...of which straight from the pinned arena (no CPU copy) - int64_t experts_resident = 0; ///< expert-layer groups served from the VRAM tier - double ms_ple = 0; -}; - -} // namespace strata::prefill -namespace strata::core { class MtpDrafter; } -namespace strata::prefill { - -class Prefill { -public: - /// E-9: the draft layer's K/V for prompt cells [cell0, cell0 + n) from their final residual rows `R_rows` - /// (device) and `next_tokens` (host: the token at cell+1), in batches through this path's GEMMs and its idle - /// scratch - call it from on_chunk. false with `err` empty: not applicable here (a ring or hybrid K/V, another - /// device, too little scratch; STRATA_MTP_BATCH=0), the caller runs the drafter's own pass. Not bit-identical to - /// that pass (FP16 GEMMs instead of Q8_1 activations): the drafts may differ, never the target's tokens' logits. - bool draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, - std::string& err); - Prefill(); - ~Prefill(); - Prefill(const Prefill&) = delete; - Prefill& operator=(const Prefill&) = delete; - - /// Frees every buffer, stream and event `init` made (as the destructor does) and starts over empty, so `init` can - /// run again - with a smaller chunk when the first one did not fit. The stage range (`set_stage`) and the - /// callbacks stay. The device `init` ran on must be current. - void reset(); - - /// `host_res`: the static residency table (n_layers x n_expert, slot or -1) or null; `cache` its slots. - /// `borrow`/`borrow_bytes`: device memory to carve every buffer from (the top slots of the expert cache, - /// lent for the prompt and refilled after it); null = allocate normally. - bool init(const core::WeightTable& wt, const core::ModelGeometry& g, core::SessionState& ss, - core::ExpertSource* src, const core::ExpertCache* cache, const int32_t* host_res, int64_t chunk, - void* stream, std::string& err, void* borrow = nullptr, uint64_t borrow_bytes = 0); - - /// With borrowed buffers: lay them out again for chunks of `chunk` tokens (at most `init`'s) in `borrow` - a - /// request lends only the slots its prompt needs. The stream must be idle (between prompts). - bool relayout(int64_t chunk, void* borrow, uint64_t borrow_bytes, std::string& err); - int64_t chunk() const; - - /// The share of the streamed experts' bytes DMA-able straight from pinned RAM (1 = all). Sizes the streamed - /// ring (a big one only pays when the copy engine, not the host copies, is the limit); set before bytes_needed. - static void set_pinned_share(double share); - static double pinned_share(); - /// #340: the streamed ring's slot count for chunks that stream every expert, instead of the pinned-share rule - /// (0 = that rule). Set before any `bytes_needed`/`init` (both count the ring); STRATA_PREFILL_RING still wins. - static void set_ring_override(int slots); - /// #583: the auto chunk scan's byte-budget ring, for chunks above `small_max` (0.1.39's auto chunk: a prompt that - /// fits it keeps 0.1.39's ring). 0 slots = none. A layer split's set_ring_override and STRATA_PREFILL_RING win. - static void set_ring_budget(int slots, int64_t small_max); - - /// Device bytes `init` needs for a chunk of `chunk` tokens (what a borrowed region must hold). - static uint64_t bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk); - - /// The same without the streamed ring: what the chunk's own buffers cost. The auto chunk scan sizes the chunk - /// first and hands the ring what the chunk leaves over, so it needs the chunk priced on its own. - static uint64_t bytes_needed_no_ring(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk); - - /// The streamed ring's byte budget as a slot count for this pack (the measured slot count x Q2_0's blob, over - /// max_blob, never past ring_cap()): - /// what the auto chunk scan treats as a full ring. A slot is one whole blob, so a pack with bigger blobs than - /// Q2_0's gets fewer of them for the same bytes - 384 on Q2_0, 199 on a 2.54 MiB-blob IQ3_S pack. - static int64_t ring_max_slots(); - /// 0.1.39's ring for this PC (1024 fused / 384 pinned / 96), within ring_cap(). - static int64_t ring_default_slots(); - /// #583: the ring the auto scan keeps full, given the chunk 0.1.39's rule picked: its byte budget where that rule's - /// chunk was small (< 6144), else 0.1.39's ring (measured: shrinking it for a bigger chunk lost there). - static int64_t ring_cap_for(int64_t old_chunk); - - /// What the ring actually resolves to for a chunk of `chunk` tokens, after the override, STRATA_PREFILL_RING - /// and the pinned-share rule - the slot count `init` lays out. The engine reports it on its INFO line so the - /// Monitor tab shows the pair the run really got, not what it asked for. - static int64_t ring_slots_for(int64_t chunk); - - /// 0.1.39b (#583, the default): the ring as a byte budget, the loan's corrected count and the auto chunk scan that - /// keeps the ring full. STRATA_RING_BYTES=0: 0.1.39's ring, loan and chunk list. - static bool ring_bytes_enabled(); - - /// Positions [pos0, pos0 + n) holding `tokens`; `ss.ple_prev` must be the two tokens before pos0 (oldest - /// first, -1 for none) and is advanced to the last two of these. - bool run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err); - - const PrefillStats& stats() const { return stats_; } - - /// multi-GPU: the experts the peer GPU holds are computed THERE for every prompt chunk (up to `cap_rows` routed - /// rows per layer; the rest of the peer's experts are read by this GPU over P2P). Allocates the peer's buffers for - /// chunks of up to init's `chunk` tokens. Needs P2P between the two cards. - bool set_peer(core::PeerExperts* peer, int64_t cap_rows, std::string& err); - - /// Plan v0.3 P6: called after every chunk with the chunk's final multi-stream residual rows (device, - /// T x hc*n_embd, valid until the next chunk) and the chunk's first position; the MTP draft layer builds its - /// K/V from them. The prefill stream is synchronized before the call. - std::function on_chunk; - - /// Layer split: called by every stage when it has read a chunk, with the position reached, while its own state - /// is still at that chunk's end (its stream synchronized; the last stage calls it just before `on_chunk`). An - /// earlier stage is a chunk or more ahead of the last one by the time `on_chunk` runs, so this is where a - /// mid-prompt checkpoint takes each stage's part. Runs on that stage's thread, with its device current. - std::function on_stage_chunk; - - /// Checked before every chunk: true stops the prompt early (`run` returns false with err "cancelled"). - std::function 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 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; - - /// LAYER SPLIT (multi-GPU): this prompt path runs layers [layer_begin, layer_end) (-1: to the last) on the - /// device `init` runs on. A stage that does not start at layer 0 reads each chunk's residual rows from the - /// previous stage instead of embedding the tokens; a stage that does not end at the last layer copies its rows - /// to pinned host buffers (two, allocated by `init`) and runs `next` on them - on a thread, so the next stage - /// reads chunk c while this one reads chunk c + 1. `on_chunk` belongs on the last stage. Set before `init`. - void set_stage(int64_t layer_begin, int64_t layer_end, Prefill* next) { - stage_lb_ = layer_begin; stage_le_ = layer_end; next_ = next; - } - - /// LAYER SPLIT: `helper` is another stage's prompt path (another GPU). A prompt of one chunk runs the stages one - /// after the other, so while this stage reads it the helper's GPU idles: it then streams a share of this stage's - /// non-resident experts over its own PCIe link into its own (lent) prompt buffers, computes their rows, and sends - /// them back - the --peer-device peer's streaming, without P2P (activations and rows through mapped host memory, - /// read by copy kernels). Only on the MMQ prompt path, only for chunks of stream_all_min() tokens and more, up to - /// the size where the measured share stops paying. Opt-in: STRATA_PREFILL_HELP=1 (not bit-identical to the default). Both stages must have - /// run `init`. - bool set_stage_helper(Prefill* helper, std::string& err); - -private: - // Stage-1 pipeline: intermediate stages return after handing their chunk to - // the direct successor. The public run() drains the chain once at prompt end. - bool run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err); - bool drain_pipeline(std::string& err); - - int64_t stage_lb_ = 0, stage_le_ = -1; - Prefill* next_ = nullptr; - Prefill* helper_ = nullptr; ///< set_stage_helper - bool single_chunk_ = false; ///< a later stage: the prompt is one chunk (set by the stage before) - bool bind_stage_helper(int64_t T); // binds the helper's buffers for a one-chunk prompt of T tokens - const float* hand_in_ = nullptr; ///< the previous stage's rows of the chunk being read (host, pinned) - - std::string next_err_; - std::future next_run_; - int hand_buf_ = 0; - - bool carve(std::size_t T, void* alloc); // the device buffers of a chunk (prefill.cpp's Alloc) - void release(); // the destructor's cleanup (also `reset`'s) - struct Impl; - std::unique_ptr impl_; - PrefillStats stats_; -}; - -} // namespace strata::prefill diff --git a/include/strata/program/conv_cache.hpp b/include/strata/program/conv_cache.hpp deleted file mode 100644 index 7fe4bfa..0000000 --- a/include/strata/program/conv_cache.hpp +++ /dev/null @@ -1,43 +0,0 @@ -// include/strata/program/conv_cache.hpp - the conversation cache's retention policy: which checkpoint -// leaves when the cache is over its slot budget. -// -// The cache holds conversation checkpoints: snapshots of the running state (the GDN recurrence, the PLE -// history, the QSA indexer tails - `ConvCheckpoint` in generate.cpp) that a request resumes its prompt -// from instead of reading those tokens again. The request path keeps only the checkpoints whose tokens -// are a prefix of the current prompt - any other checkpoint's positional cells have been overwritten, -// because the KV cache is one arena that holds one branch of history at a time - so at any moment the -// retained checkpoints are a CHAIN: sorted by length, each a prefix of the next. That is a radix cache's -// tree collapsed onto the one branch of history the session can hold. -// -// The chain's root is therefore the deepest point every request so far has shared - in practice the end -// of the system prompt, which every new chat of the same client mounts through - and it is exactly the -// node a radix cache keeps alive while its leaves rotate. First-in-first-out kept it only by accident of -// being first: after `prompt_cache` newer checkpoints it was gone, and the next chat read the whole -// prefix again at prefill speed. So: -// -// * the root is PINNED: dropping it frees one slot's ~118 MB and costs every future conversation that -// shares the prefix a full re-read of it (a 30K system prompt is ~30 s at ~1,000 tok/s); -// * every other slot rotates by least recent use. A checkpoint's stamp advances when it is created, -// when a new checkpoint lands on its length, and when a request mounts through it. -// -// With a budget below two slots there is no room to keep root and leaf apart, so the pin switches off and -// the oldest checkpoint leaves - the previous behaviour, one slot = the newest point only. -#pragma once - -#include -#include - -namespace strata::program::conv_cache { - -/// The index in `stamps` of the chain item to drop once the chain holds more than `cap` items. `stamps` -/// are the items' last-use stamps; the caller owns the chain and erases the returned index. Pure and -/// deterministic so conv_cache_test.cpp can walk the scenarios by hand. -inline size_t eviction_victim(const uint64_t* stamps, size_t n, int64_t cap) { - if (cap < 2 || n < 2) return 0; // no room for root and leaf: the pin is off, the oldest leaves - size_t v = 1; // the root (0) is pinned; least recent use among the rest - for (size_t i = 2; i < n; ++i) - if (stamps[i] < stamps[v]) v = i; - return v; -} - -} // namespace strata::program::conv_cache diff --git a/include/strata/program/logits_selection.hpp b/include/strata/program/logits_selection.hpp deleted file mode 100644 index 04462a8..0000000 --- a/include/strata/program/logits_selection.hpp +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace strata::program::logits_selection { - -// Storage selection only: callers must still condition on every input token. -// Positive decimal int64, with no sign, whitespace, suffix or overflow. -inline bool parse_stride(std::string_view text, int64_t& result) { - if (text.empty() || text.front() < '0' || text.front() > '9') return false; - int64_t value = 0; - const auto parsed = std::from_chars(text.data(), text.data() + text.size(), value); - if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size() || value <= 0) return false; - result = value; - return true; -} - -// Zero-based multiples of stride, followed by the final input position once. -inline constexpr bool selected(int64_t position, int64_t total, int64_t stride) { - return total > 0 && stride > 0 && position >= 0 && position < total && - (position % stride == 0 || position == total - 1); -} - -inline constexpr int64_t row_count(int64_t total, int64_t stride) { - return total > 0 && stride > 0 ? (total - 1) / stride + 1 + ((total - 1) % stride != 0) : 0; -} - -} // namespace strata::program::logits_selection diff --git a/include/strata/spec/controller.hpp b/include/strata/spec/controller.hpp deleted file mode 100644 index 4864ce9..0000000 --- a/include/strata/spec/controller.hpp +++ /dev/null @@ -1,73 +0,0 @@ -// include/strata/spec/controller.hpp - plan v0.3 P6: which drafter, and how many draft tokens, this step. -// -// Each step the controller maximizes E[tokens committed] / T(step) over the choices -// none (k = 0) | suffix lookup with k <= its proposal | MTP with k <= K_MAX -// using running estimates of per-position acceptance and a cost model of a (k+1)-token verify pass. It keeps -// k = 0 unless the best choice beats plain decoding by `min_gain` (plan: 5%). -// -// Acceptance: for MTP, position i's conditional acceptance p_i (EMA). For lookup, one conditional acceptance per -// match-length bucket (a long match is far more reliable than a trigram), also an EMA. `observe` updates them -// from how many drafted tokens the verify pass accepted. -// -// Cost: T(n tokens) = dense(n) + experts(n) + sync + draft. The defaults are the 23 Sep measurements: -// dense ratio per token count from native MMVQ (bench/results/2026-09-23-mmvq-multi), distinct experts per window -// from the routing trace (2026-09-23-spec-economics), extra-token CPU cost 0.2-0.35 (2026-09-23-cpu-expert-multi). -// Replace them with in-engine measurements through `CostModel`. -#pragma once - -#include -#include - -namespace strata::spec { - -inline constexpr int K_MAX = 8; - -struct CostModel { - double dense_ms = 11.0; // one-token dense pass (plan P3 target) - std::array dense_ratio{1.0, 1.05, 1.3, 1.45, 1.85, 2.2, 2.6, 3.0, 3.3}; // by n = k+1 (index n-1) - double cpu_all_miss_ms = 15.8; // 480 experts on the CPU - double hit_rate = 0.55; // share of distinct experts served from VRAM - std::array distinct_ratio{1.0, 1.70, 2.31, 2.88, 3.40, 3.89, 4.35, 4.80, 5.2}; // U(n)/U(1) - double extra_use_cost = 0.25; // each extra token on an expert, fraction of a read - double sync_ms = 2.4; - double mtp_draft_ms = 1.2; // per MTP draft token - double lookup_draft_ms = 0.01; - - /// Step time for verifying n = k + 1 tokens, plus drafting k tokens with the given source. - double step_ms(int k, bool mtp) const; -}; - -enum class Source { None, Lookup, Mtp }; - -struct Choice { - Source source = Source::None; - int k = 0; - double expected_tokens = 1.0; - double tokens_per_ms = 0.0; -}; - -class Controller { -public: - explicit Controller(CostModel cost = {}, double min_gain = 0.05, double ema = 0.05); - - /// `lookup_available` tokens the suffix drafter can propose now, from a match of `lookup_match` tokens. - Choice choose(int lookup_available, int lookup_match, bool mtp_ready) const; - - /// After verification: `accepted` of the `k` drafted tokens matched (a prefix). - void observe(const Choice& c, int accepted, int lookup_match); - - double mtp_accept(int position) const { return mtp_p_[position]; } // position 0 = first draft token - double lookup_accept(int match) const { return lookup_q_[bucket(match)]; } - const CostModel& cost() const { return cost_; } - -private: - static int bucket(int match) { return match >= 16 ? 3 : match >= 8 ? 2 : match >= 5 ? 1 : 0; } - static double expected(const double* p, int k, bool conditional_same); - - CostModel cost_; - double min_gain_, ema_; - std::array mtp_p_{}; - std::array lookup_q_{}; -}; - -} // namespace strata::spec diff --git a/include/strata/spec/draft_policy.hpp b/include/strata/spec/draft_policy.hpp deleted file mode 100644 index c77b869..0000000 --- a/include/strata/spec/draft_policy.hpp +++ /dev/null @@ -1,52 +0,0 @@ -// include/strata/spec/draft_policy.hpp - per verify round: the MTP's window, or a lookup (suffix) window? -// -// The suffix drafter (prompt lookup) proposes the tokens that followed an earlier repeat of the context. Taken -// whenever it proposes more than the MTP, it lost 2-8% on ordinary text: a long lookup window costs much more to -// verify than the MTP's usual 3-4 tokens, and it is only worth that when enough of it is accepted. llama.cpp's -// lookup decoding answers the same problem with confidence thresholds on its n-gram statistics; here the policy -// learns both sides online and compares expected committed tokens per millisecond: -// -// MTP E = the mean tokens a window of that size has committed (EMA), at the measured cost of that size -// lookup E(k) = 1 + q + q^2 + ... + q^k for k <= the proposal, q = the acceptance rate of lookup drafts whose -// match was about as long (4 buckets of match length, decayed counts), at the measured cost of k + 1 -// -// and takes the lookup window only when its best E/cost beats the MTP's by `margin`. Costs are the measured round -// times per window size (EMA; sizes not seen yet are scaled from seen ones by a prior shape), so the policy adapts -// to the machine and the context length. It only chooses which drafts to verify: the output is unchanged. -#pragma once - -#include - -namespace strata::spec { - -class DraftPolicy { -public: - static constexpr int kMaxT = 8; - static constexpr int kBuckets = 4; - - explicit DraftPolicy(int max_t, double margin = 0.03); - - struct Pick { - bool lookup = false; - int t = 1; // window size (1 + drafts) - }; - /// `t_mtp`: the MTP's window; `lookup_k`: the lookup proposal's length (0 = none); `match`: its match length. - Pick choose(int t_mtp, int lookup_k, int match) const; - /// After the round: the window it used, the drafts accepted, and the round's time (verify + commit + draft). - void observe(bool lookup, int t, int accepted, int match, double round_ms); - - double lookup_rate(int match) const; // current q for a match length - double cost_ms(int t) const; // measured or scaled round time of a window of t tokens - -private: - static int bucket(int match); - double mtp_tokens(int t) const; - - int max_t_; - double margin_; - std::array cost_{}, cost_n_{}; // round ms by window size - std::array mtp_tok_{}, mtp_n_{}; // tokens committed by MTP windows of that size - std::array ok_{}, bad_{}; // lookup drafts accepted / windows cut short, decayed -}; - -} // namespace strata::spec diff --git a/include/strata/spec/suffix_drafter.hpp b/include/strata/spec/suffix_drafter.hpp deleted file mode 100644 index 731bbef..0000000 --- a/include/strata/spec/suffix_drafter.hpp +++ /dev/null @@ -1,53 +0,0 @@ -// include/strata/spec/suffix_drafter.hpp - plan v0.3 P6: the suffix-lookup drafter (no weights, no GPU). -// -// Proposes the tokens that followed the longest earlier occurrence of the sequence's current suffix: when the -// output quotes its input (edits, refactors, repeated code) the continuation is usually exact, and a verify pass -// accepts many tokens at once. It needs no model and costs microseconds. -// -// Index: every trigram of the history (prompt + accepted output) maps to its WAYS most recent end positions in a -// fixed-size open-addressing table, so memory is bounded (~20 bytes per history token) and appends are O(1). -// A proposal checks those candidates, extends each match backwards up to `max_match`, and takes the longest -// (most recent on ties). Matches shorter than `min_match` propose nothing. -#pragma once - -#include -#include -#include - -namespace strata::spec { - -class SuffixDrafter { -public: - static constexpr int WAYS = 4; - - explicit SuffixDrafter(int min_match = 3, int max_match = 32, size_t capacity_tokens = 1u << 19); - - void reset(); - /// Add tokens to the history (the prompt, then every accepted token). - void append(const int32_t* tokens, size_t n); - void append(int32_t token) { append(&token, 1); } - - /// Write up to `max_k` proposed next tokens to `out`; returns how many (0 = no match of at least min_match). - int propose(int max_k, int32_t* out); - - /// Length of the match behind the last proposal (0 if none). - int last_match() const { return last_match_; } - size_t size() const { return hist_.size(); } - -private: - struct Slot { - uint64_t key = 0; // trigram hash + 1 (0 = empty) - uint32_t pos[WAYS] = {}; // end positions, most recent first - uint8_t n = 0; - }; - Slot* find_slot(uint64_t key, bool insert); - uint64_t key_at(size_t end) const; - - int min_match_, max_match_; - std::vector hist_; - std::vector table_; - size_t mask_ = 0; - int last_match_ = 0; -}; - -} // namespace strata::spec diff --git a/patches/llama.cpp-qwen3-coder-any-argument-order.patch b/patches/llama.cpp-qwen3-coder-any-argument-order.patch deleted file mode 100644 index 683bd32..0000000 --- a/patches/llama.cpp-qwen3-coder-any-argument-order.patch +++ /dev/null @@ -1,26 +0,0 @@ -diff --git a/common/parsers/qwen3-coder.cpp b/common/parsers/qwen3-coder.cpp -index 208f551..2d7c80f 100644 ---- a/common/parsers/qwen3-coder.cpp -+++ b/common/parsers/qwen3-coder.cpp -@@ -139,12 +139,15 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat - (param.required ? required_args : optional_args).push_back(arg_rule); - }); - -- // Accept required arguments in any order, as Qwen does not always adhere to the -- // order provided. -- auto args = p.permute("tool-" + name + "-args", required_args); -- if (!optional_args.empty()) { -- args = args + p.zero_or_more(p.choice(optional_args)); -- } -+ // Accept the arguments in any order, required and optional interleaved. The upstream rule -+ // took the required ones first and the optional ones after; Qwen3.8 Flash-Next often writes -+ // the optional ones first (limit, offset, path), and because the tool-call group below is -+ // optional and the grammar has no end anchor, such a call was dropped without any error: -+ // the client got finish_reason=stop and an empty answer. Whether every required argument -+ // is present is for the tool to report; a dropped call reports nothing. -+ std::vector all_args = required_args; -+ all_args.insert(all_args.end(), optional_args.begin(), optional_args.end()); -+ auto args = all_args.empty() ? p.eps() : p.zero_or_more(p.choice(all_args)); - - auto func = p.tool(p.tool_open("\n") + - p.tool_args(args) + diff --git a/ref/load.py b/ref/load.py deleted file mode 100644 index 88f26b5..0000000 --- a/ref/load.py +++ /dev/null @@ -1,217 +0,0 @@ -"""ref/load.py - P1.S4: GGUF -> FP32 tensors on demand, with LAZY per-expert dequantization. - -The plan is explicit: "experts are dequantized lazily per (layer, expert) - do not materialize 120B -parameters". That is the whole design constraint here, and it is what `expert()` below exists for: the -routed-expert tensors are fused `[in, out, experts]`, and touching one expert must not touch the other -511. - -Dequantization itself is NOT reimplemented. `gguf-py` handles the twelve standard encodings and is -already the reference this project validates its C++ against; `Q2_0` (type 42) is the one gguf-py -cannot represent at all, so it is served by this project's own decoder. That split is deliberate: it -means a bug in `tools/gguf_writer.dequantize_q2_0` cannot hide behind gguf-py and vice versa. - - from ref.load import Gguf - g = Gguf("path.gguf") - w = g.tensor("blk.0.attn_gate.weight") # (out, in) fp32, whole tensor - e = g.expert("blk.0.ffn_gate_exps.weight", 7) # (out, in) fp32, ONE expert only -""" -from __future__ import annotations - -import pathlib -import re -import sys - -import numpy as np - -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "tools")) -from gguf_reader import GGUFFile # noqa: E402 -from gguf_writer import dequantize_q2_0 # noqa: E402 - -# gguf-py names differ from our reader's names in a few places; map only what differs. -_GGUF_PY_NAME = {"Q4_0": "Q4_0", "Q8_0": "Q8_0", "Q4_K": "Q4_K", "Q5_K": "Q5_K", "Q6_K": "Q6_K", - "Q3_K": "Q3_K", "IQ4_NL": "IQ4_NL", "IQ4_XS": "IQ4_XS", "Q5_0": "Q5_0", - # added for Qwen3.6 (UD-IQ3_XXS ships IQ2_S gate/up and IQ3_XXS down experts; the MTP build IQ3_S / Q3_K / Q4_K): - "Q4_1": "Q4_1", "Q5_1": "Q5_1", "Q2_K": "Q2_K", "IQ2_XXS": "IQ2_XXS", "IQ2_XS": "IQ2_XS", - "IQ2_S": "IQ2_S", "IQ3_XXS": "IQ3_XXS", "IQ3_S": "IQ3_S", "IQ1_S": "IQ1_S", "IQ1_M": "IQ1_M"} - -# (elements per block, bytes per block) - mirrors block_geometry() in src/artifact/gguf_reader.cpp -GEOM = {"F32": (1, 4), "F16": (1, 2), "BF16": (1, 2), - "Q4_0": (32, 18), "Q5_0": (32, 22), "Q8_0": (32, 34), "IQ4_NL": (32, 18), - "Q3_K": (256, 110), "Q4_K": (256, 144), "Q5_K": (256, 176), "Q6_K": (256, 210), - "IQ4_XS": (256, 136), "Q2_0": (64, 18), - "Q4_1": (32, 20), "Q5_1": (32, 24), "Q2_K": (256, 84), "IQ2_XXS": (256, 66), "IQ2_XS": (256, 74), - "IQ2_S": (256, 82), "IQ3_XXS": (256, 98), "IQ3_S": (256, 110), "IQ1_S": (256, 50), "IQ1_M": (256, 56)} - - -def _dequant_flat(type_name: str, raw: np.ndarray) -> np.ndarray: - """One dequantization dispatch, shared by tensor()/expert()/rows(). - - Q2_0 is this project's own decoder because gguf-py's enum cannot represent type 42 at all; - everything else goes through gguf-py, which is already the reference this project validates its - C++ against. Keeping one dispatch means a type added in one path cannot be forgotten in another. - """ - if type_name == "Q2_0": - return dequantize_q2_0(raw.tobytes()) - if type_name == "BF16": - return _bf16_to_f32(raw) - if type_name == "F32": - return raw.view(np.float32) - if type_name == "F16": - return raw.view(np.float16).astype(np.float32) - from gguf import quants, GGMLQuantizationType as Q - return quants.dequantize(raw, Q[_GGUF_PY_NAME[type_name]]).astype(np.float32) - - -def _bf16_to_f32(raw: np.ndarray) -> np.ndarray: - return (raw.view(np.uint16).astype(np.uint32) << 16).view(np.float32) - - -def _discover_shards(path) -> list[pathlib.Path]: - """Resolve a GGUF argument to its shard list. - - The real artifact is TWO files and the split is not incidental: shard 2 holds exactly one tensor, - `per_layer_token_embd.weight` (26.82 GiB). A reader that opens one file can therefore load the - whole model EXCEPT the PLE table and will not fail until a forward pass reaches layer 1 - so - shard discovery is not a convenience, it is a correctness requirement for the real model. - - Accepts a directory (all `*.gguf` in it), any single shard (siblings found by the - `-NNNNN-of-MMMMM` suffix), or an explicit list. - """ - if isinstance(path, (list, tuple)): - return [pathlib.Path(p) for p in path] - p = pathlib.Path(path) - if p.is_dir(): - # A directory is ambiguous in practice: the project root holds BOTH the model shards (in a - # subdirectory) and an unrelated `mmproj-*.gguf`. Globbing `*.gguf` there silently loaded - # the multimodal projector instead of the model. So prefer an explicit shard set, accept a - # single unambiguous file, and REFUSE to guess otherwise. - shards = sorted(p.glob("*-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9].gguf")) - if shards: - totals = {re.match(r"^.*-(\d{5})-of-(\d{5})\.gguf$", s.name).group(2) for s in shards} - if len(totals) != 1: - raise ValueError(f"{p}: shard files from more than one split: {sorted(totals)}") - return shards - found = sorted(p.glob("*.gguf")) - if len(found) == 1: - return found - if not found: - raise FileNotFoundError(f"no .gguf files in {p}") - raise ValueError( - f"{p}: {len(found)} .gguf files and none is a shard set, so which is the model is " - f"ambiguous: {[f.name for f in found]}. Pass one file explicitly.") - m = re.match(r"^(.*)-(\d{5})-of-(\d{5})\.gguf$", p.name) - if m: - stem, _, total = m.groups() - sibs = sorted(p.parent.glob(f"{stem}-*-of-{total}.gguf")) - if len(sibs) != int(total): - raise FileNotFoundError( - f"{p.name}: expected {total} shards, found {len(sibs)} in {p.parent}") - return sibs - return [p] - - -class Gguf: - """Read-only, demand-paged view of a (possibly multi-shard) GGUF. - - Nothing is dequantized until asked for. `g` is the FIRST shard's `GGUFFile`, so metadata and the - tensor directory are reachable as before; reads route to whichever shard owns the tensor. - """ - - def __init__(self, path): - self.paths = _discover_shards(path) - self.path = self.paths[0] - self.shards: list[tuple[GGUFFile, object]] = [] - self._by_name: dict[str, tuple[int, object]] = {} - for i, sp in enumerate(self.paths): - gf = GGUFFile(sp) - self.shards.append((gf, sp.open("rb"))) - for t in gf.tensors: - if t.name in self._by_name: - raise ValueError(f"{sp.name}: duplicate tensor {t.name} across shards") - self._by_name[t.name] = (i, t) - self.g = self.shards[0][0] # metadata / directory / alignment live in shard 1 - - # ---- raw bytes - def _raw(self, name: str, nbytes: int, byte_offset: int = 0) -> bytes: - i, t = self._by_name[name] - gf, fh = self.shards[i] - fh.seek(gf.data_start + t.offset + byte_offset) - return fh.read(nbytes) - - def info(self, name: str): - return self._by_name[name][1] - - def row_bytes(self, t) -> int: - el, by = GEOM[t.type_name] - return t.shape[0] // el * by - - # ---- full tensors - def tensor(self, name: str) -> np.ndarray: - """Dequantize a whole tensor to FP32, shape as GGUF order reversed to (out, in[, experts]).""" - t = self.info(name) - el, by = GEOM[t.type_name] - if t.elements % el: - raise ValueError(f"{name}: {t.elements} not a multiple of block {el}") - raw = np.frombuffer(self._raw(name, t.elements // el * by), dtype=np.uint8) - flat = _dequant_flat(t.type_name, raw) - # GGUF dim 0 varies fastest; numpy's last axis does, so reverse and transpose to (out, in). - return flat.reshape(tuple(reversed(t.shape))) - - # ---- the lazy row path - def rows(self, name: str, idx) -> np.ndarray: - """Gather specific ROWS of a 2-D tensor without decoding the rest of it. - - This exists for `per_layer_token_embd.weight`, which is `[160, 320001536]` IQ4_NL = **26.82 - GiB** - 43% of the artifact, the entire second shard - and is read 16 rows per token by one - layer (see round 98's finding). Calling `tensor()` on it would dequantize 320 million rows to - FP32, about 205 GB, to use 2.5 KB of them. - - A row is contiguous in GGUF (ne0 varies fastest), so one row is `row_bytes` at - `row * row_bytes`. The type's block size must divide the row width; for this table it does - (160 = 5 x 32 for IQ4_NL). - """ - t = self.info(name) - if len(t.shape) != 2: - raise ValueError(f"{name}: rows() needs a 2-D tensor, got shape {t.shape}") - el, by = GEOM[t.type_name] - width = t.shape[0] - if width % el: - raise ValueError(f"{name}: row width {width} is not a multiple of block {el}") - rb = self.row_bytes(t) - idx = np.asarray(idx, dtype=np.int64).ravel() - if idx.size and (idx.min() < 0 or idx.max() >= t.shape[1]): - raise ValueError(f"{name}: row index out of range (0..{t.shape[1] - 1})") - out = np.empty((idx.size, width), dtype=np.float32) - for k, r in enumerate(idx): - raw = np.frombuffer(self._raw(name, rb, int(r) * rb), dtype=np.uint8) - out[k] = _dequant_flat(t.type_name, raw) - return out - - # ---- the lazy path - def expert(self, name: str, expert_id: int) -> np.ndarray: - """One expert out of a fused `[in, out, experts]` tensor, WITHOUT touching the others. - - In GGUF order the expert index is the LAST axis, so expert e's matrix occupies a contiguous - run of `in*out` elements at offset e*in*out. Only that run is read and decoded - which is the - plan's "do not materialize 120B parameters" requirement, and the reason the engine can run at - all on a machine where the expert set is 34 GB. - """ - t = self.info(name) - if len(t.shape) != 3: - raise ValueError(f"{name}: not a fused expert tensor (shape {t.shape})") - in_f, out_f, n_exp = t.shape - if not 0 <= expert_id < n_exp: - raise ValueError(f"{name}: expert {expert_id} out of range (0..{n_exp - 1})") - el, by = GEOM[t.type_name] - per_expert = in_f * out_f - if per_expert % el: - raise ValueError(f"{name}: per-expert element count {per_expert} not a multiple of {el}") - # byte offset of expert e: whole experts before it, in blocks - start = expert_id * (per_expert // el) * by - raw = np.frombuffer(self._raw(name, per_expert // el * by, start), dtype=np.uint8) - flat = _dequant_flat(t.type_name, raw) - return flat.reshape((out_f, in_f)) - - def close(self) -> None: - for _, fh in self.shards: - fh.close() diff --git a/ref/qwen36.py b/ref/qwen36.py deleted file mode 100644 index 2899937..0000000 --- a/ref/qwen36.py +++ /dev/null @@ -1,683 +0,0 @@ -#!/usr/bin/env python3 -"""ref/qwen36.py - the numpy oracle for Qwen3.6-35B-A3B (llama.cpp arch `qwen35moe`). - -A teacher-forced forward pass over a token sequence, written from the pinned llama.cpp graph and nothing -else: third_party/llama.cpp/src/models/qwen35moe.cpp (the layer loop and both mixers), delta-net-base.cpp -(the Gated DeltaNet), src/llama-graph.cpp (build_moe_ffn, build_norm, build_qkv) and ggml-cpu/ops.cpp (the op -semantics). Weights come through `ref/load.py`, so a real quantized GGUF dequantizes lazily (one expert at a -time) and the synthetic F32 fixture from `tools/qwen36_synth_gguf.py` loads the same way. - - python3 ref/qwen36.py MODEL.gguf --tokens 104,101,108,108,111 --dump OUTDIR - python3 ref/qwen36.py MODEL.gguf --text hello --dump OUTDIR # synthetic vocab: token id = ASCII code - python3 ref/qwen36.py MODEL.gguf --tokens ... --dump OUTDIR --mtp # also run the nextn block (needs one) - -Every tensor llama.cpp names with cb() is written to OUTDIR/.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 -" ,,,". `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-.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-.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()) diff --git a/src/artifact/dequant.cpp b/src/artifact/dequant.cpp deleted file mode 100644 index ff058c0..0000000 --- a/src/artifact/dequant.cpp +++ /dev/null @@ -1,123 +0,0 @@ -// src/artifact/dequant.cpp - the `strata-dequant` CLI (dequantize a GGUF tensor and dump F32). -// The dequantizers themselves are header-only in include/strata/artifact/dequant.hpp. -#include "strata/artifact/dequant.hpp" - -#ifdef STRATA_DEQUANT_SELFTEST -int main(int argc, char** argv) { - if (argc < 2) { - std::printf("usage: dequant \n"); - return 2; - } - try { - strata::GgufFile g(argv[1]); - int checked = 0, bad = 0; - for (const auto& t : g.tensors()) { - if (t.type != 42) continue; // Q2_0 only for now - if (checked >= 8) break; - const uint8_t* base = g.tensor_data(t); - const uint64_t nblocks = t.elements() / 64; - for (uint64_t b = 0; b < nblocks && b < 64; ++b) { - const uint8_t* blk = base + b * 18; - float out[64]; - strata::dequantize_q2_0(blk, out); - const float d = strata::fp16_to_fp32(strata::read_u16(blk)); - // STRUCTURAL INVARIANT: every value must be exactly one of {-d, 0, d, 2d}. - for (int j = 0; j < 64; ++j) { - const float v = out[j]; - const bool ok = (v == -d) || (v == 0.0f) || (v == d) || (v == 2.0f * d) || (d == 0.0f); - if (!ok) { - ++bad; - if (bad < 4) - std::printf(" VIOLATION %s block %llu elem %d: v=%g d=%g\n", t.name.c_str(), - (unsigned long long)b, j, v, d); - } - } - } - if (checked == 0) { - // A folded checksum over the FIRST 64 blocks, for cross-checking against the Python - // implementation on identical bytes. A single implementation being self-consistent - // proves little - two disagreeing is what finds bugs (round 67). - double sum = 0, sumabs = 0; - const uint8_t* base = g.tensor_data(t); - for (uint64_t b = 0; b < nblocks && b < 64; ++b) { - float out[64]; - strata::dequantize_q2_0(base + b * 18, out); - for (int j = 0; j < 64; ++j) { - sum += out[j]; - sumabs += std::fabs(out[j]); - } - } - std::printf(" CHECKSUM %s sum=%.10g sumabs=%.10g\n", t.name.c_str(), sum, sumabs); - } - ++checked; - } - // Q5_0 cross-check on the same 64-block window gguf-py is given, using the first Q5_0 tensor. - for (const auto& t : g.tensors()) { - if (t.type != 6 && t.type != 20 && t.type != 14 && t.type != 12 && t.type != 13 && t.type != 11 && - t.type != 23) - continue; - const uint8_t* base = g.tensor_data(t); - const int bsz = - (t.type == 20) - ? 18 - : (t.type == 14 - ? 210 - : (t.type == 12 - ? 144 - : (t.type == 13 ? 176 : (t.type == 11 ? 110 : (t.type == 23 ? 136 : 22))))); - const int nel = - (t.type == 14 || t.type == 12 || t.type == 13 || t.type == 11 || t.type == 23) ? 256 : 32; - const uint64_t nb = t.elements() / (uint64_t)nel; - double sum = 0, sumabs = 0; - for (uint64_t b = 0; b < nb && b < 64; ++b) { - float out[256]; - if (t.type == 20) - strata::dequantize_iq4_nl(base + b * bsz, out); - else if (t.type == 14) - strata::dequantize_q6_K(base + b * bsz, out); - else if (t.type == 12) - strata::dequantize_q4_K(base + b * bsz, out); - else if (t.type == 13) - strata::dequantize_q5_K(base + b * bsz, out); - else if (t.type == 11) - strata::dequantize_q3_K(base + b * bsz, out); - else if (t.type == 23) - strata::dequantize_iq4_xs(base + b * bsz, out); - else - strata::dequantize_q5_0(base + b * bsz, out); - for (int j = 0; j < nel; ++j) { - sum += out[j]; - sumabs += std::fabs(out[j]); - } - } - std::printf(" CHECKSUM %s %s sum=%.10g sumabs=%.10g\n", t.type_name(), t.name.c_str(), sum, - sumabs); - float f8[256]; - if (t.type == 20) - strata::dequantize_iq4_nl(base, f8); - else if (t.type == 14) - strata::dequantize_q6_K(base, f8); - else if (t.type == 12) - strata::dequantize_q4_K(base, f8); - else if (t.type == 13) - strata::dequantize_q5_K(base, f8); - else if (t.type == 11) - strata::dequantize_q3_K(base, f8); - else if (t.type == 23) - strata::dequantize_iq4_xs(base, f8); - else - strata::dequantize_q5_0(base, f8); - std::printf(" REF first8:"); - for (int j = 0; j < 8; ++j) std::printf(" %.6g", f8[j]); - std::printf("\n"); - if (t.type == 23) break; // emit Q5_0 first, then IQ4_NL - } - std::printf("%s\n Q2_0 tensors spot-checked: %d\n symbolic invariant violations: %d -> %s\n", - argv[1], checked, bad, bad ? "FAIL" : "PASS"); - return bad ? 1 : 0; - } catch (const std::exception& e) { - std::printf("ERROR: %s\n", e.what()); - return 1; - } -} -#endif diff --git a/src/artifact/gguf_reader.cpp b/src/artifact/gguf_reader.cpp deleted file mode 100644 index 5498ecd..0000000 --- a/src/artifact/gguf_reader.cpp +++ /dev/null @@ -1,67 +0,0 @@ -// src/artifact/gguf_reader.cpp - the `strata-gguf` CLI. The reader itself is header-only in -// include/strata/artifact/gguf_reader.hpp; this file is just the entry point, so it cannot drift -// from the library it exercises. -#include "strata/artifact/gguf_reader.hpp" - -#ifndef STRATA_GGUF_MAIN_DISABLED -int main(int argc, char** argv) { - if (argc < 2) { - std::printf("usage: gguf_reader [--check]\n"); - return 2; - } - const bool check = (argc > 2 && std::string(argv[2]) == "--check"); - try { - strata::GgufFile g(argv[1]); - std::printf("%s\n", argv[1]); - std::printf(" version %u tensors %zu metadata %zu data_start %llu size %llu\n", g.version(), - g.tensors().size(), g.metadata().size(), (unsigned long long)g.data_start(), - (unsigned long long)g.file_size()); - - if (check) { - // Independent expectations, all established by earlier phases. - size_t n_blk = 0; - for (const auto& t : g.tensors()) - if (t.name.rfind("blk.", 0) == 0) ++n_blk; - std::printf(" blk.* tensors %zu globals %zu\n", n_blk, g.tensors().size() - n_blk); - std::printf(" Q2_0 %llu BF16 %llu F32 %llu\n", (unsigned long long)g.count_type("Q2_0"), - (unsigned long long)g.count_type("BF16"), (unsigned long long)g.count_type("F32")); - - // Every tensor's byte size must land inside the gap to the next tensor's offset, since - // GGUF aligns every tensor. That is the same bracket test tools/verify_q2_0_geometry.py - // uses, and it validates block_geometry() against the file rather than asserting it. - std::vector ordered; - for (const auto& t : g.tensors()) ordered.push_back(&t); - std::sort(ordered.begin(), ordered.end(), [](auto a, auto b) { return a->offset < b->offset; }); - size_t bad = 0, unknown = 0; - for (size_t i = 0; i < ordered.size(); ++i) { - const auto* t = ordered[i]; - int el = 0, by = 0; - if (!strata::block_geometry(t->type, el, by)) { - ++unknown; - continue; - } - if (t->elements() % (uint64_t)el) { - ++bad; - continue; - } - const uint64_t nb = t->elements() / (uint64_t)el * (uint64_t)by; - // The bracket is on the GAP to the next tensor's offset, not on that offset itself - - // offsets are relative to data_start, so the gap is a difference. Comparing against - // the raw offset flagged almost every tensor (213/214) while the same test in Python - // (tools/verify_q2_0_geometry.py) passed. - const uint64_t end = (i + 1 < ordered.size()) ? ordered[i + 1]->offset - t->offset - : g.file_size() - g.data_start() - t->offset; - if (!(nb <= end && end < nb + 32)) ++bad; - } - std::printf(" geometry bracket: %zu out of range, %zu types unknown\n", bad, unknown); - const std::string err = strata::check_architecture(g); - std::printf(" architecture guard: %s\n", err.empty() ? "PASS" : ("FAIL - " + err).c_str()); - if (bad) return 1; - } - return 0; - } catch (const std::exception& e) { - std::printf("ERROR: %s\n", e.what()); - return 1; - } -} -#endif // STRATA_GGUF_MAIN_DISABLED diff --git a/src/artifact/gguf_reader_test.cpp b/src/artifact/gguf_reader_test.cpp deleted file mode 100644 index 70f1bc2..0000000 --- a/src/artifact/gguf_reader_test.cpp +++ /dev/null @@ -1,93 +0,0 @@ -// src/artifact/gguf_reader_test.cpp - the reader refuses what it cannot arbitrate (synthetic GGUF, no model, -// no GPU). -// -// 1. two tensors with distinct names: the file opens and find() sees both; -// 2. the same name twice: refused at open, and the error names the tensor and the file - GGUF has no -// index to say which of the two a name means, and find() is first-match, so the alternative is a -// lookup that silently picks by position. -// -// The fixture is a minimal GGUF v3 written here (header, no metadata, two F32[8] tensors, 32-byte -// alignment), so the test needs neither gguf-py nor a shard. The file is closed before it is removed: -// on Windows an open mapping keeps it. -#include "strata/artifact/gguf_reader.hpp" - -#include -#include -#include -#include -#include -#include -#include - -namespace { -int g_fail = 0; -void check(bool ok, const char* what) { - std::printf(" %-66s %s\n", what, ok ? "ok" : "FAIL"); - if (!ok) ++g_fail; -} - -template void put(std::vector& b, T v) { - const auto n = b.size(); - b.resize(n + sizeof(T)); - std::memcpy(b.data() + n, &v, sizeof(T)); -} -void put_str(std::vector& b, const std::string& s) { - put(b, s.size()); - b.insert(b.end(), s.begin(), s.end()); -} - -// A GGUF v3 file of F32[8] tensors named `names`, laid out 32 bytes apart from a 32-byte-aligned data start. -std::filesystem::path write_gguf(const std::vector& names) { - std::vector b; - put(b, 0x46554747u); // "GGUF" - put(b, 3); - put(b, names.size()); // n_tensors - put(b, 0); // n_kv - for (size_t i = 0; i < names.size(); ++i) { - put_str(b, names[i]); - put(b, 1); // n_dims - put(b, 8); - put(b, 0); // F32 - put(b, 32 * i); // offset from data_start - } - b.resize((b.size() + 31) / 32 * 32 + 32 * names.size(), 0); - const auto path = std::filesystem::temp_directory_path() / "strata_gguf_reader_test.gguf"; - std::ofstream(path, std::ios::binary).write(reinterpret_cast(b.data()), (std::streamsize)b.size()); - return path; -} -} // namespace - -int main() { - std::printf("gguf_reader_test\n"); - { - const auto path = write_gguf({"blk.0.attn_q.weight", "blk.0.attn_k.weight"}); - std::string err; - size_t n = 0; - bool both = false; - try { - strata::GgufFile g(path.string()); - n = g.tensors().size(); - both = g.find("blk.0.attn_q.weight") && g.find("blk.0.attn_k.weight"); - } catch (const std::exception& e) { - err = e.what(); - } - std::filesystem::remove(path); - check(err.empty() && n == 2 && both, "distinct names: the file opens and find() sees both tensors"); - } - { - const auto path = write_gguf({"blk.0.attn_q.weight", "blk.0.attn_q.weight"}); - std::string err; - try { - strata::GgufFile g(path.string()); - } catch (const std::exception& e) { - err = e.what(); - } - std::filesystem::remove(path); - check(!err.empty(), "the same name twice: refused at open"); - check(err.find("blk.0.attn_q.weight") != std::string::npos, " the error names the tensor"); - check(err.find(path.filename().string()) != std::string::npos, " the error names the file"); - if (!err.empty()) std::printf(" (%s)\n", err.c_str()); - } - std::printf(g_fail ? "gguf_reader_test: %d FAILED\n" : "gguf_reader_test: all passed\n", g_fail); - return g_fail ? 1 : 0; -} diff --git a/src/core/concurrent_main.cpp b/src/core/concurrent_main.cpp deleted file mode 100644 index ab5b5ad..0000000 --- a/src/core/concurrent_main.cpp +++ /dev/null @@ -1,197 +0,0 @@ -// src/core/concurrent_main.cpp - do the CPU expert path and the GPU stream path actually run at once? -// -// L9 concluded that the two miss paths are INDEPENDENT RESOURCES - 42.55 GB/s of DRAM bandwidth for the CPU -// expert kernel and 28.9 GB/s of PCIe for the stream - and that running them together would cover a token's -// 552.7 MB of misses in 7.74 ms, which is what puts 100 tps inside reach on this Gen4 machine. -// -// THAT CLAIM HAS A HOLE. An H2D copy from PINNED host memory READS HOST DRAM to do it, so the bus path is not -// free of the resource the CPU path is bound by. If the two contend, the combined rate is not 42.55 + 28.9 and -// the 129 tok/s figure is optimistic; if they overlap cleanly, it stands. This measures it three ways in one -// process - CPU alone, GPU alone, both - because comparing two separately-measured rates is exactly the -// inference that has been wrong twice already in this ledger (L2's dependency chain, L8's bus-only ceiling). -// -// The CPU side is a READ LOOP over the same pinned arena rather than the real VNNI kernel, and that is -// deliberate: the question is whether the two paths contend for DRAM BANDWIDTH, and a read loop is a pure -// measurement of that demand, with no compute that could mask it. -#include "strata/core/pinned.hpp" -#include "strata/kernels/s_gemv.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { - -void check(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -// Volatile sink so the read loop cannot be optimised away; summed across threads and printed, so a compiler -// that removed the loads would produce a suspiciously round zero rather than a plausible number. -std::atomic g_sink{0}; - -struct Run { - double seconds = 0; - double cpu_gb = 0; // GB/s read by the CPU threads - double gpu_experts = 0; // experts streamed and computed by the GPU -}; - -} // namespace - -int main(int argc, char** argv) { - std::string path; - // 4096 planes = 2 GiB, which is 64x the 32 MB L3 on this CPU. At 0.1 GiB the read loop measured 206 GB/s - - // that is CACHE bandwidth, not DRAM, and it would have answered the contention question with a number about - // a different resource entirely. - int experts = 4096; - int cpu_threads = 6; - int gpu_roles = 256; - for (int i = 1; i < argc; ++i) { - const std::string a = argv[i]; - auto val = [&]() -> 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 == "--file") path = val(); - else if (a == "--experts") experts = std::atoi(val()); - else if (a == "--cpu-threads") cpu_threads = std::atoi(val()); - else if (a == "--gpu-roles") gpu_roles = std::atoi(val()); - else { - std::fprintf(stderr, "usage: strata-concurrent --file experts.bin [--experts N] " - "[--cpu-threads N] [--gpu-roles N]\n"); - return 2; - } - } - if (path.empty()) { std::fprintf(stderr, "--file is required\n"); return 2; } - - const long long n_in = 2560, n_out = 640; - const uint64_t role_codes = (uint64_t) n_out * n_in / 4; - const uint64_t plane_bytes = role_codes; // the CPU loop reads the same planes - - strata::core::PinnedArena arena((uint64_t) experts * role_codes); - if (!arena.valid()) { std::fprintf(stderr, "arena allocation failed\n"); return 1; } - { - std::ifstream f(path, std::ios::binary); - if (!f) { std::fprintf(stderr, "cannot open %s\n", path.c_str()); return 1; } - for (int i = 0; i < experts; ++i) { - f.seekg((std::streamoff) i * 1382400); - f.read((char*) arena.data() + (uint64_t) i * role_codes, (std::streamsize) role_codes); - if ((uint64_t) f.gcount() != role_codes) { std::fprintf(stderr, "short read\n"); return 1; } - } - } - std::printf("arena %.2f GiB pinned; %d CPU threads; %d GPU roles\n", - (double) arena.capacity / (1024.0 * 1024 * 1024), cpu_threads, gpu_roles); - - uint8_t* d_codes = nullptr; - check(cudaMalloc(&d_codes, role_codes), "cudaMalloc codes"); - uint16_t* d_x = nullptr; - float *d_scales = nullptr, *d_y = nullptr; - check(cudaMalloc(&d_x, n_in * sizeof(uint16_t)), "cudaMalloc x"); - check(cudaMalloc(&d_scales, (size_t) n_out * (n_in / 64) * sizeof(float)), "cudaMalloc scales"); - check(cudaMalloc(&d_y, n_out * sizeof(float)), "cudaMalloc y"); - std::vector hx((size_t) n_in, 0x3C00); - std::vector hs((size_t) n_out * (size_t) (n_in / 64), 0.001f); - check(cudaMemcpy(d_x, hx.data(), hx.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "copy x"); - check(cudaMemcpy(d_scales, hs.data(), hs.size() * sizeof(float), cudaMemcpyHostToDevice), "copy scales"); - cudaStream_t s_copy{}, s_comp{}; - check(cudaStreamCreate(&s_copy), "stream copy"); - check(cudaStreamCreate(&s_comp), "stream compute"); - const strata::kernels::SForm form{2, -1, 64, strata::kernels::Codebook::Affine, false}; - - // The CPU loop: read the whole arena, Nthreads ways, and sum bytes so nothing is elided. - auto cpu_work = [&](std::atomic& stop, std::atomic& bytes) { - uint64_t acc = 0, n = 0; - const uint8_t* p = arena.data(); - while (!stop.load(std::memory_order_relaxed)) { - // touch one byte per 64 - a stride that defeats prefetch into a pure streaming read - for (uint64_t i = 0; i < plane_bytes * (uint64_t) experts; i += 64) acc += p[i]; - n += plane_bytes * (uint64_t) experts; - } - bytes.fetch_add(n); - g_sink.fetch_add(acc); - }; - - // The GPU loop: stream each role plane on the copy stream while computing on the compute stream. - auto gpu_work = [&](int roles) { - cudaEvent_t ev[2]; - for (int b = 0; b < 2; ++b) check(cudaEventCreateWithFlags(&ev[b], cudaEventDisableTiming), "event"); - uint8_t* buf[2] = {d_codes, d_codes}; // one buffer is enough: the timing is what is measured - check(cudaMemcpyAsync(buf[0], arena.data(), role_codes, cudaMemcpyHostToDevice, s_copy), "prologue"); - check(cudaEventRecord(ev[0], s_copy), "prologue event"); - for (int i = 0; i < roles; ++i) { - const int cur = i & 1, nxt = (i + 1) & 1; - if (i + 1 < roles) { - check(cudaMemcpyAsync(buf[nxt], arena.data() + (uint64_t) ((i + 1) % experts) * role_codes, - role_codes, cudaMemcpyHostToDevice, s_copy), - "copy"); - check(cudaEventRecord(ev[nxt], s_copy), "event"); - } - check(cudaStreamWaitEvent(s_comp, ev[cur], 0), "wait"); - strata::kernels::s_gemv_split_async(d_x, buf[cur], d_scales, nullptr, d_y, n_in, n_out, form, 32, - (void*) s_comp); - } - check(cudaStreamSynchronize(s_comp), "sync comp"); - check(cudaStreamSynchronize(s_copy), "sync copy"); - for (int b = 0; b < 2; ++b) cudaEventDestroy(ev[b]); - }; - - auto run = [&](bool do_cpu, bool do_gpu, const char* name) { - std::atomic stop{false}; - std::atomic bytes{0}; - std::vector cpu; - check(cudaStreamSynchronize(0), "pre"); - const auto t0 = std::chrono::steady_clock::now(); - if (do_cpu) for (int t = 0; t < cpu_threads; ++t) cpu.emplace_back(cpu_work, std::ref(stop), std::ref(bytes)); - if (do_gpu) { - gpu_work(gpu_roles); - } else { - // CPU-only needs a REAL window. The first version let t0..t1 span nothing when there was no GPU - // work, so the threads were stopped immediately and the run reported 0.000 s and 0.00 GB/s. - std::this_thread::sleep_for(std::chrono::milliseconds(3000)); - } - const auto t1 = std::chrono::steady_clock::now(); - stop = true; - for (auto& t : cpu) t.join(); - Run r; - r.seconds = std::chrono::duration(t1 - t0).count(); - r.cpu_gb = (double) bytes.load() / 1e9 / r.seconds; - r.gpu_experts = do_gpu ? (double) gpu_roles / r.seconds : 0.0; - std::printf(" %-18s %7.3f s CPU read %6.2f GB/s GPU %7.1f roles/s\n", name, r.seconds, r.cpu_gb, - r.gpu_experts); - return r; - }; - - std::printf("\n mode wall CPU read GPU\n"); - const Run cpu_only = run(true, false, "CPU only"); - const Run gpu_only = run(false, true, "GPU only"); - const Run both = run(true, true, "BOTH"); - - std::printf("\n independence check (1.00 = perfectly shared, 0.00 = fully independent):\n"); - const double cpu_interference = cpu_only.cpu_gb > 0 ? 1.0 - both.cpu_gb / cpu_only.cpu_gb : 0.0; - const double gpu_interference = gpu_only.gpu_experts > 0 ? 1.0 - both.gpu_experts / gpu_only.gpu_experts : 0.0; - std::printf(" CPU throughput lost when the GPU also runs : %5.1f%%\n", cpu_interference * 100); - std::printf(" GPU throughput lost when the CPU also runs : %5.1f%%\n", gpu_interference * 100); - std::printf(" combined vs the sum of the parts : CPU %6.2f + GPU-equivalent vs %6.2f measured\n", - cpu_only.cpu_gb, both.cpu_gb); - std::printf("\n NOTE: the CPU side is a READ LOOP, not the VNNI kernel - it measures DRAM DEMAND, which is the\n" - " resource the question is about. L9's 129 tok/s assumes these two do not contend.\n"); - - cudaFree(d_codes); - cudaFree(d_x); - cudaFree(d_scales); - cudaFree(d_y); - cudaStreamDestroy(s_copy); - cudaStreamDestroy(s_comp); - return 0; -} diff --git a/src/core/conversation_cache_test.cpp b/src/core/conversation_cache_test.cpp deleted file mode 100644 index f544dd7..0000000 --- a/src/core/conversation_cache_test.cpp +++ /dev/null @@ -1,305 +0,0 @@ -#include "strata/core/conversation_cache.hpp" - -#include -#include -#include - -using namespace strata::core; - -namespace { -int checks = 0; -void check(bool value, const char* description) { - ++checks; - if (!value) { std::fprintf(stderr, "FAIL: %s\n", description); std::exit(1); } -} -SavedConversation image(std::initializer_list ids, bool cvec = true) { - SavedConversation s; - s.live.ids = ids; - s.live.gdn.resize(64, 7); - s.cvec = cvec; - return s; -} -} - -int main() { - { - ConversationBuffer bytes; - const size_t first = ConversationBuffer::segment_bytes + 17; - const size_t peak = bytes.allocation_peak(first); - bytes.resize(first, 7); - check(bytes.bytes() <= peak, "segmented payload and directory fit admitted bytes"); - uint8_t* original = nullptr; - bytes.visit(0, 1, [&](uint8_t* p, size_t, size_t) { original = p; return true; }); - const size_t grown_peak = bytes.allocation_peak(first + 99); - bytes.resize(first + 99, 9); - bytes.visit(0, 1, [&](uint8_t* p, size_t, size_t) { - check(p == original, "appending preserves existing payload addresses"); return true; - }); - check(bytes.bytes() <= grown_peak, "growth including transient directory fits admission"); - std::vector tail(116); - check(bytes.read(tail.data(), ConversationBuffer::segment_bytes, tail.size()), "read spans segment boundaries"); - check(std::all_of(tail.begin(), tail.begin()+17, [](auto v){return v==7;}) && - std::all_of(tail.begin()+17, tail.end(), [](auto v){return v==9;}), "growth preserves prefix and initializes only suffix"); - auto copy = bytes; - bytes.resize(ConversationBuffer::segment_bytes + 10); - bytes.resize(first, 7); bytes.resize(first + 99, 9); - check(bytes == copy, "equality ignores differing segmentation after rewind and regrowth"); - check(!bytes.read(tail.data(), bytes.size()-1, 2), "range check rejects a truncated payload"); - check(bytes.allocation_peak(SIZE_MAX) == SIZE_MAX, "allocation estimate rejects overflow"); - } - { - ConversationBuffer bytes; - for (size_t n=1;n<=4096;++n) { - const size_t peak = bytes.allocation_peak(n*17); - bytes.resize(n*17,7); - check(bytes.bytes() <= peak,"small append stays within the predicted allocation peak"); - } - size_t segments = 0; - bytes.visit(0,bytes.size(),[&](const uint8_t*,size_t,size_t){++segments;return true;}); - check(segments <= 4,"thousands of small turns do not create thousands of restore transfers"); - } - { - ConversationKv layer; - layer.k.resize(400); - std::vector layers; - layers.push_back(std::move(layer)); - const size_t retained = layers.capacity()*sizeof(ConversationKv) + layers[0].bytes(); - const size_t parked = image({1,2,3}).bytes(); - ConversationCache cache(retained + parked, 4); - check(cache.put(image({1,2,3})), "park before retaining active storage"); - cache.retain(std::move(layers), 16); - check(cache.bytes() == retained + parked && cache.size() == 1, "active retained storage consumes bytes but no parked slot"); - cache.limit_reuse(9); cache.limit_reuse(12); - auto reuse = cache.take_reuse(); - check(reuse.unchanged_tokens == 9, "a later continuation cannot undo a rewind's dirty boundary"); - check(cache.bytes() == parked, "taking retained buffers releases their budget accounting"); - cache.retain(std::move(reuse.kv), 16); - check(!cache.can_fit(parked),"retained storage is counted when checking a capture without eviction"); - check(cache.retained_bytes() == retained && cache.size() == 1 && cache.evictions() == 0, - "optional reuse admission does not evict or release anything"); - check(!cache.can_fit(SIZE_MAX) && !cache.can_fit(1,SIZE_MAX),"non-mutating reservation rejects overflow"); - check(cache.make_room(parked), "reservation can discard optional active buffers"); - check(cache.retained_bytes() == 0 && cache.size() == 1 && cache.evictions() == 0, - "pressure drops retained storage before evicting parked conversations"); - } - const std::vector a = {1, 2, 3, 4}, b = {9, 8, 7, 6}; - { - ConversationCache cache(1024, 2); - check(cache.put(image({1, 2, 3})), "park A"); - check(cache.put(image({9, 8, 7})), "park B"); - auto match = cache.best(a, {}, true); - check(match.tokens == 3 && match.live, "A/B/A: recover A"); - auto restored = cache.take(match.index); - check(restored.live.ids == std::vector({1, 2, 3}), "taking selected A preserves identity"); - check(cache.size() == 1 && cache.best(b, {}, true).tokens == 3, "B remains parked"); - check(cache.bytes() == image({9,8,7}).bytes(), "byte accounting after take"); - check(cache.put(std::move(restored)), "park returned A as newest"); - check(cache.put(image({5, 6})), "evict oldest by slot limit"); - check(cache.best(b, {}, true).tokens == 0 && cache.best(a, {}, true).tokens == 3, "B evicted before A"); - check(cache.evictions() == 1, "eviction counter"); - } - { - auto s = image({1, 2, 3}); - ConversationCheckpoint cp; - cp.ids = {1, 2}; - s.checkpoints.push_back(cp); - ConversationCache cache(4096, 4); - cache.put(std::move(s)); - auto match = cache.best(std::vector{1, 2, 9, 4}, {}, true); - check(match.tokens == 2 && !match.live, "edited suffix falls back to parked checkpoint"); - check(cache.best(a, {}, true).tokens == 3, "live prefix beats shorter checkpoint"); - check(cache.best(a, {}, false).tokens == 0, "steering mode is isolated"); - check(cache.best(std::vector{1, 2}, {}, true).tokens == 0, "equal-length checkpoint cannot consume last token"); - check(cache.best(std::vector{1}, {}, true).tokens == 0, "short prompt cannot match"); - check(cache.best(std::vector{}, {}, true).tokens == 0, "empty prompt cannot match"); - cache.put(image({1, 2, 3})); - check(cache.best(a, {}, true).index == 1, "ties prefer most recently parked"); - } - { - auto s = image({1, 2, 3}); - s.live.imgs = {{1, 123}}; - ConversationCache cache(1024, 3); - cache.put(std::move(s)); - check(cache.best(a, {{1,123}}, true).tokens == 3, "same image can resume"); - check(cache.best(a, {{1,124}}, true).tokens == 0, "different image pixels invalidate same pad tokens"); - check(cache.best(a, {}, true).tokens == 0, "missing image invalidates prefix"); - check(cache.best(a, {{1,123},{2,45}}, true).tokens == 0, "additional image in cached prefix invalidates"); - check(cache.best(a, {{1,123},{3,45}}, true).tokens == 3, "image after cached prefix does not invalidate"); - } - { - const size_t one = image({1,2,3}).bytes(); - ConversationCache cache(one*2, 8); - cache.put(image({1,2,3})); cache.put(image({9,8,7})); - check(cache.bytes() == one*2, "budget holds two exact-sized images"); - auto held = cache.take(cache.best(a, {}, true).index); - check(cache.make_room(one, held.bytes()), "count in-flight image when reserving outgoing snapshot"); - check(cache.size() == 0, "in-flight reservation evicts otherwise fitting B"); - check(cache.put(image({5,6,7}), held.bytes()), "insert with in-flight accounting"); - check(cache.bytes()+held.bytes() <= one*2, "exchange obeys byte budget"); - check(!cache.make_room(one+1, one), "oversized exchange rejected"); - check(cache.size() == 1, "oversized snapshot does not evict useful entries"); - auto huge = image({1}); huge.live.gdn.resize(one*3); - check(!cache.put(std::move(huge)), "oversized image rejected"); - check(cache.size() == 1, "oversized put leaves cache unchanged"); - check(!cache.make_room(0, one*2+1), "held larger than budget cannot underflow"); - } - { - // #342: MAIN -> SUB (9 turns) -> MAIN with 4 slots. Every SUB turn parks the previous turn's live state - // (its reply as generated, which the next request re-rendered) with a chain that holds that turn's - // boundary checkpoint; the copy a turn back adds only that stale tail and is dropped, so MAIN survives. - auto cp = [](std::vector ids) { ConversationCheckpoint c; c.ids = std::move(ids); return c; }; - auto with = [](std::vector prefix, std::initializer_list more) { - prefix.insert(prefix.end(), more); return prefix; - }; - const std::vector root = {1, 2, 3, 4}; - SavedConversation main = image({}); - main.live.ids = with(with(root, {10, 11, 12}), {13, 14}); - main.checkpoints = {cp(root), cp(with(root, {10, 11, 12}))}; - const size_t big = 1 << 20; - ConversationCache cache(big, 4); - check(cache.put(std::move(main)), "park MAIN"); - std::vector history = with(root, {20}); // SUB's conversation so far, re-rendered - std::vector chain = {cp(root)}; - for (int turn = 1; turn <= 9; ++turn) { - chain.push_back(cp(history)); // the turn boundary the next request resumes from - SavedConversation sub = image({}); - sub.live.ids = with(history, {900, (int32_t) turn}); // + the reply with its thinking (stale tail) - sub.checkpoints = chain; - check(cache.put(std::move(sub)), "park SUB turn"); - check(cache.size() <= 2, "one parked copy of SUB at a time"); - history = with(history, {30, (int32_t) turn}); // the reply as the next request renders it - } - check(cache.evictions() == 0 && cache.superseded() == 8, "8 superseded copies dropped, nothing evicted"); - const auto m = cache.best(with(with(root, {10, 11, 12}), {13, 14, 15}), {}, true); - check(m.tokens == 9 && m.live, "MAIN still restores in full"); - const auto s = cache.best(with(history, {40}), {}, true); - check(s.tokens == (int64_t) history.size() - 2, "SUB resumes from its last turn boundary"); - } - { - // what is NOT superseded: another conversation sharing only the root, an entry without checkpoints, the - // other steering mode, a branch whose deepest checkpoint the new chain does not hold - auto cp = [](std::vector ids) { ConversationCheckpoint c; c.ids = std::move(ids); return c; }; - ConversationCache cache(1 << 20, 8); - SavedConversation other = image({1, 2, 3, 4, 50, 51, 52}); - other.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 50, 51})}; - cache.put(std::move(other)); - cache.put(image({1, 2, 3, 4, 7, 7})); // no checkpoints - SavedConversation steered = image({1, 2, 3, 4, 60, 61}, false); - steered.checkpoints = {cp({1, 2, 3, 4, 60})}; - cache.put(std::move(steered)); - SavedConversation branch = image({1, 2, 3, 4, 60, 70, 71}); - branch.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 60, 70})}; - cache.put(std::move(branch)); - SavedConversation incoming = image({1, 2, 3, 4, 60, 80, 81}); - incoming.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 60})}; - check(cache.put(std::move(incoming)), "park a conversation sharing roots with all of them"); - check(cache.size() == 5 && cache.superseded() == 0, "none of them is superseded"); - SavedConversation same_state = image({1, 2, 3, 4, 60, 70}); // live equal to the branch's deepest point - same_state.checkpoints = {cp({1, 2, 3, 4})}; - check(cache.put(std::move(same_state)) && cache.superseded() == 1 && cache.size() == 5, - "the live state equal to an entry's deepest checkpoint supersedes it"); - SavedConversation huge = image({1, 2, 3, 4, 60, 80}); - huge.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 60})}; - huge.live.gdn.resize(2 << 20); - check(!cache.put(std::move(huge)) && cache.size() == 5 && cache.superseded() == 1, - "an oversized put drops nothing"); - } - { - ConversationCache disabled(0,4), no_slots(1024,0); - check(!disabled.enabled() && !no_slots.enabled(), "both disable switches"); - check(!disabled.put(image({1,2,3})) && !no_slots.put(image({1,2,3})), "disabled cache stores nothing"); - check(disabled.best(a,{},true).tokens == 0, "disabled cache has no matches"); - } - { - // layer-split parking: checkpoints moved apart into stage parts and put back, no running state copied - auto running = [](std::initializer_list ids, uint8_t salt, size_t parts) { - ConversationCheckpoint c; - c.ids = ids; - c.gdn.assign(256, salt); - c.tails.assign(32, uint8_t(salt + 1)); - c.used = salt; - for (size_t k = 0; k < parts; ++k) { - ConversationCheckpoint p; - p.gdn.assign(128, uint8_t(salt + 10 + k)); - c.stage_parts.push_back(std::move(p)); - } - return c; - }; - std::vector checks; - checks.push_back(running({1, 2}, 3, 2)); - checks.push_back(running({1, 2, 3}, 5, 1)); // an incomplete set: kept aside, put back in place - checks.push_back(running({1, 2, 3, 4}, 7, 2)); - const auto original = checks; - const uint8_t* gdn0 = checks[0].gdn.data(); - const uint8_t* part1 = checks[2].stage_parts[1].gdn.data(); - auto split = conversation_checkpoints_split(std::move(checks), 2); - check(checks.empty() && split.stage0.size() == 2 && split.rest.size() == 1 && split.parts.size() == 2 && - split.parts[0].size() == 2 && split.parts[1].size() == 2, "split: complete checkpoints apart, the other aside"); - check(split.stage0[0].stage_parts.empty() && split.parts[1][1].ids == original[2].ids && - split.parts[1][1].used == original[2].used && split.parts[0][0].gdn == original[0].stage_parts[0].gdn, - "split: every stage part carries its checkpoint's ids and LRU stamp"); - check(split.stage0[0].gdn.data() == gdn0 && split.parts[1][1].gdn.data() == part1, - "split moves the running state (same buffers, no copy)"); - std::vector back; - check(conversation_checkpoints_merge(std::move(split), back) && back.size() == 3, "merge puts them back"); - bool same = true; - for (size_t j = 0; j < back.size(); ++j) { - same = same && back[j].ids == original[j].ids && back[j].gdn == original[j].gdn && - back[j].tails == original[j].tails && back[j].used == original[j].used && - back[j].stage_parts.size() == original[j].stage_parts.size(); - for (size_t k = 0; same && k < back[j].stage_parts.size(); ++k) - same = back[j].stage_parts[k].gdn == original[j].stage_parts[k].gdn; - } - check(same, "merge(split(x)) == x, in the original order"); - check(back[0].gdn.data() == gdn0 && back[2].stage_parts[1].gdn.data() == part1, "merge moves them back too"); - - auto torn = conversation_checkpoints_split(std::vector(original), 2); - torn.parts[1].pop_back(); - check(!conversation_checkpoints_merge(std::move(torn), back) && back.empty(), "a stage short of a part is refused"); - auto mixed = conversation_checkpoints_split(std::vector(original), 2); - mixed.parts[0][0].ids = {9, 9}; - check(!conversation_checkpoints_merge(std::move(mixed), back) && back.empty(), "a part of another checkpoint is refused"); - // a restored image: stage 0's checkpoints and each stage's, with no record of an incomplete one - ConversationCheckpointSplit restored; - restored.stage0.push_back(running({4, 5}, 11, 0)); - restored.parts.resize(2); - for (auto& p : restored.parts) { auto c = running({4, 5}, 12, 0); p.push_back(std::move(c)); } - check(conversation_checkpoints_merge(std::move(restored), back) && back.size() == 1 && - back[0].stage_parts.size() == 2, "a restored image's parts are all whole"); - auto none = conversation_checkpoints_split({}, 3); - check(conversation_checkpoints_merge(std::move(none), back) && back.empty(), "no checkpoints: nothing to do"); - } - { - // the later stages' retained K/V, kept with the first stage's and limited together - auto kv = [](size_t n) { - std::vector v(2); - for (auto& l : v) l.k.resize(n, 1); - return v; - }; - ConversationCache cache(1 << 20, 4); - std::vector> stage_kv; - stage_kv.push_back(kv(1000)); - stage_kv.push_back(kv(2000)); - cache.retain(kv(500), 40, std::move(stage_kv)); - check(cache.retained_bytes() >= 2 * (500 + 1000 + 2000), "retained bytes count every stage"); - cache.limit_reuse(30); - auto r = cache.take_reuse(); - check(r.kv.size() == 2 && r.stages.size() == 2 && r.unchanged_tokens == 30 && - r.stages[0].unchanged_tokens == 30 && r.stages[1].unchanged_tokens == 30 && - r.stages[1].captured_tokens == 40, "every stage's reuse is limited to the first rewrite"); - check(cache.retained_bytes() == 0, "taken once"); - std::vector> big; - big.push_back(kv(1 << 20)); - cache.retain(kv(500), 40, std::move(big)); - check(cache.retained_bytes() == 0, "a stage's K/V over the budget drops the whole reuse"); - std::vector> one; - one.push_back(kv(100)); - cache.retain(kv(500), 40, std::move(one)); - cache.limit_reuse(0); - check(cache.retained_bytes() == 0, "a rewrite from the start drops every stage's reuse"); - cache.retain(kv(500), 40); - r = cache.take_reuse(); - check(r.kv.size() == 2 && r.stages.empty(), "no layer split: no stage reuse, as before"); - } - std::printf("conversation_cache_test: %d checks passed\n", checks); -} diff --git a/src/core/conversation_checked.hpp b/src/core/conversation_checked.hpp deleted file mode 100644 index 4355dc4..0000000 --- a/src/core/conversation_checked.hpp +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace strata::core::conversation_detail { -inline bool add(size_t& total, size_t n) { - if (n > std::numeric_limits::max() - total) return false; - total += n; - return true; -} -inline bool product(size_t& out, std::initializer_list factors) { - size_t value = 1; - for (uint64_t factor : factors) { - if (factor > std::numeric_limits::max() || - (factor && value > std::numeric_limits::max() / factor)) return false; - value *= (size_t) factor; - } - out = value; - return true; -} -} // namespace strata::core::conversation_detail diff --git a/src/core/conversation_memory.cpp b/src/core/conversation_memory.cpp deleted file mode 100644 index bd5740f..0000000 --- a/src/core/conversation_memory.cpp +++ /dev/null @@ -1,51 +0,0 @@ -#include "strata/core/conversation_memory.hpp" - -#include -#include -#include -#include -#include - -#if defined(_WIN32) -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include -#endif - -namespace strata::core { - -std::optional conversation_mem_available(std::istream& meminfo) { - std::optional result; - std::string line; - while (std::getline(meminfo, line)) { - std::istringstream fields(line); - std::string key, value, unit, extra; - if (!(fields >> key) || key != "MemAvailable:") continue; - if (result || !(fields >> value >> unit) || unit != "kB" || (fields >> extra)) return {}; - uint64_t kb = 0; - const auto parsed = std::from_chars(value.data(), value.data() + value.size(), kb); - if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || - kb > std::numeric_limits::max() / 1024) return {}; - result = kb * 1024; - } - if (meminfo.bad() || (meminfo.fail() && !meminfo.eof())) return {}; - return result; -} - -std::optional conversation_available_memory() { -#if defined(_WIN32) - MEMORYSTATUSEX status{}; - status.dwLength = sizeof status; - if (GlobalMemoryStatusEx(&status)) return status.ullAvailPhys; - return {}; -#elif defined(__linux__) - std::ifstream meminfo("/proc/meminfo"); - if (!meminfo) return {}; - return conversation_mem_available(meminfo); -#else - return {}; -#endif -} - -} // namespace strata::core diff --git a/src/core/conversation_memory_test.cpp b/src/core/conversation_memory_test.cpp deleted file mode 100644 index a8cb25d..0000000 --- a/src/core/conversation_memory_test.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include "strata/core/conversation_memory.hpp" - -#include -#include -#include -#include - -#if defined(_WIN32) -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include -#endif - -using namespace strata::core; -namespace { -int checks = 0; -void check(bool ok, const char* label) { - ++checks; - if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); } -} -} - -int main() { - for (const char* text : {"", "MemFree: 100 kB\n", "MemAvailable: -1 kB\n", - "MemAvailable: +1 kB\n", "MemAvailable: 1 MB\n", - "MemAvailable: 1\n", "MemAvailable: 1x kB\n", - "MemAvailable: 18446744073709551615 kB\n", - "MemAvailable: 18446744073709551616 kB\n", - "MemAvailable: 1 kB trailing\n", - "MemAvailable: 1 kB\nMemAvailable: 2 kB\n"}) { - std::istringstream input(text); - check(!conversation_mem_available(input), "missing/malformed telemetry is unknown"); - } - std::istringstream normal("MemTotal: 999999 kB\nMemAvailable: 12345 kB\nSwapFree: 777 kB\n"); - check(conversation_mem_available(normal) == 12345ULL * 1024, "only MemAvailable is counted"); - std::istringstream zero("MemAvailable: 0 kB"); - check(conversation_mem_available(zero) == 0, "zero available memory is known"); - std::istringstream broken("MemAvailable: 123 kB\n"); - broken.setstate(std::ios::badbit); - check(!conversation_mem_available(broken), "I/O failure declines admission"); - check(!conversation_memory_admit({}, 0, 0), "unknown fails closed even with zero floor"); - check(conversation_memory_admit(100, 40, 60), "exact allocation plus floor fits"); - check(!conversation_memory_admit(99, 40, 60), "one byte below required memory rejected"); - check(!conversation_memory_admit(59, 0, 60), "floor subtraction cannot underflow"); - check(conversation_memory_admit(60, 0, 60), "post-capture floor check"); - check(!conversation_memory_admit(100, std::numeric_limits::max(), 1), "allocation arithmetic cannot overflow"); - check(conversation_memory_admit(std::numeric_limits::max(), - std::numeric_limits::max(), 0), "maximal exact bound"); - check(!conversation_memory_admit(std::numeric_limits::max(), - std::numeric_limits::max(), 1), "maximal sum overflow rejected"); - // Test the real provider without assuming any particular amount of free RAM. - const auto available = conversation_available_memory(); - check(!available || conversation_memory_admit(available, 0, 0), "provider returns bytes or unknown"); -#if defined(_WIN32) - // Unknown must fail closed in production, but must not let a broken Windows provider pass this test. - // Compare with total physical memory, not a second available reading: other processes can allocate - // between calls. No pressure allocation or fixed free-memory assumption is needed. - MEMORYSTATUSEX physical{}; - physical.dwLength = sizeof physical; - check(GlobalMemoryStatusEx(&physical) != 0, "Windows physical-memory API is available"); - check(available.has_value() && *available <= physical.ullTotalPhys, - "Windows provider returns a known, physically bounded sample"); -#endif - std::printf("conversation_memory_test: %d checks passed\n", checks); -} diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp deleted file mode 100644 index 8bc3d06..0000000 --- a/src/core/conversation_snapshot.cpp +++ /dev/null @@ -1,269 +0,0 @@ -#include "strata/core/conversation_snapshot.hpp" -#include "strata/kernels/kv_q4.hpp" -#include "conversation_checked.hpp" -#include - -#include -#include -#include - -namespace strata::core { -namespace { -struct Layout { - int format; - int64_t cells, pooled_rows, page_size; - size_t data, scales, pooled, value_data, value_scales; -}; - -bool valid_extent(const QsaState& st, int64_t upto, std::string& error) { - const int64_t page = strata::kernels::qsa_real_shapes().page_size; - if (upto < 0 || upto > st.max_cells || upto > std::numeric_limits::max() - (page - 1)) { - error = "conversation snapshot: invalid K/V extent"; - return false; - } - return true; -} - -bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index, Layout& l, std::string& error) { - if (!valid_extent(st, upto, error)) return false; - if (st.kv_hybrid && (st.kv_mode != 0 || st.kv_q4 || st.kv_int8)) { - error = "conversation snapshot: hybrid K8V4 requires an identity layout and distinct format flags"; - return false; - } - 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 || - (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; - } - const int64_t cells = ((upto + s.page_size - 1) / s.page_size) * s.page_size; - const size_t per = st.kv_q4 ? (size_t) strata::kernels::kv_q4_bytes_per_head((int) g.head_dim) - : (size_t) g.head_dim * (int8_keys ? 1 : 2); - // Include the moving spare row, not only completed blocks. The checkpoint - // restore reconstructs that row when rewinding to an earlier prefix. - // (a dense-attention model has no indexer and so no pooled rows: idx_key_dim 0) - const int64_t pooled = index && g.has_indexer() && upto > 0 ? upto / s.idx_block + 1 : 0; - // 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. - // (Q4_0 is always rotated: nothing to tell apart; without the rotation the format is the one it always was.) - const int rotated = st.kv_rot && !st.kv_q4 && !st.kv_hybrid ? 16 : 0; - l = {(st.kv_hybrid ? 3 : qsa_kv_format(st)) + rotated, cells, pooled, s.page_size, 0, 0, 0, 0, 0}; - using conversation_detail::product; - if (!product(l.data, {(uint64_t) cells, (uint64_t) g.n_head_kv, per}) || - !product(l.scales, {(uint64_t) cells, (uint64_t) g.n_head_kv, - int8_keys && !st.kv_q4 ? (uint64_t) (g.head_dim / 64) * 2 : 0}) || - !product(l.pooled, {(uint64_t) pooled, (uint64_t) g.idx_key_dim, sizeof(float)})) { - error = "conversation snapshot: K/V byte count overflow"; - return false; - } - l.value_data = l.data; - l.value_scales = l.scales; - if (st.kv_hybrid) { - if (!product(l.value_data, {(uint64_t) cells, (uint64_t) g.n_head_kv, - (uint64_t) strata::kernels::kv_q4_bytes_per_head((int) g.head_dim)})) { - error = "conversation snapshot: hybrid V byte count overflow"; - return false; - } - l.value_scales = 0; - } - return true; -} - -std::array pools(const QsaState& st, bool resident = false) { - const bool host = st.kv_mode != 0 && !resident; - if (st.kv_hybrid) return {st.k_q, st.v_q4, st.k_scale, nullptr, st.idx_pooled}; - if (st.kv_q4) - return {host ? st.host.k_q4 : st.k_q4, host ? st.host.v_q4 : st.v_q4, nullptr, nullptr, st.idx_pooled}; - if (st.kv_int8) - return {host ? st.host.k_q : st.k_q, host ? st.host.v_q : st.v_q, - host ? st.host.k_scale : st.k_scale, host ? st.host.v_scale : st.v_scale, st.idx_pooled}; - return {host ? st.host.k_pool : st.k_pool, host ? st.host.v_pool : st.v_pool, nullptr, nullptr, st.idx_pooled}; -} - -bool valid(const QsaState& st, const Layout& l, int64_t upto, std::string& error) { - if (upto < 0 || upto > st.max_cells || st.n_pages < 0 || l.cells / l.page_size > st.n_pages || - st.kv_mode < 0 || st.kv_mode > 2 || st.n_slots <= 0 || - (st.kv_mode == 0 && st.n_slots < st.n_pages) || - l.pooled_rows > st.idx_pooled_rows || (st.kv_mode != 0 && !st.host.present())) { - error = "conversation snapshot: invalid K/V extent or missing authoritative host pool"; - return false; - } - if (st.kv_mode == 1) { - const auto& m = st.map; - if (m.n_blocks != st.n_pages || m.n_slots != st.n_slots || !m.page_table || !m.slot_block || - !m.slot_stamp || !m.slot_ref || !m.ctl || !m.miss_block || !m.miss_slot) { - error = "conversation snapshot: invalid streaming map"; - return false; - } - } - if (st.kv_mode == 2 && (!st.page_table || - (st.kv_q4 ? !st.k_q4 || !st.v_q4 : st.kv_int8 ? !st.k_q || !st.v_q || !st.k_scale || !st.v_scale - : !st.k_pool || !st.v_pool))) { - error = "conversation snapshot: invalid draft ring"; - return false; - } - return true; -} - -bool transfer(void* dst, const void* src, size_t n, std::string& error) { - if (!n) return true; - if (!src || !dst) { error = "conversation snapshot: missing state buffer"; return false; } - // Default handles both device allocations and device-mapped host pool aliases. - const cudaError_t e = cudaMemcpy(dst, src, n, cudaMemcpyDefault); - if (e == cudaSuccess) return true; - error = std::string("conversation snapshot copy: ") + cudaGetErrorString(e); - return false; -} -} // namespace - -bool conversation_kv_capture_bytes(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, - int64_t upto, bool index, size_t& bytes, std::string& error) { - Layout l{}; - if (!layout(st, g, upto, index, l, error) || !valid(st, l, upto, error)) return false; - const std::array sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled}; - const std::array buffers = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; - bytes = 0; - for (size_t i = 0; i < buffers.size(); ++i) { - const size_t n = buffers[i]->allocation_peak(sizes[i]); - if (n == SIZE_MAX || !conversation_detail::add(bytes, n)) { - error = "conversation snapshot: segmented K/V allocation overflow"; - return false; - } - } - return true; -} - -size_t conversation_kv_bytes(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index) { - size_t bytes = 0; - std::string error; - return conversation_kv_capture_bytes({}, st, g, upto, index, bytes, error) ? bytes : 0; -} - -bool conversation_kv_save(ConversationKv& image, const QsaState& st, const ModelGeometry& g, - int64_t upto, bool index, std::string& error, - int64_t unchanged_tokens, size_t* reused_bytes) { - Layout l{}; - if (!layout(st, g, upto, index, l, error)) return false; - if (!valid(st, l, upto, error)) return false; - if (unchanged_tokens < 0 || unchanged_tokens > upto || unchanged_tokens > image.cells) { - error = "conversation snapshot: invalid unchanged prefix"; - return false; - } - const int64_t whole_cells = (unchanged_tokens / l.page_size) * l.page_size; - image.format = l.format; - image.cells = l.cells; - image.heads = g.n_head_kv; - image.head_dim = g.head_dim; - image.page_size = l.page_size; - image.pooled_rows = l.pooled_rows; - image.idx_dim = g.idx_key_dim; - const auto src = pools(st); - const std::array sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled}; - const std::array dst = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; - for (size_t i = 0; i < dst.size(); ++i) { - // Recopy the partial page and the indexer's moving spare row. Completed - // pages/rows strictly before the first rewritten token remain identical. - const size_t keep = i == 4 ? (index ? size_t(unchanged_tokens / strata::kernels::qsa_real_shapes().idx_block) * g.idx_key_dim * 4 : 0) - : l.cells ? (sizes[i] / size_t(l.cells)) * size_t(whole_cells) : 0; - if (keep > dst[i]->size()) { error = "conversation snapshot: missing reusable prefix"; return false; } - dst[i]->resize(sizes[i]); - if (!dst[i]->visit(keep, sizes[i] - keep, [&](uint8_t* p, size_t n, size_t at) { - return transfer(p, src[i] ? static_cast(src[i]) + at : nullptr, n, error); - })) return false; - if (reused_bytes) *reused_bytes += keep; - } - return true; -} - -bool conversation_kv_validate(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, - int64_t upto, bool index, std::string& error) { - Layout l{}; - if (!layout(st, g, upto, index, l, error)) return false; - if (!valid(st, l, upto, error)) return false; - const std::array sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled}; - const std::array src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; - if (image.format != l.format || image.cells != l.cells || image.heads != g.n_head_kv || - image.head_dim != g.head_dim || image.page_size != l.page_size || image.pooled_rows != l.pooled_rows || - image.idx_dim != g.idx_key_dim) { - error = "conversation snapshot: incompatible K/V geometry"; - return false; - } - for (size_t i = 0; i < src.size(); ++i) - if (src[i]->size() != sizes[i]) { error = "conversation snapshot: invalid K/V payload size"; return false; } - const auto dst = pools(st); - for (size_t i = 0; i < src.size(); ++i) - if (sizes[i] && !dst[i]) { error = "conversation snapshot: missing target state buffer"; return false; } - return true; -} - -bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, - int64_t upto, bool index, std::string& error) { - if (!conversation_kv_validate(image, st, g, upto, index, error)) return false; - const std::array src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; - const auto dst = pools(st); - for (size_t i = 0; i < src.size(); ++i) - if (!src[i]->visit(0, src[i]->size(), [&](const uint8_t* p, size_t n, size_t at) { - return transfer(static_cast(dst[i]) + at, p, n, error); - })) return false; - // VRAM slots still contain the outgoing conversation. Resolve must refill - // them from the restored authoritative pools before any attention reads. - if (st.kv_mode == 1) strata::kernels::kv_stream_reset(st.map, nullptr); - if (st.kv_mode == 2 && upto > 0) { - auto shapes = strata::kernels::qsa_real_shapes(); - shapes.n_head_kv = g.n_head_kv; shapes.head_dim = g.head_dim; - const int64_t end = (upto + shapes.page_size - 1) / shapes.page_size; - strata::kernels::kv_ring_restore(qsa_attn_pools(st), st.host, qsa_kv_format(st), - std::max(0, end - st.n_slots), end, st.n_slots, shapes, nullptr); - } - const auto status = cudaGetLastError(); - if (status == cudaSuccess) return true; - error = std::string("conversation snapshot residency restore: ") + cudaGetErrorString(status); - return false; -} - -bool conversation_kv_verify(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, - int64_t upto, bool index, uint64_t& fingerprint, std::string& error) { - if (!conversation_kv_validate(image, st, g, upto, index, error)) return false; - std::array buffer; - uint64_t hash = 1469598103934665603ull; - auto compare = [&](const void* device, const uint8_t* expected, size_t bytes, bool include_hash) { - for (size_t offset = 0; offset < bytes;) { - const size_t n = std::min(buffer.size(), bytes - offset); - if (!transfer(buffer.data(), static_cast(device) + offset, n, error)) return false; - if (std::memcmp(buffer.data(), expected + offset, n) != 0) { - error = "conversation snapshot: restored K/V bytes differ"; - return false; - } - if (include_hash) for (size_t i = 0; i < n; ++i) { hash ^= buffer[i]; hash *= 1099511628211ull; } - offset += n; - } - return true; - }; - const std::array saved = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; - const auto authoritative = pools(st); - for (size_t i = 0; i < saved.size(); ++i) - if (!saved[i]->visit(0, saved[i]->size(), [&](const uint8_t* p, size_t n, size_t at) { - return compare(static_cast(authoritative[i]) + at, p, n, true); - })) return false; - if (st.kv_mode == 2 && image.cells > 0) { - const auto resident = pools(st, true); - const int64_t end = image.cells / image.page_size; - const int64_t begin = std::max(0, end - st.n_slots); - for (size_t i = 0; i < 4; ++i) { - if (saved[i]->empty()) continue; - const size_t page_bytes = saved[i]->size() / size_t(end); - for (int64_t page = begin; page < end; ++page) - if (!saved[i]->visit(size_t(page) * page_bytes, page_bytes, - [&](const uint8_t* p, size_t n, size_t at) { - const size_t offset = size_t(page % st.n_slots) * page_bytes + at - size_t(page) * page_bytes; - return compare(static_cast(resident[i]) + offset, p, n, false); - })) return false; - } - } - fingerprint = hash; - return true; -} - -} // namespace strata::core diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp deleted file mode 100644 index 1f1de53..0000000 --- a/src/core/conversation_snapshot_test.cpp +++ /dev/null @@ -1,324 +0,0 @@ -#include "strata/core/conversation_snapshot.hpp" -#include "strata/kernels/kv_q4.hpp" -#include - -#include -#include -#include -#include -#include - -using namespace strata::core; -using namespace strata::kernels; - -namespace { -int checks = 0; -void check(bool ok, const char* label) { - ++checks; - if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); } -} -void cuda_check(cudaError_t e) { - if (e != cudaSuccess) { std::fprintf(stderr, "CUDA: %s\n", cudaGetErrorString(e)); std::exit(1); } -} -struct Fixture { - ModelGeometry g; - QsaState state; - std::vector device, host; - std::array sources{}; - std::array sizes{}; - - template void alloc(T*& p, size_t n, bool pinned = false) { - if (!n) return; - void* raw = nullptr; - if (pinned) { - cuda_check(cudaHostAlloc(&raw, n, cudaHostAllocMapped)); - host.push_back(raw); - void* mapped = nullptr; - cuda_check(cudaHostGetDevicePointer(&mapped, raw, 0)); - p = static_cast(mapped); - } else { - cuda_check(cudaMalloc(&raw, n)); device.push_back(raw); p = static_cast(raw); - } - } - Fixture(int fmt, int mode) { - auto& st = state; - st.kv_mode = mode; st.kv_int8 = fmt==kKvInt8; st.kv_q4 = fmt==kKvQ4; st.kv_hybrid = fmt==3; - st.n_pages = 24; st.n_slots = mode ? 4 : st.n_pages; - st.max_cells = st.n_pages * 4; st.idx_pooled_rows = mode==2 ? 2 : st.max_cells/4+2; - const size_t per = fmt==kKvQ4 ? kv_q4_bytes_per_head((int)g.head_dim) : g.head_dim*((st.kv_int8 || st.kv_hybrid) ? 1:2); - const size_t rows = st.max_cells*g.n_head_kv, slot_rows = st.n_slots*4*g.n_head_kv; - sizes = {rows*per, rows*per, fmt==kKvInt8 ? rows*(g.head_dim/64)*2:0, - fmt==kKvInt8 ? rows*(g.head_dim/64)*2:0, (size_t)st.idx_pooled_rows*g.idx_key_dim*4}; - if (fmt==3) { - sizes = {rows*per, rows*kv_q4_bytes_per_head((int)g.head_dim), rows*(g.head_dim/64)*2, 0, - (size_t)st.idx_pooled_rows*g.idx_key_dim*4}; - alloc(st.k_q,sizes[0]); alloc(st.v_q4,sizes[1]); alloc(st.k_scale,sizes[2]); - sources[0]=st.k_q; sources[1]=st.v_q4; sources[2]=st.k_scale; - } else if (fmt==kKvQ4) { - alloc(st.k_q4,slot_rows*per); alloc(st.v_q4,slot_rows*per); - if (mode) {alloc(st.host.k_q4,sizes[0],true); alloc(st.host.v_q4,sizes[1],true);} - sources[0]=mode?st.host.k_q4:st.k_q4; sources[1]=mode?st.host.v_q4:st.v_q4; - } else if (fmt==kKvInt8) { - alloc(st.k_q,slot_rows*per); alloc(st.v_q,slot_rows*per); - alloc(st.k_scale,slot_rows*(g.head_dim/64)*2); alloc(st.v_scale,slot_rows*(g.head_dim/64)*2); - if (mode) { - alloc(st.host.k_q,sizes[0],true); alloc(st.host.v_q,sizes[1],true); - alloc(st.host.k_scale,sizes[2],true); alloc(st.host.v_scale,sizes[3],true); - } - sources[0]=mode?st.host.k_q:st.k_q; sources[1]=mode?st.host.v_q:st.v_q; - sources[2]=mode?st.host.k_scale:st.k_scale; sources[3]=mode?st.host.v_scale:st.v_scale; - } else { - alloc(st.k_pool,slot_rows*per); alloc(st.v_pool,slot_rows*per); - if (mode) {alloc(st.host.k_pool,sizes[0],true); alloc(st.host.v_pool,sizes[1],true);} - sources[0]=mode?st.host.k_pool:st.k_pool; sources[1]=mode?st.host.v_pool:st.v_pool; - } - alloc(st.idx_pooled,sizes[4]); sources[4]=st.idx_pooled; - alloc(st.page_table,st.n_pages*4); - if (mode==1) { - auto& m=st.map; - m.page_table=st.page_table; m.n_blocks=st.n_pages; m.n_slots=st.n_slots; - alloc(m.slot_block,st.n_slots*4); alloc(m.slot_stamp,st.n_slots*4); alloc(m.slot_ref,st.n_slots*4); - alloc(m.miss_block,st.n_slots*4); alloc(m.miss_slot,st.n_slots*4); alloc(m.ctl,kKvCtlInts*4); - } else if (mode==2) { - kv_ring_table(st.page_table,st.n_pages,st.n_slots,nullptr); - } - } - void fill(uint8_t salt) { - for (size_t i=0;i data(sizes[i]); - for (size_t j=0;j offset) - cuda_check(cudaMemset(static_cast(sources[i])+offset, salt, sizes[i]-offset)); - } - } - ~Fixture() { for (void* p:device) cudaFree(p); for (void* p:host) cudaFreeHost(p); } -}; -bool equal(const ConversationKv& a,const ConversationKv& b) { - return a.k==b.k && a.v==b.v && a.k_scale==b.k_scale && a.v_scale==b.v_scale && a.pooled==b.pooled; -} - -void full_session(int fmt, int mode, int experts) { - Fixture main(fmt,mode), draft(fmt==3?kKvInt8:fmt,2); - auto& g=main.g; - g.n_layers=4; g.n_expert=experts; - g.ssm_state_size=2; g.ssm_v_heads=2; g.ssm_conv_channels=8; - SessionState ss; - ss.max_cells=96; ss.qsa_states=&main.state; - ss.layer_hi=g.n_layers; ss.gdn_alloc=g.n_gdn_layers(); ss.qsa_alloc=g.n_qsa_layers(); // the whole-model carve - std::string err; - ConversationStateSizes sizes; - check(conversation_state_sizes(g,sizes,err),"whole-session geometry sizes"); - main.alloc(ss.gdn_state,sizes.gdn); main.alloc(ss.ple_hist,sizes.ple); - main.alloc(main.state.idx_tail,sizes.tail); main.alloc(main.state.idx_dead,sizes.dead); - main.alloc(main.state.idx_block_pos,sizes.block_pos); - std::vector ids(65); - for (size_t i=0;i images; - std::vector checkpoints; - auto fill=[&](uint8_t salt) { - main.fill(salt); draft.fill(salt); - for (const auto& [p,n] : std::vector>{ - {ss.gdn_state,sizes.gdn},{ss.ple_hist,sizes.ple},{main.state.idx_tail,sizes.tail}, - {main.state.idx_dead,sizes.dead},{main.state.idx_block_pos,sizes.block_pos}}) - cuda_check(cudaMemset(p,salt,n)); - // A real indexer maintains its spare pooled row as a copy of idx_dead. - cuda_check(cudaMemcpy(main.state.idx_pooled+(ids.size()/4)*g.idx_key_dim, - main.state.idx_dead,sizes.dead,cudaMemcpyDeviceToDevice)); - cuda_check(cudaDeviceSynchronize()); - }; - fill(13); - ConversationCheckpoint checkpoint; - checkpoint.ids.assign(ids.begin(),ids.begin()+3); - check(conversation_checkpoint_save(checkpoint,ss,g,err),"save complete running checkpoint"); - checkpoint.used = 17; - checkpoints.push_back(std::move(checkpoint)); - const ConversationView view{ids,images,checkpoints,true}; - SavedConversation a,b,restored; - check(conversation_snapshot_save(a,view,ss,g,draft.state,err),"capture complete A"); - check(a.checkpoints[0].used == 17,"upstream checkpoint LRU stamp survives capture"); - fill(177); - check(conversation_snapshot_save(b,view,ss,g,draft.state,err),"capture complete B"); - check(a.live.dead!=b.live.dead,"different opening-state spare keys in regression fixture"); - auto bad=a; bad.kv.back().k.pop_back(); - check(conversation_snapshot_restore(bad,ss,g,draft.state,err)==ConversationRestore::invalid, - "reject invalid late draft before any main-layer write"); - check(conversation_snapshot_save(restored,view,ss,g,draft.state,err),"capture B after refused restore"); - check(restored.live.gdn==b.live.gdn && restored.live.dead==b.live.dead && - equal(restored.kv[0],b.kv[0]) && equal(restored.kv[1],b.kv[1]),"refusal preserves all tested state"); - check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore complete A"); - check(conversation_snapshot_save(restored,view,ss,g,draft.state,err),"capture restored A"); - check(restored.live.gdn==a.live.gdn && restored.live.ple==a.live.ple && restored.live.tails==a.live.tails && - restored.live.dead==a.live.dead && restored.live.block_pos==a.live.block_pos && - equal(restored.kv[0],a.kv[0]) && equal(restored.kv[1],a.kv[1]),"whole-session A/B/A exactness including spare key"); - check(ss.ple_prev[0]==64 && ss.ple_prev[1]==65,"PLE token window reconstructed"); - for (int64_t dirty : {65, 3, 0}) { - check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore growth fixture base"); - ConversationKvReuse reuse{a.kv,65,dirty}; - const uint8_t* original = nullptr; - reuse.kv[0].k.visit(0,1,[&](const uint8_t* p,size_t,size_t){original=p;return true;}); - main.fill_after(91,dirty); draft.fill_after(91,std::max(0,dirty-1)); - cuda_check(cudaMemset(ss.gdn_state,91,sizes.gdn)); - ids.resize(70); - for (size_t i=65;i=4)==(reused>0),"only complete unchanged pages or rows are retained"); - incremental.kv[0].k.visit(0,1,[&](const uint8_t* p,size_t,size_t){ - check(p==original,"growth never reallocates the retained payload");return true; - }); - check(conversation_snapshot_restore(incremental,ss,g,draft.state,err)==ConversationRestore::restored,"restore segmented incremental snapshot"); - uint64_t fingerprint=0; - check(conversation_kv_verify(incremental.kv.back(),draft.state,g,70,false,fingerprint,err),"incremental draft authoritative and ring read-back"); - ids.resize(65); - } - { - // a layer split's later stage: the same image WITHOUT the draft layer's K/V (draft == nullptr) - check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore A before stage images"); - size_t with_draft=0,without=0; - check(conversation_snapshot_bytes(view,ss,g,draft.state,with_draft,err) && - conversation_snapshot_bytes(view,ss,g,nullptr,without,err) && without0 && incremental.bytes()<=peak && equal(incremental.kv[0],fresh.kv[0]) && - incremental.live.gdn==fresh.live.gdn,"an incremental stage capture reuses pages and equals a full one"); - SavedConversation split_image=stage; - split_image.stage_images.push_back(stage); - check(!conversation_snapshot_validate(split_image,ss,g,draft.state,err), - "a layer split's image is refused by the whole-session form"); - ConversationKvReuse wrong{a.kv,65,65,{}}; - check(!conversation_snapshot_capture_bytes(wrong,view,ss,g,nullptr,peak,err),"a draft image's K/V is not a stage's reuse"); - } - check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore A after stage images"); - check(conversation_checkpoint_restore(a.checkpoints[0],ss,g,err),"restore early running checkpoint"); - std::vector spare(sizes.dead); - cuda_check(cudaMemcpy(spare.data(),main.state.idx_pooled,sizes.dead,cudaMemcpyDeviceToHost)); - check(spare==a.checkpoints[0].dead,"checkpoint rebuilds spare row over a later completed block"); - check(ss.ple_prev[0]==2 && ss.ple_prev[1]==3,"checkpoint PLE token window"); -} -} - -int main() { - int devices=0; - if (cudaGetDeviceCount(&devices)!=cudaSuccess || !devices) return 77; - for (int fmt : std::array{kKvF16,kKvInt8,kKvQ4,3}) for (int mode : {0,1,2}) { - if (fmt==3 && mode!=0) continue; - Fixture f(fmt,mode); - if (fmt==3) { - std::string err; - ConversationKv invalid; - for (int unsupported : {1,2}) { - f.state.kv_mode=unsupported; - check(conversation_kv_bytes(f.state,f.g,9,true)==0,"hybrid streaming/ring rejected without block-mover abort"); - check(!conversation_kv_save(invalid,f.state,f.g,9,true,err),"hybrid streaming/ring capture fails closed"); - } - f.state.kv_mode=0; - } - { - std::string err; - ConversationKv invalid; - for (const int64_t bad : {-1LL, 97LL, (long long) std::numeric_limits::max()}) { - check(!conversation_kv_save(invalid,f.state,f.g,bad,mode!=2,err),"reject invalid save extent before allocation"); - check(!conversation_kv_restore(invalid,f.state,f.g,bad,mode!=2,err),"reject invalid restore extent before copying"); - check(conversation_kv_bytes(f.state,f.g,bad,mode!=2)==0,"invalid extent cannot overflow byte estimate"); - } - } - for (int64_t upto : {0,1,3,4,5,63,64,65,96}) { - const bool index=mode!=2; - std::string err; - f.fill(13); - ConversationKv a,b,restored; - cuda_check(cudaDeviceSynchronize()); - check(conversation_kv_save(a,f.state,f.g,upto,index,err),"save A"); - check(a.bytes()==conversation_kv_bytes(f.state,f.g,upto,index),"size estimate equals snapshot payload"); - f.fill(177); - check(conversation_kv_save(b,f.state,f.g,upto,index,err),"save B"); - check(upto==0 || !equal(a,b),"fixture changes state"); - check(conversation_kv_restore(a,f.state,f.g,upto,index,err),"restore A over B"); - cuda_check(cudaDeviceSynchronize()); - check(conversation_kv_save(restored,f.state,f.g,upto,index,err),"read back restored A"); - check(equal(a,restored),"A/B/A byte-exact K/V and indexer state"); - uint64_t fingerprint = 0; - check(conversation_kv_verify(a,f.state,f.g,upto,index,fingerprint,err),"verify restored authoritative and resident bytes without rewriting them"); - if (mode==1) { - std::vector table((size_t)f.state.n_pages); - cuda_check(cudaMemcpy(table.data(),f.state.page_table,table.size()*4,cudaMemcpyDeviceToHost)); - check(std::all_of(table.begin(),table.end(),[](int32_t x){return x==-1;}),"stale VRAM pages invalidated"); - } - if (mode==2 && upto>0) { - const auto s=qsa_real_shapes(); - const int64_t b1=(upto+s.page_size-1)/s.page_size,b0=std::max(0,b1-f.state.n_slots); - const size_t block=kv_block_bytes(s,fmt)/2; - // Codes and scales are separate in INT8; check code bytes here. - const size_t code_block=fmt==kKvInt8 ? s.page_size*s.n_head_kv*s.head_dim : block; - const void* slots=fmt==kKvQ4?(void*)f.state.k_q4:fmt==kKvInt8?(void*)f.state.k_q:(void*)f.state.k_pool; - std::vector got(code_block); - for (int64_t page=b0;page expected(code_block); - check(a.k.read(expected.data(), page*code_block, code_block),"read segmented expected draft page"); - check(got == expected,"draft ring contains restored pages"); - } - } - auto bad=a; bad.head_dim++; - check(!conversation_kv_restore(bad,f.state,f.g,upto,index,err),"reject incompatible geometry"); - if (fmt==kKvInt8) { - // #293: INT8 K/V saved through the Hadamard rotation (STRATA_KV_ROT=1) never restores into a state - // without it, nor the reverse - f.state.kv_rot=true; - ConversationKv rotated; - check(conversation_kv_save(rotated,f.state,f.g,upto,index,err),"save rotated INT8"); - check(!conversation_kv_restore(a,f.state,f.g,upto,index,err),"unrotated image into a rotated state rejected"); - f.state.kv_rot=false; - check(!conversation_kv_restore(rotated,f.state,f.g,upto,index,err),"rotated image into an unrotated state rejected"); - check(conversation_kv_restore(a,f.state,f.g,upto,index,err),"unrotated image still restores"); - } - if (!a.k.empty()) { - bad=a; bad.k.pop_back(); - check(!conversation_kv_restore(bad,f.state,f.g,upto,index,err),"reject malformed payload"); - } - } - } - for (int fmt : {kKvF16,kKvInt8,kKvQ4}) for (int mode : {0,1}) for (int experts : {256,512}) - full_session(fmt,mode,experts); - for (int experts : {256,512}) full_session(3,0,experts); - std::printf("conversation_snapshot_test: %d checks passed\n",checks); -} diff --git a/src/core/conversation_state.cpp b/src/core/conversation_state.cpp deleted file mode 100644 index c53d552..0000000 --- a/src/core/conversation_state.cpp +++ /dev/null @@ -1,340 +0,0 @@ -#include "strata/core/conversation_snapshot.hpp" -#include "conversation_checked.hpp" - -#include -#include -#include - -namespace strata::core { -namespace { -using conversation_detail::add; -using conversation_detail::product; - -std::array geometry_key(const ModelGeometry& g) { - return {g.n_embd, g.n_layers, g.qsa_interval, g.ssm_state_size, g.ssm_k_heads, - g.ssm_v_heads, g.ssm_d_conv, g.ssm_conv_channels, g.ssm_value_dim, - g.n_head, g.n_head_kv, g.head_dim, g.idx_q_heads, g.idx_key_dim, - g.hc, g.hc_lr, g.n_expert, g.n_ff}; -} - -bool fail(std::string& error, const char* message) { - error = std::string("conversation snapshot: ") + message; - return false; -} - -bool sync(std::string& error) { - const auto status = cudaDeviceSynchronize(); - if (status == cudaSuccess) return true; - error = std::string("conversation snapshot synchronize: ") + cudaGetErrorString(status); - return false; -} - -bool copy(void* dst, const void* src, size_t bytes, std::string& error) { - if (!bytes) return true; - if (!dst || !src) return fail(error, "missing running-state buffer"); - const auto status = cudaMemcpy(dst, src, bytes, cudaMemcpyDefault); - if (status == cudaSuccess) return true; - error = std::string("conversation snapshot running-state copy: ") + cudaGetErrorString(status); - return false; -} - -// The session's carve (#216): `qsa_states` keeps global ordinals and holds the owned ones -// [qsa_ord0, qsa_ord0 + qsa_alloc); `gdn_state` holds `gdn_alloc` rows. A whole-model session owns every layer. -size_t owned_qsa(const SessionState& ss) { return (size_t) std::max(ss.qsa_alloc, 0); } -const QsaState& owned(const SessionState& ss, size_t j) { return ss.qsa_states[(size_t) ss.qsa_ord0 + j]; } - -bool image_keys(const std::vector& images, size_t tokens) { - int64_t previous = -1; - for (const auto& image : images) { - if (image.start <= previous || image.start < 0 || (uint64_t) image.start >= tokens) return false; - previous = image.start; - } - return true; -} - -bool checkpoint_targets(const SessionState& ss, const ModelGeometry& g, size_t tokens, - ConversationStateSizes& z, std::string& error) { - if (!conversation_session_sizes(g, ss, z, error)) return false; - if (ss.max_cells < 0 || tokens > (uint64_t) ss.max_cells || (z.gdn && !ss.gdn_state) || - (owned_qsa(ss) && !ss.qsa_states)) return fail(error, "invalid session running-state targets"); - for (size_t j = 0; j < owned_qsa(ss); ++j) { - 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(0, st.idx_pooled_rows)) || - !product(pooled_bytes, {tokens / (uint64_t) block + 1, (uint64_t) g.idx_key_dim, sizeof(float)})) - return fail(error, "invalid indexer running-state target"); - } - return true; -} - -bool view_validate(const ConversationView& view, const SessionState& ss, - const ModelGeometry& g, std::string& error) { - ConversationStateSizes z; - if (!checkpoint_targets(ss, g, view.ids.size(), z, error)) return false; - if (view.ids.empty() || !image_keys(view.images, view.ids.size()) || - std::any_of(view.ids.begin(), view.ids.end(), [](int32_t id) { return id < 0; })) - return fail(error, "invalid live token/image metadata"); - for (const auto& c : view.checkpoints) { - if (!c.stage_parts.empty() || c.ids.empty() || c.ids.size() > view.ids.size() || - !std::equal(c.ids.begin(), c.ids.end(), view.ids.begin())) - return fail(error, "checkpoint is not a live token prefix"); - if (!conversation_checkpoint_validate(c, ss, g, error)) return false; - size_t image = 0; - for (const auto& key : view.images) { - if ((uint64_t) key.start >= c.ids.size()) break; - if (image >= c.imgs.size() || !(c.imgs[image++] == key)) - return fail(error, "checkpoint image identity differs"); - } - if (image != c.imgs.size()) return fail(error, "checkpoint image prefix differs"); - } - return true; -} - -bool metadata_bytes(const ConversationCheckpoint& c, size_t& total) { - size_t ids = 0, images = 0; - if (!product(ids, {c.ids.size(), sizeof(int32_t)}) || - !product(images, {c.imgs.size(), sizeof(ConversationImageKey)})) return false; - for (size_t n : {ids, images, c.gdn.size(), c.ple.size(), c.tails.size(), c.dead.size(), c.block_pos.size()}) - if (!add(total, n)) return false; - return true; -} -} // namespace - -bool conversation_state_sizes(const ModelGeometry& g, ConversationStateSizes& z, std::string& error) { - z = {}; - const auto key = geometry_key(g); - // A plain-residual model (hc 1) has no hyper-connection rate (key 15) and a dense-attention model has no - // indexer (keys 12 and 13, the indexer heads and key width): those zeros are the geometry, not an error. - for (size_t i = 0; i < key.size(); ++i) { - const bool may_be_zero = i == 1 || (!g.has_indexer() && (i == 12 || i == 13)) || (g.hc == 1 && i == 15); - if (key[i] < 0 || (!may_be_zero && key[i] == 0)) return fail(error, "invalid model geometry"); - } - 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)}) || - !add(recurrence, convolution) || - !product(z.gdn, {(uint64_t) g.n_gdn_layers(), recurrence, sizeof(float)}) || - !product(z.ple, {strata::kernels::NG_HIST, strata::kernels::NG_HC_DIM, sizeof(float)}) || - !product(z.tail, {(uint64_t) (strata::kernels::qsa_real_shapes().idx_block - 1), - (uint64_t) g.idx_key_dim, sizeof(float)}) || - !product(z.dead, {(uint64_t) g.idx_key_dim, sizeof(float)})) - return fail(error, "running-state byte count overflow"); - z.block_pos = g.has_indexer() ? sizeof(int32_t) : 0; // no indexer: no block position, no tail, no dead row - 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}) || - !product(total, {(uint64_t) g.n_qsa_layers(), z.block_pos})) - return fail(error, "indexer byte count overflow"); - return true; -} - -bool conversation_session_sizes(const ModelGeometry& g, const SessionState& ss, ConversationStateSizes& z, - std::string& error) { - if (!conversation_state_sizes(g, z, error)) return false; - const int64_t n_gdn = g.n_gdn_layers(), n_qsa = g.n_qsa_layers(); - if (ss.gdn_alloc < 0 || ss.gdn_alloc > n_gdn || ss.qsa_ord0 < 0 || ss.qsa_alloc < 0 || - ss.qsa_ord0 > n_qsa || ss.qsa_alloc > n_qsa - ss.qsa_ord0) - return fail(error, "invalid session layer carve"); - // z.gdn is n_gdn whole rows; the session holds gdn_alloc of them (all of them for the default full range) - z.gdn = n_gdn > 0 ? z.gdn / (size_t) n_gdn * (size_t) ss.gdn_alloc : 0; - return true; -} - -bool conversation_checkpoint_validate(const ConversationCheckpoint& c, const SessionState& ss, - const ModelGeometry& g, std::string& error) { - ConversationStateSizes z; - if (!checkpoint_targets(ss, g, c.ids.size(), z, error)) return false; - const size_t layers = owned_qsa(ss); - if (c.gdn.size() != z.gdn || c.ple.size() != (ss.ple_hist ? z.ple : 0) || - c.tails.size() != layers * z.tail || c.dead.size() != layers * z.dead || - c.block_pos.size() != layers * z.block_pos || !image_keys(c.imgs, c.ids.size())) - return fail(error, "invalid checkpoint running-state payload"); - return true; -} - -bool conversation_checkpoint_save(ConversationCheckpoint& c, const SessionState& ss, - const ModelGeometry& g, std::string& error) { - ConversationStateSizes z; - if (!checkpoint_targets(ss, g, c.ids.size(), z, error)) return false; - const size_t layers = owned_qsa(ss); - c.gdn.resize(z.gdn); c.ple.resize(ss.ple_hist ? z.ple : 0); - c.tails.resize(layers * z.tail); c.dead.resize(layers * z.dead); c.block_pos.resize(layers * z.block_pos); - if (!copy(c.gdn.data(), ss.gdn_state, c.gdn.size(), error) || - !copy(c.ple.data(), ss.ple_hist, c.ple.size(), error)) return false; - for (size_t j = 0; j < layers; ++j) { - const auto& st = owned(ss, j); - if (!copy(c.tails.data() + j * z.tail, st.idx_tail, z.tail, error) || - !copy(c.dead.data() + j * z.dead, st.idx_dead, z.dead, error) || - !copy(c.block_pos.data() + j * z.block_pos, st.idx_block_pos, z.block_pos, error)) return false; - } - return true; -} - -bool conversation_checkpoint_restore(const ConversationCheckpoint& c, SessionState& ss, - const ModelGeometry& g, std::string& error) { - if (!conversation_checkpoint_validate(c, ss, g, error)) return false; - ConversationStateSizes z; - if (!conversation_session_sizes(g, ss, z, error)) return false; - if (!copy(ss.gdn_state, c.gdn.data(), c.gdn.size(), error) || - !copy(ss.ple_hist, c.ple.data(), c.ple.size(), error)) return false; - for (size_t j = 0; j < owned_qsa(ss); ++j) { - const auto& st = owned(ss, j); - if (!copy(st.idx_tail, c.tails.data() + j * z.tail, z.tail, error) || - !copy(st.idx_dead, c.dead.data() + j * z.dead, z.dead, error) || - !copy(st.idx_block_pos, c.block_pos.data() + j * z.block_pos, z.block_pos, error)) return false; - if (!c.ids.empty()) { - const size_t row = c.ids.size() / strata::kernels::qsa_real_shapes().idx_block; - if (!copy(st.idx_pooled + row * g.idx_key_dim, c.dead.data() + j * z.dead, z.dead, error)) return false; - } - } - const size_t tokens = c.ids.size(); - ss.ple_prev[0] = tokens >= 2 ? c.ids[tokens - 2] : -1; - ss.ple_prev[1] = tokens >= 1 ? c.ids[tokens - 1] : -1; - return sync(error); -} - -bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& ss, - const ModelGeometry& g, const QsaState* draft, size_t& bytes, std::string& error) { - bytes = 0; - if (!view_validate(view, ss, g, error)) return false; - ConversationStateSizes z; - if (!conversation_session_sizes(g, ss, z, error)) return false; - size_t ids = 0, images = 0, checkpoints = 0, layers = 0, tails = 0, dead = 0, positions = 0; - const auto qsa = (uint64_t) owned_qsa(ss); - if (!product(ids, {view.ids.size(), sizeof(int32_t)}) || - !product(images, {view.images.size(), sizeof(ConversationImageKey)}) || - !product(checkpoints, {view.checkpoints.size(), sizeof(ConversationCheckpoint)}) || - !product(layers, {qsa + (draft ? 1 : 0), sizeof(ConversationKv)}) || - !product(tails, {qsa, z.tail}) || !product(dead, {qsa, z.dead}) || - !product(positions, {qsa, z.block_pos})) return fail(error, "snapshot metadata byte count overflow"); - for (size_t n : {ids, images, checkpoints, layers, tails, dead, positions, z.gdn, ss.ple_hist ? z.ple : 0}) - if (!add(bytes, n)) return fail(error, "snapshot byte count overflow"); - for (const auto& c : view.checkpoints) - if (!metadata_bytes(c, bytes)) return fail(error, "checkpoint byte count overflow"); - const int64_t upto = (int64_t) view.ids.size(); // view_validate bounds this by signed max_cells - for (uint64_t i = 0; i < qsa + (draft ? 1 : 0); ++i) { - const auto& st = i == qsa ? *draft : owned(ss, (size_t) i); - const size_t n = conversation_kv_bytes(st, g, upto, i != qsa); - if (!n || !add(bytes, n)) return fail(error, "invalid or overflowing K/V byte estimate"); - } - return true; -} - -bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view, - const SessionState& ss, const ModelGeometry& g, - const QsaState* draft, size_t& bytes, std::string& error) { - if (!conversation_snapshot_bytes(view, ss, g, draft, bytes, error)) return false; - if (reuse.kv.empty()) return true; - const size_t layers = owned_qsa(ss) + (draft ? 1 : 0); - if (reuse.kv.size() != layers || reuse.unchanged_tokens < 0 || - reuse.unchanged_tokens > reuse.captured_tokens || reuse.unchanged_tokens > int64_t(view.ids.size())) - return fail(error, "invalid retained K/V prefix"); - for (size_t i = 0; i < layers; ++i) { - const bool index = i < owned_qsa(ss); - const auto& st = index ? owned(ss, i) : *draft; - if (!conversation_kv_validate(reuse.kv[i], st, g, reuse.captured_tokens, index, error)) return false; - const size_t fresh = conversation_kv_bytes(st, g, int64_t(view.ids.size()), index); - size_t retained = 0; - if (!conversation_kv_capture_bytes(reuse.kv[i], st, g, int64_t(view.ids.size()), index, retained, error)) return false; - bytes -= fresh; - if (!add(bytes, retained)) return fail(error, "retained K/V allocation overflow"); - } - size_t directory = 0; - if (!product(directory, {reuse.kv.capacity() - layers, sizeof(ConversationKv)}) || !add(bytes, directory)) - return fail(error, "retained K/V directory overflow"); - return true; -} - -bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, - const SessionState& ss, const ModelGeometry& g, - const QsaState* draft, std::string& error, - ConversationKvReuse reuse, size_t* reused_bytes) { - size_t estimate = 0; - if (!conversation_snapshot_capture_bytes(reuse, view, ss, g, draft, estimate, error) || !sync(error)) return false; - // Build into a new object so a failure cannot publish a partial snapshot. - SavedConversation captured; - captured.geometry = geometry_key(g); - captured.layer_lo = ss.layer_lo; captured.layer_hi = ss.layer_hi; - captured.live.ids = view.ids; captured.live.imgs = view.images; - captured.cvec = view.cvec; captured.checkpoints = view.checkpoints; - const int64_t unchanged = reuse.kv.empty() ? 0 : reuse.unchanged_tokens; - captured.kv = std::move(reuse.kv); - const size_t layers = owned_qsa(ss); - captured.kv.resize(layers + (draft ? 1 : 0)); - if (!conversation_checkpoint_save(captured.live, ss, g, error)) return false; - const int64_t upto = (int64_t) view.ids.size(); - for (size_t j = 0; j < layers; ++j) - if (!conversation_kv_save(captured.kv[j], owned(ss, j), g, upto, true, error, - unchanged, reused_bytes)) return false; - // The draft's final cell may not have been computed when the output cap was - // reached. Refresh that page even when the main prefix continued unchanged. - if (draft && !conversation_kv_save(captured.kv.back(), *draft, g, upto, false, error, - std::max(0, unchanged - 1), reused_bytes)) return false; - image = std::move(captured); - return true; -} - -bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& ss, - const ModelGeometry& g, const QsaState* draft, std::string& error) { - if (!image.live.stage_parts.empty()) - return fail(error, "a running checkpoint's stage parts belong in the stage images, not in live.stage_parts"); - if (image.geometry != geometry_key(g)) return fail(error, "incompatible runtime geometry"); - // an image holds exactly one carve's running state and K/V: same layer range or nothing - if (image.layer_lo != ss.layer_lo || image.layer_hi != ss.layer_hi) - return fail(error, "snapshot from another session layer range"); - const ConversationView view{image.live.ids, image.live.imgs, image.checkpoints, image.cvec}; - if (!view_validate(view, ss, g, error) || !conversation_checkpoint_validate(image.live, ss, g, error)) return false; - const size_t layers = owned_qsa(ss); - if (image.kv.size() != layers + (draft ? 1 : 0)) return fail(error, "invalid K/V layer count"); - const int64_t upto = (int64_t) image.live.ids.size(); - for (size_t j = 0; j < layers; ++j) - if (!conversation_kv_validate(image.kv[j], owned(ss, j), g, upto, true, error)) return false; - return !draft || conversation_kv_validate(image.kv.back(), *draft, g, upto, false, error); -} - -ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& ss, - const ModelGeometry& g, const QsaState* draft, std::string& error) { - if (!conversation_snapshot_validate(image, ss, g, draft, error)) return ConversationRestore::invalid; - if (!sync(error)) return ConversationRestore::transfer_failed; - const int64_t upto = (int64_t) image.live.ids.size(); - for (size_t j = 0; j < owned_qsa(ss); ++j) - if (!conversation_kv_restore(image.kv[j], owned(ss, j), g, upto, true, error)) - return ConversationRestore::transfer_failed; - if ((draft && !conversation_kv_restore(image.kv.back(), *draft, g, upto, false, error)) || - !conversation_checkpoint_restore(image.live, ss, g, error)) return ConversationRestore::transfer_failed; - return ConversationRestore::restored; -} - -// the draft layer's K/V included (the stage that owns the draft head, or no layer split) -bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& ss, const ModelGeometry& g, - const QsaState& draft, size_t& bytes, std::string& error) { - return conversation_snapshot_bytes(view, ss, g, &draft, bytes, error); -} -bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view, - const SessionState& ss, const ModelGeometry& g, const QsaState& draft, - size_t& bytes, std::string& error) { - return conversation_snapshot_capture_bytes(reuse, view, ss, g, &draft, bytes, error); -} -bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, const SessionState& ss, - const ModelGeometry& g, const QsaState& draft, std::string& error, - ConversationKvReuse reuse, size_t* reused_bytes) { - return conversation_snapshot_save(image, view, ss, g, &draft, error, std::move(reuse), reused_bytes); -} -bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& ss, const ModelGeometry& g, - const QsaState& draft, std::string& error) { - // the whole-session form: a layer split's image (stage images) is restored stage by stage, never through here - if (!image.stage_images.empty()) return fail(error, "a layer split's image restored as a single session"); - return conversation_snapshot_validate(image, ss, g, &draft, error); -} -ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& ss, - const ModelGeometry& g, const QsaState& draft, std::string& error) { - return conversation_snapshot_restore(image, ss, g, &draft, error); -} -} // namespace strata::core diff --git a/src/core/conversation_validation_test.cpp b/src/core/conversation_validation_test.cpp deleted file mode 100644 index f993eeb..0000000 --- a/src/core/conversation_validation_test.cpp +++ /dev/null @@ -1,239 +0,0 @@ -// Host-only validation fixtures. CUDA is linked but must never be initialized: -// invalid restores must return before the first CUDA call or destination write. -#include "strata/core/conversation_snapshot.hpp" -#include "strata/kernels/kv_q4.hpp" - -#include -#include -#include -#include -#include - -#if defined(CONVERSATION_TEST_TRANSFERS) -// GNU/ELF link wrapping exercises the actual restore control flow without -// initializing CUDA or deliberately poisoning a real device context. This is -// host-backend fault injection, not a claim of hardware-failure recovery. -namespace { -int copy_calls = 0, sync_calls = 0, fail_copy = 0, fail_sync = 0; -size_t copied_bytes = 0; -} -extern "C" cudaError_t __wrap_cudaMemcpy(void* dst, const void* src, size_t n, cudaMemcpyKind) { - if (++copy_calls == fail_copy) return cudaErrorInvalidValue; - copied_bytes += n; - std::memcpy(dst, src, n); - return cudaSuccess; -} -extern "C" cudaError_t __wrap_cudaDeviceSynchronize() { - return ++sync_calls == fail_sync ? cudaErrorUnknown : cudaSuccess; -} -extern "C" cudaError_t __wrap_cudaGetLastError() { return cudaSuccess; } -#endif - -using namespace strata::core; -namespace { -int checks = 0; -void check(bool ok, const char* label) { - ++checks; - if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); } -} -struct Pools { - QsaState st; - std::array, 8> data; - Pools(const ModelGeometry& g, int format) { - st.max_cells = 96; st.n_pages = st.n_slots = 24; st.idx_pooled_rows = 26; - st.kv_int8 = format == 1; st.kv_q4 = format == 2; - const size_t per = format == 2 ? strata::kernels::kv_q4_bytes_per_head((int) g.head_dim) - : g.head_dim * (format == 1 ? 1 : 2); - data[0].resize(96 * g.n_head_kv * per, 0xa5); data[1] = data[0]; - data[2].resize(format == 1 ? 96 * g.n_head_kv * (g.head_dim / 64) * 2 : 0, 0xa5); data[3] = data[2]; - data[4].resize(26 * g.idx_key_dim * 4, 0xa5); - data[5].resize(3 * g.idx_key_dim * 4, 0xa5); - data[6].resize(g.idx_key_dim * 4, 0xa5); data[7].resize(4, 0xa5); - if (format == 2) { st.k_q4 = data[0].data(); st.v_q4 = data[1].data(); } - else if (format == 1) { - st.k_q = (int8_t*) data[0].data(); st.v_q = (int8_t*) data[1].data(); - st.k_scale = (uint16_t*) data[2].data(); st.v_scale = (uint16_t*) data[3].data(); - } else { st.k_pool = (uint16_t*) data[0].data(); st.v_pool = (uint16_t*) data[1].data(); } - st.idx_pooled = (float*) data[4].data(); st.idx_tail = (float*) data[5].data(); - st.idx_dead = (float*) data[6].data(); st.idx_block_pos = (int32_t*) data[7].data(); - } - ConversationKv image(const ModelGeometry& g, bool index) const { - ConversationKv k; - k.format = qsa_kv_format(st); k.cells = 12; k.page_size = 4; - k.heads = g.n_head_kv; k.head_dim = g.head_dim; k.idx_dim = g.idx_key_dim; - k.pooled_rows = index ? 3 : 0; - k.k.resize(data[0].size() / 8, 13); k.v = k.k; - k.k_scale.resize(data[2].size() / 8, 13); k.v_scale = k.k_scale; - k.pooled.resize(k.pooled_rows * g.idx_key_dim * 4, 13); - return k; - } -}; - -void fixture(int format, int experts, bool zero_qsa, bool ple) { - ModelGeometry g; - g.n_layers = zero_qsa ? 3 : 8; g.n_expert = experts; - g.ssm_state_size = 2; g.ssm_v_heads = 2; g.ssm_conv_channels = 8; - g.n_head_kv = 1; g.head_dim = 64; g.idx_key_dim = 8; - std::string error; - ConversationStateSizes z; - check(conversation_state_sizes(g, z, error), "checked canonical/pruned/zero-QSA sizing"); - Pools first(g, format), last(g, format), draft(g, format); - std::array layers{first.st, last.st}; - std::vector gdn(z.gdn, 0xa5), history(ple ? z.ple : 0, 0xa5); - SessionState ss; - ss.max_cells = 96; ss.gdn_state = (float*) gdn.data(); - // the whole-model carve, as session_init leaves a one-GPU session - ss.layer_hi = g.n_layers; ss.gdn_alloc = g.n_gdn_layers(); ss.qsa_alloc = g.n_qsa_layers(); - ss.ple_hist = ple ? (float*) history.data() : nullptr; - ss.qsa_states = zero_qsa ? nullptr : layers.data(); - SavedConversation image; - image.geometry = {g.n_embd,g.n_layers,g.qsa_interval,g.ssm_state_size,g.ssm_k_heads,g.ssm_v_heads, - g.ssm_d_conv,g.ssm_conv_channels,g.ssm_value_dim,g.n_head,g.n_head_kv,g.head_dim, - g.idx_q_heads,g.idx_key_dim,g.hc,g.hc_lr,g.n_expert,g.n_ff}; - image.layer_hi = g.n_layers; - auto checkpoint = [&](size_t tokens) { - ConversationCheckpoint c; - c.ids.resize(tokens); - for (size_t i = 0; i < tokens; ++i) c.ids[i] = (int32_t) i + 1; - c.imgs = {{1, 44}}; - c.gdn.resize(z.gdn, 13); c.ple.resize(ple ? z.ple : 0, 13); - c.tails.resize(g.n_qsa_layers() * z.tail, 13); c.dead.resize(g.n_qsa_layers() * z.dead, 13); - c.block_pos.resize(g.n_qsa_layers() * z.block_pos, 13); - return c; - }; - image.live = checkpoint(9); image.checkpoints.push_back(checkpoint(5)); - image.kv.reserve((size_t) g.n_qsa_layers() + 1); - if (!zero_qsa) { image.kv.push_back(first.image(g, true)); image.kv.push_back(last.image(g, true)); } - image.kv.push_back(draft.image(g, false)); - check(conversation_snapshot_validate(image, ss, g, draft.st, error), "complete image validates without CUDA"); - size_t estimate = 0; - check(conversation_snapshot_bytes({image.live.ids,image.live.imgs,image.checkpoints,true},ss,g,draft.st,estimate,error), - "capture estimate works without CUDA"); - check(estimate == image.bytes(), "estimate covers checkpoint/indexer/spare payloads"); - auto unchanged = [&] { - auto pristine = [](const auto& bytes) { return std::all_of(bytes.begin(),bytes.end(),[](uint8_t b){return b==0xa5;}); }; - if (!pristine(gdn) || !pristine(history) || ss.ple_prev[0] != -1 || ss.ple_prev[1] != -1) return false; - for (const auto* p : {&first,&last,&draft}) for (const auto& bytes : p->data) if (!pristine(bytes)) return false; - return true; - }; - auto reject = [&](const std::function& mutate, const char* label) { - auto bad = image; mutate(bad); - check(conversation_snapshot_restore(bad,ss,g,draft.st,error) == ConversationRestore::invalid,label); - check(unchanged(), "invalid restore did not touch any layer or running-state buffer"); - }; - reject([](auto& s){s.kv.back().k.pop_back();}, "late draft corruption rejected before first layer write"); - reject([](auto& s){s.geometry[16] = 128;}, "different expert geometry rejected"); - reject([](auto& s){s.live.stage_parts.emplace_back();}, "layer-split live state rejected before writes"); - reject([](auto& s){s.checkpoints[0].stage_parts.emplace_back();}, "layer-split checkpoint rejected before writes"); - reject([](auto& s){s.kv.pop_back();}, "missing KV layer rejected"); - reject([](auto& s){s.live.gdn.pop_back();}, "bad live recurrence rejected"); - reject([](auto& s){s.checkpoints.back().gdn.pop_back();}, "bad retained checkpoint rejected"); - reject([](auto& s){s.checkpoints.back().ids[0] = 99;}, "foreign checkpoint prefix rejected"); - reject([](auto& s){s.checkpoints.back().imgs[0].hash++;}, "foreign checkpoint image rejected"); - reject([](auto& s){s.live.imgs[0].start = -1;}, "negative image position rejected"); - reject([](auto& s){s.live.ids[0] = -1;}, "negative live token rejected"); - reject([](auto& s){s.live.ple.push_back(0);}, "PLE size/enabled mismatch rejected"); - reject([](auto& s){s.live.tails.push_back(0);}, "tail size/zero-QSA mismatch rejected"); - if (!zero_qsa) { - reject([](auto& s){s.kv[1].pooled.pop_back();}, "late indexer spare row corruption rejected"); - reject([](auto& s){s.live.dead.pop_back();}, "missing indexer spare key rejected"); - reject([](auto& s){s.live.block_pos.pop_back();}, "missing indexer metadata rejected"); - ss.qsa_states = nullptr; - check(!conversation_snapshot_validate(image,ss,g,draft.st,error), "missing QSA targets rejected"); - ss.qsa_states = layers.data(); - reject([](auto& s){s.layer_lo = 4;}, "snapshot from another layer range rejected"); - // #216's carve: a split stage owning layers [4, 8) holds GDN rows 3..5 and QSA ordinal 1 only - SessionState stage = ss; - stage.layer_lo = 4; stage.gdn_alloc = 3; stage.qsa_ord0 = 1; stage.qsa_alloc = 1; - ConversationStateSizes zs; - check(conversation_session_sizes(g,stage,zs,error) && zs.gdn == z.gdn / 6 * 3 && zs.tail == z.tail, - "carved session sizes cover the owned rows only"); - check(!conversation_checkpoint_validate(image.live,stage,g,error), "whole-model checkpoint rejected by a carve"); - ConversationCheckpoint part = image.live; - part.gdn.resize(zs.gdn); part.tails.resize(zs.tail); part.dead.resize(zs.dead); - part.block_pos.resize(zs.block_pos); - check(conversation_checkpoint_validate(part,stage,g,error), "carve-sized checkpoint validates"); - check(!conversation_snapshot_validate(image,stage,g,draft.st,error), "whole-model snapshot rejected by a carve"); - stage.qsa_alloc = 2; - check(!conversation_session_sizes(g,stage,zs,error), "carve past the last QSA ordinal rejected"); - stage.qsa_alloc = 1; stage.gdn_alloc = 7; - check(!conversation_session_sizes(g,stage,zs,error), "carve past the GDN rows rejected"); - } - auto bad_geometry = g; bad_geometry.ssm_state_size = std::numeric_limits::max(); - check(!conversation_state_sizes(bad_geometry,z,error), "running-state arithmetic overflow rejected"); - bad_geometry = g; bad_geometry.qsa_interval = 0; - check(!conversation_state_sizes(bad_geometry,z,error), "zero layer interval rejected before division"); - bad_geometry = g; bad_geometry.n_head_kv = std::numeric_limits::max(); - check(conversation_kv_bytes(draft.st,bad_geometry,9,false)==0, "KV byte overflow rejected"); -#if defined(CONVERSATION_TEST_TRANSFERS) - auto reset = [&] { - for (auto* p : {&first,&last,&draft}) for (auto& bytes : p->data) std::fill(bytes.begin(),bytes.end(),0xa5); - std::fill(gdn.begin(),gdn.end(),0xa5); std::fill(history.begin(),history.end(),0xa5); - ss.ple_prev[0] = ss.ple_prev[1] = -1; - copy_calls = sync_calls = fail_copy = fail_sync = 0; - }; - reset(); fail_sync = 1; - check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed, - "pre-transfer CUDA synchronization failure is fatal"); - check(copy_calls==0 && unchanged(), "pre-sync failure did not mutate state"); - reset(); fail_copy = 1; - check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed, - "first CUDA transfer failure is fatal"); - check(unchanged(), "first-copy failure did not mutate state"); - reset(); fail_copy = 2; - check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed, - "partial CUDA transfer failure is fatal, not an invalid-image fallback"); - check(!unchanged(), "fault fixture genuinely produced partial state"); - reset(); fail_sync = 2; - check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed, - "post-transfer CUDA synchronization failure is fatal"); - check(copy_calls>0 && !unchanged(), "post-sync failure occurred after state writes"); - reset(); - check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::restored, - "injected host transfer backend completes a valid restore"); - check(gdn==image.live.gdn && history==image.live.ple && ss.ple_prev[0]==8 && ss.ple_prev[1]==9, - "successful restore publishes correct running state and PLE window"); - uint64_t fingerprint = 0; - check(conversation_kv_verify(image.kv.back(),draft.st,g,9,false,fingerprint,error), "read-back verifies complete draft payload"); - draft.data[0][0] ^= 1; - check(!conversation_kv_verify(image.kv.back(),draft.st,g,9,false,fingerprint,error), "read-back detects corrupted draft byte"); - draft.data[0][0] ^= 1; - fail_copy = copy_calls + 1; - check(!conversation_kv_verify(image.kv.back(),draft.st,g,9,false,fingerprint,error), "read-back transfer failure is not a successful fingerprint"); - reset(); copied_bytes = 0; - const ConversationView view{image.live.ids,image.live.imgs,image.checkpoints,true}; - SavedConversation full,incremental; - check(conversation_snapshot_save(full,view,ss,g,draft.st,error), "full capture through host transfer backend"); - const size_t full_copies = copied_bytes; - ConversationKvReuse reuse{full.kv,9,9}; - size_t peak = 0, reused = 0; - check(conversation_snapshot_capture_bytes(reuse,view,ss,g,draft.st,peak,error), "incremental capture admission without transfers"); - copied_bytes = 0; - const bool saved_incrementally = conversation_snapshot_save(incremental,view,ss,g,draft.st,error,std::move(reuse),&reused); - if (!saved_incrementally) std::fprintf(stderr,"capture error: %s\n",error.c_str()); - check(saved_incrementally, "incremental capture through host backend"); - check(reused > 0 && copied_bytes + reused == full_copies, "reused byte count measures transfers actually omitted"); - check(incremental.bytes() <= peak && incremental.live.gdn == full.live.gdn, "running state refreshed within admitted allocation"); - for (size_t i=0;i -#include -#include - -using namespace strata::core; - -namespace { -int g_fail = 0; -int64_t g_checks = 0; -void check(bool ok, const char* what, long long a = 0, long long b = 0) { - ++g_checks; - if (!ok) { - if (++g_fail <= 20) std::printf(" FAIL %s (%lld vs %lld)\n", what, a, b); - } -} - -// verify.cpp run(): sp.counter = pos0, and the kernel draws row t with sp.counter + t -uint64_t verify_row_counter(int64_t pos0, int t) { return (uint64_t) pos0 + (uint64_t) t; } - -// The counters and positions of a chain of `n` drafts made after a window at `p` with `a` accepted (draft()), or for -// draft_first (cell0 = p - 1, a = 0), checked against the next window at `p_next`. -void check_chain(int64_t p, int a, int n, int64_t p_next) { - for (int j = 0; j < n; ++j) { - const int64_t cell = coupled_draft_cell(p, a, j); - // mtp.hpp: cell c predicts the token at c + 2; the next window's row j + 1 holds position p_next + j + 1 - check(cell + 2 == p_next + j + 1, "draft position = its row in the next window", cell + 2, p_next + j + 1); - // row j + 1 is kept iff it equals row j's pick, drawn at p_next + j - check(coupled_draft_counter(cell) == verify_row_counter(p_next, j), "draft counter = verifying row's counter", - (long long) coupled_draft_counter(cell), (long long) verify_row_counter(p_next, j)); - } -} - -// The device ring for one chain: base staged at [cap - h, cap) by the host, draft i at cap + i; draft j's window is -// [coupled_hist_start(cap, j, h), + h). Compared with penalty_rows over (consumed, [next, drafts...]). -void check_history(std::mt19937& rng, int cap, int h, int n_consumed, int n_drafts) { - std::uniform_int_distribution tok(0, 999); - std::vector consumed((size_t) n_consumed), drafts((size_t) n_drafts); - for (auto& t : consumed) t = tok(rng); - for (auto& t : drafts) t = tok(rng); - const int32_t next = tok(rng); - std::vector mapped((size_t) cap, 777777), ring((size_t) (cap + n_drafts), 888888); - coupled_hist_base(consumed.data(), (int64_t) consumed.size(), next, h, mapped.data() + (cap - h)); // set_draft_history - for (int i = cap - h; i < cap; ++i) ring[(size_t) i] = mapped[(size_t) i]; // coupled_stage_kernel - // the next window: [next, drafts...], T = n_drafts + 1 rows; row j checks draft j (row j + 1) - std::vector window; - window.push_back(next); - window.insert(window.end(), drafts.begin(), drafts.end()); - const int T = (int) window.size(); - std::vector rows((size_t) T * (size_t) h); - strata::kernels::penalty_rows(consumed.data(), (int64_t) consumed.size(), window.data(), T, h, rows.data()); - for (int j = 0; j < n_drafts; ++j) { - const int s = coupled_hist_start(cap, j, h); - check(s >= 0 && s + h <= cap + n_drafts, "the window lies inside the ring", s, cap + n_drafts); - for (int i = 0; i < h; ++i) - check(ring[(size_t) (s + i)] == rows[(size_t) j * (size_t) h + (size_t) i], "draft history = verify row history", - ring[(size_t) (s + i)], rows[(size_t) j * (size_t) h + (size_t) i]); - ring[(size_t) (cap + j)] = drafts[(size_t) j]; // coupled_merge_kernel appends the draft after sampling it - } -} -} // namespace - -int main() { - std::printf("coupled_draft_test\n"); - std::mt19937 rng(20260930); - // ---- 1 + 2: a serve-style decode (the first window is the last prompt token alone, then MTP windows) - for (int run = 0; run < 200; ++run) { - std::uniform_int_distribution tdist(1, 8); - int64_t p = 100 + run * 37; // n - 1 - int T = 1; - for (int round = 0; round < 300; ++round) { - std::uniform_int_distribution adist(0, T - 1); - const int a = adist(rng); - const int64_t p_next = p + a + 1; - const int n = 7; // the chain makes up to max_t - 1 drafts, whatever T the next window takes - check_chain(p, a, n, p_next); - p = p_next; - T = tdist(rng); // --spec-min-p / the draft policy choose the next window's size - } - } - // the CLI's draft_first: the first window at p, drafts from cell p - 1 with a = 0 - for (int64_t p = 1; p < 5000; p += 13) check_chain(p - 1, 0, 7, p); - // ---- 3: the penalty ring against penalty_rows - for (int cap : {8, 64, kCoupledHistCap}) { - for (int h : {1, 3, 8}) { - if (h > cap) continue; - for (int n_consumed : {0, 1, 2, 5, 7, 20, 100}) - for (int n_drafts : {1, 3, 7}) check_history(rng, cap, h, n_consumed, n_drafts); - } - check_history(rng, cap, cap, 3, 7); // the window is the whole ring base - check_history(rng, cap, cap, 5000, 7); - } - // ---- 4: the window length the target uses: min(penalty_last_n, history_len) with history_len = - // min(penalty_last_n, 4096) in serve (0 = off) - for (int pln : {-1, 0, 1, 64, 4095, 4096, 4097, 100000}) { - const int hist_n = std::min(std::max(pln, 0), 4096); - const int target = hist_n > 0 ? std::min(pln, hist_n) : 0; - check(coupled_hist_len(pln, kCoupledHistCap) == target, "penalty window length = the target's", - coupled_hist_len(pln, kCoupledHistCap), target); - } - std::printf(" %lld checks, %d failed\n", (long long) g_checks, g_fail); - std::printf("%s\n", g_fail == 0 ? "PASS" : "FAIL"); - return g_fail == 0 ? 0 : 1; -} diff --git a/src/core/device.cu b/src/core/device.cu deleted file mode 100644 index fbc7030..0000000 --- a/src/core/device.cu +++ /dev/null @@ -1,344 +0,0 @@ -// src/core/device.cu - P2.S1: the CUDA side of the runtime core. -#include "strata/core/device.hpp" - -#include - -#include -#include - -namespace strata::core { - -namespace { - -void check(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - throw CudaError(std::string(what) + ": " + cudaGetErrorString(e), (int) e); - } -} - -// A NaN pattern, not zero. Zeros read from uninitialised memory are indistinguishable from real zeros in a -// dequantized weight or a masked attention score, which is exactly the kind of wrong-but-plausible value the -// Phase 1 harnesses kept catching. -__global__ void poison_kernel(float* p, uint64_t n_floats) { - const uint64_t i = (uint64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i < n_floats) p[i] = __int_as_float(0x7fc00000); -} - -#if defined(STRATA_USE_HIP) -#if !defined(STRATA_HIP_ARCHS) -#error "STRATA_HIP_ARCHS (the compiled HIP architectures) is set by cmake/hip_backend.cmake" -#endif -// "gfx1201:sramecc-:xnack-" -> "gfx1201" -std::string base_arch(const char* gcn_arch_name) { - std::string arch(gcn_arch_name); - const size_t colon = arch.find(':'); - if (colon != std::string::npos) arch.resize(colon); - return arch; -} - -bool compiled_for(const std::string& arch) { - const std::string list = STRATA_HIP_ARCHS; - size_t a = 0; - while (a <= list.size()) { - size_t b = list.find(',', a); - if (b == std::string::npos) b = list.size(); - if (!arch.empty() && list.compare(a, b - a, arch) == 0 && b - a == arch.size()) return true; - a = b + 1; - } - return false; -} - -std::string arch_problem(const cudaDeviceProp& p, int ordinal) { - const std::string arch = base_arch(p.gcnArchName); - const std::string card = "GPU " + std::to_string(ordinal) + " (" + p.name + ", " + arch + ")"; - if (!compiled_for(arch)) { - return card + " is not an architecture this Strata engine was compiled for (" + STRATA_HIP_ARCHS + - "); compile it for this card (./setup.sh --backend hip, or -DCMAKE_HIP_ARCHITECTURES=" + arch + - ", docs/AMD_HIP.md) or choose another GPU with HIP_VISIBLE_DEVICES"; - } - if (p.warpSize != 32) { - return card + " runs wave" + std::to_string(p.warpSize) + "; Strata's HIP kernels need wave32"; - } - return ""; -} -#endif - -} // namespace - -const char* compiled_gpu_archs() { -#if defined(STRATA_USE_HIP) - return STRATA_HIP_ARCHS; -#else - return ""; -#endif -} - -int device_count() { - int count = 0; - if (cudaGetDeviceCount(&count) != cudaSuccess) { // HIP without a usable device reports an error, not 0 - cudaGetLastError(); - return 0; - } - return count < 0 ? 0 : count; -} - -bool device_summary(int ordinal, std::string& name, std::string& detail) { - cudaDeviceProp p{}; - if (ordinal < 0 || ordinal >= device_count() || cudaGetDeviceProperties(&p, ordinal) != cudaSuccess) { - cudaGetLastError(); - return false; - } - char buf[160]; -#if defined(STRATA_USE_HIP) - std::snprintf(buf, sizeof(buf), "arch %s, %.1f GiB, wave%d", base_arch(p.gcnArchName).c_str(), - (double) p.totalGlobalMem / (1024.0 * 1024 * 1024), p.warpSize); -#else - std::snprintf(buf, sizeof(buf), "compute capability %d.%d, %.1f GiB", p.major, p.minor, - (double) p.totalGlobalMem / (1024.0 * 1024 * 1024)); -#endif - name = p.name; - detail = buf; - return true; -} - -} // namespace strata::core - -#if defined(STRATA_USE_HIP) && defined(_WIN32) -// The free VRAM figure on Windows HIP (include/strata/hip_compat/cuda_runtime.h maps cudaMemGetInfo here). -// -// hipMemGetInfo (ROCclr's PAL backend, Device::globalFreeMemory) is the card's size minus this process's own -// allocations: it asks Windows for this process's usage only, never for what the desktop and other programs hold. -// So on a card that also drives the desktop the engine counted ~930 MiB that was not there, the expert cache filled -// the card, and WDDM moved memory out to system RAM: decode at 30 tok/s instead of 41 (RX 6800, HIP SDK 7.2). -// Windows itself gives each process a video memory budget (DXGI QueryVideoMemoryInfo) that does account for the -// others. Measured on that card: the budget sits 0.8 GiB below the card's size while this process is small and -// 1.8 GiB below once it holds 11 GiB; allocations past it still succeed, and are what Windows moves out. The -// free figure here is hipMemGetInfo's lowered by what the budget withholds (the card's size minus the budget). -// Subtracting from HIP's own figure, rather than taking the budget minus DXGI's usage, keeps memory the HIP runtime -// has freed and holds in its cache counted as free, as hipMemGetInfo counts it. dxgi.dll is loaded at run time, so -// nothing new is linked; when it or the card's adapter cannot be found, hipMemGetInfo's figure stands. -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include -#include -#include -#include -#include - -namespace strata::hip_compat { -namespace { -IDXGIAdapter3* budget_adapter(int device) { - constexpr int kMaxDevices = 16; - static std::mutex mu; - static IDXGIAdapter3* adapters[kMaxDevices] = {}; - static bool tried[kMaxDevices] = {}; - if (device < 0 || device >= kMaxDevices) return nullptr; - std::lock_guard lock(mu); - if (tried[device]) return adapters[device]; - tried[device] = true; - hipDeviceProp_t p{}; - if (hipGetDeviceProperties(&p, device) != hipSuccess) { - (void) hipGetLastError(); - return nullptr; - } - LUID luid{}; - std::memcpy(&luid, p.luid, sizeof luid); - using CreateFactory = HRESULT(WINAPI*)(REFIID, void**); - static HMODULE dxgi = LoadLibraryW(L"dxgi.dll"); // kept for the process' lifetime, like the adapters - const auto create = dxgi ? (CreateFactory) (void*) GetProcAddress(dxgi, "CreateDXGIFactory1") : nullptr; - IDXGIFactory4* factory = nullptr; - if (create == nullptr || FAILED(create(__uuidof(IDXGIFactory4), (void**) &factory))) return nullptr; - IDXGIAdapter3* adapter = nullptr; - if (FAILED(factory->EnumAdapterByLuid(luid, __uuidof(IDXGIAdapter3), (void**) &adapter))) adapter = nullptr; - factory->Release(); - adapters[device] = adapter; - return adapter; -} -} // namespace - -hipError_t mem_get_info(size_t* free_bytes, size_t* total_bytes) { - const hipError_t e = hipMemGetInfo(free_bytes, total_bytes); - static const bool off = [] { - const char* v = std::getenv("STRATA_WDDM_BUDGET"); - return v != nullptr && std::atoi(v) == 0; - }(); - if (e != hipSuccess || off || free_bytes == nullptr || total_bytes == nullptr) return e; - int device = 0; - if (hipGetDevice(&device) != hipSuccess) { - (void) hipGetLastError(); - return e; - } - IDXGIAdapter3* adapter = budget_adapter(device); - DXGI_QUERY_VIDEO_MEMORY_INFO local{}; - if (adapter == nullptr || FAILED(adapter->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &local)) || - local.Budget == 0 || local.Budget >= *total_bytes) - return e; - const size_t withheld = *total_bytes - (size_t) local.Budget; // the desktop's and other programs' share - static std::atomic said{false}; - if (!said.exchange(true)) { - std::fprintf(stderr, "strata: Windows budgets %llu of this card's %llu MiB for this process; free VRAM is " - "counted within that (STRATA_WDDM_BUDGET=0: off)\n", - (unsigned long long) (local.Budget >> 20), (unsigned long long) (*total_bytes >> 20)); - } - *free_bytes = *free_bytes > withheld ? *free_bytes - withheld : 0; - return e; -} -} // namespace strata::hip_compat -#endif - -namespace strata::core { - -std::string gpu_arch_problem(int ordinal) { -#if defined(STRATA_USE_HIP) - int count = 0; - if (cudaGetDeviceCount(&count) != cudaSuccess || ordinal < 0 || ordinal >= count) { - cudaGetLastError(); - return ""; - } - cudaDeviceProp p{}; - if (cudaGetDeviceProperties(&p, ordinal) != cudaSuccess) { - cudaGetLastError(); - return ""; - } - return arch_problem(p, ordinal); -#else - (void) ordinal; - return ""; -#endif -} - -std::string device_code_error() { -#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) - return ""; // gpu_arch_problem() checks the HIP architectures against STRATA_HIP_ARCHS, before this point -#else - // every .cu of the engine is compiled for the same CMAKE_CUDA_ARCHITECTURES, so this kernel stands for all - cudaFuncAttributes a{}; - const cudaError_t e = cudaFuncGetAttributes(&a, poison_kernel); - if (e == cudaSuccess) return {}; - cudaGetLastError(); - return cudaGetErrorString(e); -#endif -} - -DeviceInfo device_info(int ordinal) { - int count = 0; - check(cudaGetDeviceCount(&count), "cudaGetDeviceCount"); - if (count == 0) { -#if defined(STRATA_USE_HIP) - throw CudaError(std::string("no HIP device is present; this engine was compiled for ") + STRATA_HIP_ARCHS, -1); -#else - throw CudaError("no CUDA device is present; Strata needs an NVIDIA GPU (RTX 20 series or newer)", -1); -#endif - } - if (ordinal < 0 || ordinal >= count) { - throw CudaError("device ordinal " + std::to_string(ordinal) + " is out of range (have " + - std::to_string(count) + ")", - -1); - } - DeviceInfo d; - d.ordinal = ordinal; - check(cudaSetDevice(ordinal), "cudaSetDevice"); - - cudaDeviceProp p{}; - check(cudaGetDeviceProperties(&p, ordinal), "cudaGetDeviceProperties"); - d.name = p.name; - d.cc_major = p.major; - d.cc_minor = p.minor; - d.multi_processor_count = p.multiProcessorCount; - - size_t free_b = 0, total_b = 0; - check(cudaMemGetInfo(&free_b, &total_b), "cudaMemGetInfo"); - d.free_bytes = free_b; - d.total_bytes = total_b; - - check(cudaDriverGetVersion(&d.driver_version), "cudaDriverGetVersion"); - check(cudaRuntimeGetVersion(&d.runtime_version), "cudaRuntimeGetVersion"); - - // The engine supports compute capability 7.5 and newer (Turing: the QSA scorer's tf32 mma has a portable - // fp32-FMA fallback below sm_80, the tensor-core prompt kernels refuse and fall back). Compiling for a - // supported arch is enforced by CMake; RUNNING on an older card is caught here, because a binary can be carried - // to a machine with an older card and would otherwise silently take whatever path the driver chose. The HIP - // backend checks the card against the architectures the binary was compiled for (and wave32). -#if defined(STRATA_HIP_GFX906) - // AMD gfx906 (the STRATA_HIP_GFX906 compat build, not STRATA_USE_HIP): the build targets one gfx arch - // (CMAKE_HIP_ARCHITECTURES, wave64); a card of another arch fails at the first kernel launch with - // hipErrorInvalidDeviceFunction. gcnArchName says which it is. - { - std::string arch(p.gcnArchName); - if (const size_t colon = arch.find(':'); colon != std::string::npos) arch.resize(colon); - d.arch = arch; - } - if (p.gcnArchName[0] != 0) d.name += std::string(" (") + p.gcnArchName + ")"; -#elif defined(STRATA_USE_HIP) - d.arch = base_arch(p.gcnArchName); - if (const std::string why = arch_problem(p, ordinal); !why.empty()) throw CudaError(why, -1); -#else - // #236: the experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON: Pascal sm_60, Volta sm_70) runs on the cards it - // was built for - refusing them below 7.5 there made the flag useless; the release engine keeps 7.5 -#if defined(STRATA_EXPERIMENTAL_SM60) - constexpr int kMinCc = 60; - const char* const kNeed = "6.0 or newer (this is the experimental Pascal / Volta build)"; -#else - constexpr int kMinCc = 75; - const char* const kNeed = "7.5 or newer (RTX 20 / 30 / 40 / 50 series)"; -#endif - if (d.cc_major * 10 + d.cc_minor < kMinCc) { - throw CudaError("device " + d.name + " reports compute capability " + std::to_string(d.cc_major) + - "." + std::to_string(d.cc_minor) + "; Strata needs compute capability " + kNeed, - -1); - } -#endif - return d; -} - -DeviceArena::DeviceArena(uint64_t bytes, int ordinal, bool poison) - : capacity_(bytes), ordinal_(ordinal), poison_(poison) { - if (bytes == 0) throw CudaError("DeviceArena of 0 bytes", -1); - check(cudaSetDevice(ordinal), "cudaSetDevice"); - // One allocation for the whole region. cudaMalloc of a large block is the thing that can fail late, so it - // happens once, here, before anything depends on it. - check(cudaMalloc(&base_, (size_t) bytes), "cudaMalloc"); - if (poison_) { - const int threads = 256; - const uint64_t n = bytes / sizeof(float); - const uint64_t blocks = (n + threads - 1) / threads; - // gridDim.x is 32-bit, so a large region needs a loop. 12 GB of floats is 3e9 elements = 1.2e7 - // blocks, which fits, but the loop keeps it correct for any size rather than for today's sizes. - const uint64_t max_blocks = 0x7FFFFFFFull; - for (uint64_t b = 0; b < blocks; b += max_blocks) { - const uint64_t chunk = (blocks - b < max_blocks) ? (blocks - b) : max_blocks; - poison_kernel<<<(unsigned) chunk, threads>>>((float*) base_ + b * threads, n - b * threads); - check(cudaGetLastError(), "poison_kernel"); - } - check(cudaDeviceSynchronize(), "poison sync"); - } -} - -DeviceArena::~DeviceArena() { - if (base_) cudaFree(base_); // best effort: a destructor must not throw -} - -void* DeviceArena::alloc(uint64_t bytes, uint64_t align) { - if (bytes == 0) return nullptr; - if (align == 0 || (align & (align - 1)) != 0) { - throw CudaError("DeviceArena::alloc alignment must be a power of two", -1); - } - const uint64_t start = (used_ + align - 1) & ~(align - 1); - if (start + bytes > capacity_) { - char msg[256]; - std::snprintf(msg, sizeof(msg), - "DeviceArena out of memory: asked for %llu B at offset %llu (align %llu) in a %llu B " - "region - the plan from P1.S9 did not close", - (unsigned long long) bytes, (unsigned long long) start, (unsigned long long) align, - (unsigned long long) capacity_); - throw CudaError(msg, -1); - } - used_ = start + bytes; - return (char*) base_ + start; -} - -} // namespace strata::core diff --git a/src/core/device_main.cpp b/src/core/device_main.cpp deleted file mode 100644 index c6872af..0000000 --- a/src/core/device_main.cpp +++ /dev/null @@ -1,122 +0,0 @@ -// src/core/device_main.cpp - `strata-device`: report the GPU, the plan, and exercise the arena. -// -// This is P2.S1's "startup prints the memory plan vs actual cudaMemGetInfo" bullet, on its own so it can run -// without the model. It is also the run-time half of the sm_120 policy: CMake refuses to COMPILE for another -// architecture, and this refuses to RUN on one. -#include "strata/core/device.hpp" -#include "strata/plan/plan.hpp" - -#include -#include -#include -#if defined(STRATA_USE_HIP) && defined(_WIN32) -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include -#endif - -static std::string human(uint64_t b) { - char buf[64]; - std::snprintf(buf, sizeof(buf), "%.3f GiB (%llu B)", (double) b / (1024.0 * 1024 * 1024), - (unsigned long long) b); - return buf; -} - -int main(int argc, char** argv) { - bool selftest = false; - bool list_devices = false; - for (int i = 1; i < argc; ++i) { - if (std::strcmp(argv[i], "--selftest") == 0) selftest = true; - else if (std::strcmp(argv[i], "--list-devices") == 0) list_devices = true; - else if (std::strcmp(argv[i], "--help") == 0 || std::strcmp(argv[i], "-h") == 0) { - std::printf("usage: strata-device [--selftest] [--list-devices]\n" - " --list-devices every GPU the runtime enumerates, numbered as HIP_VISIBLE_DEVICES /\n" - " CUDA_VISIBLE_DEVICES number them, and whether this binary can run it\n"); - return 0; - } else { - std::fprintf(stderr, "unknown argument: %s\n", argv[i]); - return 2; - } - } - - // The runtime's numbering, which setup needs on Windows: there an integrated Radeon is HIP device 0 and pushes the - // discrete card to 1, while setup finds the cards in the display-adapter order (#325). No arch check here - the - // cards this binary has no code for are part of the answer. Format (setup.py's hip_devices parses it): - // device N: - // arch gfx1201, 15.9 GiB, wave32 (CUDA: compute capability 12.0, 11.9 GiB) - // cannot run: (only for a card this binary cannot run) - if (list_devices) { - const int count = strata::core::device_count(); - if (count == 0) std::printf("(no GPU device)\n"); - for (int ordinal = 0; ordinal < count; ++ordinal) { - std::string name, detail; - if (!strata::core::device_summary(ordinal, name, detail)) { - std::printf("device %d: (the runtime cannot describe it)\n", ordinal); - continue; - } - std::printf("device %d: %s\n %s\n", ordinal, name.c_str(), detail.c_str()); - if (const std::string why = strata::core::gpu_arch_problem(ordinal); !why.empty()) - std::printf(" cannot run: %s\n", why.c_str()); - } - return 0; - } - - try { - const strata::core::DeviceInfo d = strata::core::device_info(0); - std::printf("device %d: %s\n", d.ordinal, d.name.c_str()); -#if defined(STRATA_USE_HIP) - std::printf(" HIP arch %s wave32 (compiled for %s)\n", d.arch.c_str(), - strata::core::compiled_gpu_archs()); -#else - std::printf(" compute capability %d.%d (sm_%d%d)\n", d.cc_major, d.cc_minor, d.cc_major, d.cc_minor); -#endif - std::printf(" multiprocessors %d\n", d.multi_processor_count); - std::printf(" VRAM total / free %s / %s\n", human(d.total_bytes).c_str(), human(d.free_bytes).c_str()); - std::printf(" driver / runtime %d / %d\n", d.driver_version, d.runtime_version); -#if defined(STRATA_USE_HIP) && defined(_WIN32) - // #468 #461: which HIP runtime this process loaded - the one beside the exe, or an AMD driver's System32 copy - if (HMODULE h = GetModuleHandleA("amdhip64_7.dll")) { - char path[MAX_PATH] = {}; - if (GetModuleFileNameA(h, path, MAX_PATH) > 0) std::printf(" HIP runtime %s\n", path); - } -#endif - - // The planner's view against the card's. A plan that does not fit in what is actually FREE is the - // failure this print exists to make visible at startup rather than at token 4000. - const auto plan = strata::plan::make_plan(20480, strata::plan::Geometry{}, strata::plan::Costs{}); - std::printf("\n%s", strata::plan::to_string(plan).c_str()); - std::printf(" card free %s\n", human(d.free_bytes).c_str()); - std::printf(" plan + KV vs free %s\n", - plan.vram_budget <= d.free_bytes ? "FITS" : "*** DOES NOT FIT ***"); - - if (selftest) { - // Exercise the arena for real: allocate, write from the host, read back, and check the poison - // path leaves NaNs rather than zeros. A GPU test that only asks the driver for its name does not - // test the runtime this file exists to provide. - const uint64_t bytes = 64ull << 20; // 64 MiB, small enough to be safe on any card - strata::core::DeviceArena arena(bytes, 0, /*poison=*/true); - void* a = arena.alloc(1 << 20, 256); - void* b = arena.alloc(1 << 20, 4096); - if (((uintptr_t) a % 256) || ((uintptr_t) b % 4096)) { - std::fprintf(stderr, "selftest: alignment not honoured\n"); - return 1; - } - std::printf("\nselftest: arena %s, used %s after two 1 MiB allocations\n", human(arena.capacity()).c_str(), - human(arena.used()).c_str()); - // and the arena must REFUSE rather than wrap - try { - arena.alloc(bytes * 2); - std::fprintf(stderr, "selftest: over-allocation did NOT throw\n"); - return 1; - } catch (const strata::core::CudaError&) { - std::printf("selftest: over-allocation refused as required\n"); - } - std::printf("strata-device selftest OK\n"); - } - return 0; - } catch (const std::exception& e) { - std::fprintf(stderr, "strata-device: %s\n", e.what()); - return 1; - } -} diff --git a/src/core/expert_cache.cpp b/src/core/expert_cache.cpp deleted file mode 100644 index b8df2fa..0000000 --- a/src/core/expert_cache.cpp +++ /dev/null @@ -1,696 +0,0 @@ -// src/core/expert_cache.cpp - R4's slot storage and residency table. Read the header first. -#include "strata/core/expert_cache.hpp" - -// #533's segmented cache uses CUDA's virtual memory management (cuMem*): not on HIP, neither the RDNA backend nor -// the gfx906 compat build (PR #638), which compiles this file as HIP without STRATA_USE_HIP -#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) -#define STRATA_EC_NO_VMM 1 -#endif - -#include -#if !defined(STRATA_EC_NO_VMM) -#include // #533: the virtual memory management types (the functions come through the runtime's entry points) -#endif - -#include -#include -#include -#include -#include - -namespace strata::core { - -bool read_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert, - std::vector>& ranked, int64_t& slots, std::string& err) { - std::FILE* f = std::fopen(path.c_str(), "rb"); - if (f == nullptr) { - err = "read_expert_profile: cannot open " + path; - return false; - } - char magic[4] = {0, 0, 0, 0}; - uint32_t hdr[5] = {0, 0, 0, 0, 0}; - if (std::fread(magic, 1, 4, f) != 4 || std::fread(hdr, 4, 5, f) != 5) { - std::fclose(f); - err = "read_expert_profile: " + path + " is too short to hold a header"; - return false; - } - if (std::memcmp(magic, "STRP", 4) != 0) { - std::fclose(f); - err = "read_expert_profile: " + path + " does not start with STRP"; - return false; - } - const uint32_t version = hdr[0], nl = hdr[1], ne = hdr[2], want = hdr[3], n_ranked = hdr[4]; - if ((int64_t) nl != n_layers || (int64_t) ne != n_expert) { - std::fclose(f); - char buf[256]; - std::snprintf(buf, sizeof buf, - "read_expert_profile: %s is %ux%u but this model is %lldx%lld - it is a profile for a " - "different artifact", path.c_str(), nl, ne, (long long) n_layers, (long long) n_expert); - err = buf; - return false; - } - if (n_ranked > want) { - std::fclose(f); - err = "read_expert_profile: the header claims more ranked pairs than slots"; - return false; - } - ranked.assign(n_ranked, {0, 0}); - std::vector raw((size_t) n_ranked * 2); - if (n_ranked > 0 && std::fread(raw.data(), 2, (size_t) n_ranked * 2, f) != (size_t) n_ranked * 2) { - std::fclose(f); - err = "read_expert_profile: the ranked list is truncated"; - return false; - } - std::fclose(f); - for (uint32_t i = 0; i < n_ranked; ++i) { - const int32_t l = (int32_t) raw[(size_t) i * 2], e = (int32_t) raw[(size_t) i * 2 + 1]; - if (l < 0 || l >= n_layers || e < 0 || e >= n_expert) { - char buf[256]; - std::snprintf(buf, sizeof buf, "read_expert_profile: pair %u is (layer %d, expert %d), out of range", - i, l, e); - err = buf; - return false; - } - ranked[(size_t) i] = {l, e}; - } - slots = (int64_t) want; - (void) version; // a future format bumps it; the layout check above is what protects this reader today - return true; -} - -std::vector> rank_learned_profile(int64_t n_layers, int64_t n_expert, - const std::vector& resident, - const std::vector& heat, - const std::vector>& prior) { - const size_t n = (size_t) (n_layers * n_expert); - std::vector prior_rank(n, INT64_MAX); - for (size_t r = 0; r < prior.size(); ++r) { - const auto [l, e] = prior[r]; - if (l >= 0 && l < n_layers && e >= 0 && e < n_expert) { - int64_t& pr = prior_rank[(size_t) (l * n_expert + e)]; - if (pr == INT64_MAX) pr = (int64_t) r; - } - } - std::vector order(n); - for (size_t i = 0; i < n; ++i) order[i] = (int64_t) i; - auto res = [&](int64_t i) { return (size_t) i < resident.size() && resident[(size_t) i] != 0; }; - auto ht = [&](int64_t i) { return (size_t) i < heat.size() ? heat[(size_t) i] : 0.0; }; - std::stable_sort(order.begin(), order.end(), [&](int64_t a, int64_t b) { - if (res(a) != res(b)) return res(a); - if (ht(a) != ht(b)) return ht(a) > ht(b); - if (prior_rank[(size_t) a] != prior_rank[(size_t) b]) return prior_rank[(size_t) a] < prior_rank[(size_t) b]; - return a < b; - }); - std::vector> ranked(n); - for (size_t r = 0; r < n; ++r) - ranked[r] = {(int32_t) (order[r] / n_expert), (int32_t) (order[r] % n_expert)}; - return ranked; -} - -bool write_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert, - const std::vector>& ranked, std::string& err) { - if (n_layers <= 0 || n_expert <= 0 || n_layers > 65535 || n_expert > 65535) { - err = "write_expert_profile: the model's layout does not fit the format"; - return false; - } - std::vector table((size_t) (n_layers * n_expert), -1); - std::vector pairs; - pairs.reserve(ranked.size() * 2); - for (size_t r = 0; r < ranked.size(); ++r) { - const auto [l, e] = ranked[r]; - if (l < 0 || l >= n_layers || e < 0 || e >= n_expert) { - err = "write_expert_profile: a ranked pair is out of range"; - return false; - } - table[(size_t) (l * n_expert + e)] = (int32_t) r; - pairs.push_back((uint16_t) l); - pairs.push_back((uint16_t) e); - } - const uint32_t hdr[5] = {1u, (uint32_t) n_layers, (uint32_t) n_expert, (uint32_t) ranked.size(), - (uint32_t) ranked.size()}; - const std::string tmp = path + ".tmp"; - std::FILE* f = std::fopen(tmp.c_str(), "wb"); - if (f == nullptr) { - err = "write_expert_profile: cannot create " + tmp; - return false; - } - // the format is little-endian (make_profile.py's "<"): so is every machine this engine runs on - bool ok = std::fwrite("STRP", 1, 4, f) == 4 && std::fwrite(hdr, 4, 5, f) == 5 && - (pairs.empty() || std::fwrite(pairs.data(), 2, pairs.size(), f) == pairs.size()) && - std::fwrite(table.data(), 4, table.size(), f) == table.size(); - ok = (std::fclose(f) == 0) && ok; - std::error_code ec; - if (ok) std::filesystem::rename(tmp, path, ec); // replaces an existing file (MoveFileEx / rename(2)) - if (!ok || ec) { - std::filesystem::remove(tmp, ec); - err = "write_expert_profile: cannot write " + path; - return false; - } - return true; -} - -ExpertCache::~ExpertCache() { close(); } - -// ---- #533: the segmented arena (--vram-elastic). The driver API's virtual memory functions, looked up through the -// runtime (no link against the driver library): one address range for the whole arena, backed by physical segments, -// and the tail's segments unmapped / mapped again later. Nothing here runs unless a segment size was set. -#if !defined(STRATA_EC_NO_VMM) -namespace { -struct Vmm { - CUresult (CUDAAPI* device_get)(CUdevice*, int) = nullptr; - CUresult (CUDAAPI* attribute)(int*, CUdevice_attribute, CUdevice) = nullptr; - CUresult (CUDAAPI* granularity)(size_t*, const CUmemAllocationProp*, CUmemAllocationGranularity_flags) = nullptr; - CUresult (CUDAAPI* reserve)(CUdeviceptr*, size_t, size_t, CUdeviceptr, unsigned long long) = nullptr; - CUresult (CUDAAPI* address_free)(CUdeviceptr, size_t) = nullptr; - CUresult (CUDAAPI* create)(CUmemGenericAllocationHandle*, size_t, const CUmemAllocationProp*, - unsigned long long) = nullptr; - CUresult (CUDAAPI* release)(CUmemGenericAllocationHandle) = nullptr; - CUresult (CUDAAPI* map)(CUdeviceptr, size_t, size_t, CUmemGenericAllocationHandle, unsigned long long) = nullptr; - CUresult (CUDAAPI* unmap)(CUdeviceptr, size_t) = nullptr; - CUresult (CUDAAPI* set_access)(CUdeviceptr, size_t, const CUmemAccessDesc*, size_t) = nullptr; - bool ok = false; -}; - -template bool entry(const char* name, F& f) { - void* p = nullptr; - cudaDriverEntryPointQueryResult q{}; -#if CUDART_VERSION >= 12050 - const cudaError_t e = cudaGetDriverEntryPointByVersion(name, &p, 12000, cudaEnableDefault, &q); -#else - const cudaError_t e = cudaGetDriverEntryPoint(name, &p, cudaEnableDefault, &q); -#endif - if (e != cudaSuccess || q != cudaDriverEntryPointSuccess || p == nullptr) { - (void) cudaGetLastError(); - return false; - } - f = reinterpret_cast(p); - return true; -} - -const Vmm& vmm() { - static const Vmm v = [] { - Vmm x; - x.ok = entry("cuDeviceGet", x.device_get) && entry("cuDeviceGetAttribute", x.attribute) && - entry("cuMemGetAllocationGranularity", x.granularity) && entry("cuMemAddressReserve", x.reserve) && - entry("cuMemAddressFree", x.address_free) && entry("cuMemCreate", x.create) && - entry("cuMemRelease", x.release) && entry("cuMemMap", x.map) && entry("cuMemUnmap", x.unmap) && - entry("cuMemSetAccess", x.set_access); - return x; - }(); - return v; -} - -CUmemAllocationProp device_prop(int dev) { - CUmemAllocationProp prop{}; - prop.type = CU_MEM_ALLOCATION_TYPE_PINNED; - prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE; - prop.location.id = dev; - return prop; -} - -// one segment: a physical allocation mapped at `va`, readable and writable by this device -bool map_segment(const Vmm& v, int dev, CUdeviceptr va, size_t bytes, unsigned long long& handle) { - const CUmemAllocationProp prop = device_prop(dev); - CUmemGenericAllocationHandle h = 0; - if (v.create(&h, bytes, &prop, 0) != CUDA_SUCCESS) return false; - if (v.map(va, bytes, 0, h, 0) != CUDA_SUCCESS) { - v.release(h); - return false; - } - CUmemAccessDesc access{}; - access.location.type = CU_MEM_LOCATION_TYPE_DEVICE; - access.location.id = dev; - access.flags = CU_MEM_ACCESS_FLAGS_PROT_READWRITE; - if (v.set_access(va, bytes, &access, 1) != CUDA_SUCCESS) { - v.unmap(va, bytes); - v.release(h); - return false; - } - handle = (unsigned long long) h; - return true; -} -} // namespace -#endif - -bool ExpertCache::open_segmented(uint64_t want, std::string& err) { -#if defined(STRATA_EC_NO_VMM) - (void) want; - err = "ExpertCache: --vram-elastic (a segmented expert cache) is CUDA-only for now"; - return false; -#else - const Vmm& v = vmm(); - int dev = 0, supported = 0; - CUdevice cu = 0; - if (!v.ok || cudaGetDevice(&dev) != cudaSuccess || v.device_get(&cu, dev) != CUDA_SUCCESS || - v.attribute(&supported, CU_DEVICE_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED, cu) != CUDA_SUCCESS || - !supported) { - err = "ExpertCache: --vram-elastic needs the driver's virtual memory management, which this GPU or driver " - "does not offer"; - return false; - } - const CUmemAllocationProp prop = device_prop(dev); - size_t gran = 0; - if (v.granularity(&gran, &prop, CU_MEM_ALLOC_GRANULARITY_RECOMMENDED) != CUDA_SUCCESS || gran == 0) { - err = "ExpertCache: cannot read the driver's allocation granularity"; - return false; - } - const uint64_t g = (uint64_t) gran; - const uint64_t total = (want + g - 1) / g * g; - seg_ = (int64_t) (((uint64_t) seg_req_ + g - 1) / g * g); - CUdeviceptr va = 0; - if (v.reserve(&va, (size_t) total, 0, 0, 0) != CUDA_SUCCESS) { - err = "ExpertCache: cannot reserve the address range of the segmented expert cache"; - return false; - } - base_ = reinterpret_cast(va); - reserved_ = total; - for (uint64_t at = 0; at < total; at += (uint64_t) seg_) { - segs_.push_back(0); - seg_size_.push_back((int64_t) std::min((uint64_t) seg_, total - at)); - } - for (size_t i = 0; i < segs_.size(); ++i) { - if (!map_segment(v, dev, va + (CUdeviceptr) ((uint64_t) i * (uint64_t) seg_), (size_t) seg_size_[i], - segs_[i])) { - char buf[200]; - std::snprintf(buf, sizeof buf, "ExpertCache: cudaMalloc failed: segment %zu of %zu (%.2f GiB) of the " - "segmented cache could not be allocated", i + 1, segs_.size(), - (double) seg_size_[i] / 1073741824.0); - err = buf; // "cudaMalloc failed": the auto cache's smaller-retry path reads it as an allocation failure - release_segmented(); - return false; - } - mapped_segs_ = (int64_t) i + 1; - } - return true; -#endif -} - -void ExpertCache::release_segmented() { -#if !defined(STRATA_EC_NO_VMM) - const Vmm& v = vmm(); - if (base_ != nullptr) cudaDeviceSynchronize(); - const CUdeviceptr va = reinterpret_cast(base_); - for (size_t i = 0; i < segs_.size(); ++i) - if (segs_[i] != 0) { - v.unmap(va + (CUdeviceptr) ((uint64_t) i * (uint64_t) seg_), (size_t) seg_size_[i]); - v.release((CUmemGenericAllocationHandle) segs_[i]); - } - if (base_ != nullptr && reserved_ > 0) v.address_free(va, (size_t) reserved_); -#endif - segs_.clear(); - seg_size_.clear(); - mapped_segs_ = 0; - reserved_ = 0; - base_ = nullptr; -} - -int64_t ExpertCache::mapped_bytes() const { - if (segs_.empty()) return base_ != nullptr ? full_bytes() : 0; - int64_t b = 0; - for (int64_t i = 0; i < mapped_segs_; ++i) b += seg_size_[(size_t) i]; - return b; -} - -int64_t ExpertCache::slots_within(int64_t bytes) const { - if (bytes >= full_bytes()) return slots_; - if (bytes <= 0) return 0; - if (off_.empty()) return blob_ > 0 ? bytes / blob_ : 0; - // off_[i + 1] is slot i's end: count the slots whose end is at most `bytes` - return (int64_t) (std::upper_bound(off_.begin() + 1, off_.end(), (uint64_t) bytes) - (off_.begin() + 1)); -} - -bool ExpertCache::shrink(int64_t keep_bytes, std::string& err) { - if (segs_.empty()) { - err = "the expert cache is not segmented (the engine needs --vram-elastic)"; - return false; - } -#if defined(STRATA_EC_NO_VMM) - (void) keep_bytes; - return false; -#else - const Vmm& v = vmm(); - int64_t keep = 0, at = 0; // the segments [0, keep) hold the first keep_bytes - while (keep < (int64_t) segs_.size() && at < keep_bytes) at += seg_size_[(size_t) keep++]; - if (keep >= mapped_segs_) return true; - if (cudaDeviceSynchronize() != cudaSuccess) { - err = std::string("the device failed before the cache shrank: ") + cudaGetErrorString(cudaGetLastError()); - return false; - } - const CUdeviceptr va = reinterpret_cast(base_); - for (int64_t i = mapped_segs_ - 1; i >= keep; --i) { - const CUdeviceptr p = va + (CUdeviceptr) ((uint64_t) i * (uint64_t) seg_); - if (v.unmap(p, (size_t) seg_size_[(size_t) i]) != CUDA_SUCCESS || - v.release((CUmemGenericAllocationHandle) segs_[(size_t) i]) != CUDA_SUCCESS) { - err = "the driver refused to release an expert-cache segment"; - live_slots_ = slots_within(mapped_bytes()); - return false; - } - segs_[(size_t) i] = 0; - mapped_segs_ = i; - } - live_slots_ = slots_within(mapped_bytes()); - return true; -#endif -} - -bool ExpertCache::grow(int64_t want_bytes, std::string& err) { - if (segs_.empty()) { - err = "the expert cache is not segmented (the engine needs --vram-elastic)"; - return false; - } -#if defined(STRATA_EC_NO_VMM) - (void) want_bytes; - return false; -#else - const Vmm& v = vmm(); - int dev = 0; - cudaGetDevice(&dev); - const CUdeviceptr va = reinterpret_cast(base_); - int64_t at = mapped_bytes(); - while (mapped_segs_ < (int64_t) segs_.size() && at + seg_size_[(size_t) mapped_segs_] <= want_bytes) { - const size_t i = (size_t) mapped_segs_; - if (!map_segment(v, dev, va + (CUdeviceptr) ((uint64_t) i * (uint64_t) seg_), (size_t) seg_size_[i], - segs_[i])) { - (void) cudaGetLastError(); - err = "the driver has no VRAM for another expert-cache segment"; - live_slots_ = slots_within(mapped_bytes()); - return false; - } - at += seg_size_[i]; - ++mapped_segs_; - } - live_slots_ = slots_within(mapped_bytes()); - return true; -#endif -} - -#if defined(STRATA_USE_HIP) -bool ExpertCache::ensure_blocking_staging(std::size_t bytes, std::string& err) { - if (bytes <= blocking_staging_bytes_) return true; - void* next = nullptr; - const cudaError_t status = cudaHostAlloc(&next, bytes, cudaHostAllocDefault); - if (status != cudaSuccess) { - err = std::string("ExpertCache: HIP blocking staging allocation: ") + cudaGetErrorString(status); - return false; - } - if (blocking_staging_) (void) cudaFreeHost(blocking_staging_); - blocking_staging_ = static_cast(next); - blocking_staging_bytes_ = bytes; - return true; -} -#endif - -bool ExpertCache::open(int64_t n_slots, int64_t n_layers, int64_t n_expert, int64_t blob_bytes, - std::string& err) { - close(); - if (n_slots <= 0) { - err = "ExpertCache: n_slots must be positive"; - return false; - } - if (n_layers <= 0 || n_expert <= 0 || blob_bytes <= 0) { - err = "ExpertCache: n_layers, n_expert and blob_bytes must all be positive"; - return false; - } - - const uint64_t want = (uint64_t) n_slots * (uint64_t) blob_bytes; - - // ---- **THE ALLOCATION IS CHECKED AGAINST THE CARD, NOT AGAINST THE REQUEST.** - // - // `cudaMalloc` failing is the easy case. The one that matters is a machine where the weights already own - // most of VRAM: the cache then takes what is left and `slots()` would report the number ASKED FOR while - // `device_slot()` walks off the end. So the free-VRAM figure is read and compared BEFORE the allocation, - // and the two numbers are named in the refusal. - size_t free_b = 0, total_b = 0; - if (cudaMemGetInfo(&free_b, &total_b) == cudaSuccess) { - if ((uint64_t) free_b < want) { - char buf[320]; - std::snprintf(buf, sizeof buf, - "ExpertCache: %lld slots x %lld B = %.2f GiB, but only %.2f GiB of VRAM is free " - "(%.2f GiB of %.2f GiB total). Lower --expert-cache.", - (long long) n_slots, (long long) blob_bytes, (double) want / 1073741824.0, - (double) free_b / 1073741824.0, (double) (total_b - free_b) / 1073741824.0, - (double) total_b / 1073741824.0); - err = buf; - return false; - } - } - - if (seg_req_ > 0) { // #533: --vram-elastic: physical segments behind one address range (zeroed below) - if (!open_segmented(want, err)) return false; - } else if (cudaMalloc((void**) &base_, (size_t) want) != cudaSuccess) { - base_ = nullptr; - char buf[256]; - std::snprintf(buf, sizeof buf, "ExpertCache: cudaMalloc(%.2f GiB) failed: %s", - (double) want / 1073741824.0, cudaGetErrorString(cudaGetLastError())); - err = buf; - return false; - } - // Zeroed so a slot read before it is filled is a DETERMINISTIC wrong answer rather than whatever the - // allocator handed back. A stale block of a previous process's memory would still sum to finite floats. - if (cudaMemset(base_, 0, (size_t) want) != cudaSuccess) { - err = "ExpertCache: cudaMemset of the slot arena failed"; - close(); - return false; - } - - residency_.assign((size_t) (n_layers * n_expert), kNotResident); - slots_ = n_slots; - live_slots_ = n_slots; - n_layers_ = n_layers; - n_expert_ = n_expert; - blob_ = blob_bytes; -#if defined(STRATA_USE_HIP) - if (!ensure_blocking_staging((std::size_t) blob_, err)) { - close(); - return false; - } -#endif - next_free_ = 0; - fills_ = 0; - admitted_ = 0; - // R4.2g: each layer starts at the bottom of its own range. Built here rather than lazily so `admit` - // stays allocation-free on the token path. - layer_next_.assign((size_t) (n_layers > 0 ? n_layers : 0), 0); - for (int64_t l = 0; l < n_layers; ++l) { - int64_t lo = 0, hi = 0; - layer_slot_range(l, lo, hi); - layer_next_[(size_t) l] = (int32_t) lo; - } - return true; -} - -bool ExpertCache::open_sized(const std::vector& slot_bytes, int64_t n_layers, int64_t n_expert, - std::string& err) { - if (slot_bytes.empty()) { err = "ExpertCache: no slots"; return false; } - int64_t mx = 0; - std::vector off(slot_bytes.size() + 1, 0); - for (size_t i = 0; i < slot_bytes.size(); ++i) { - // 256-byte aligned slots, so every blob starts where the kernels' vector loads expect it - off[i + 1] = off[i] + ((uint64_t) slot_bytes[i] + 255) / 256 * 256; - mx = slot_bytes[i] > mx ? slot_bytes[i] : mx; - } - // one allocation of the summed size, through the uniform path's checks: n "slots" of 1 byte - if (!open((int64_t) off.back(), n_layers, n_expert, 1, err)) return false; - slots_ = (int64_t) slot_bytes.size(); - live_slots_ = slots_; - blob_ = mx; - off_ = std::move(off); -#if defined(STRATA_USE_HIP) - if (!ensure_blocking_staging((std::size_t) blob_, err)) { - close(); - return false; - } -#endif - // #369: each layer's cursor at the bottom of its own range, as open() seeds it - open() above ran on byte-sized - // "slots", so its seeds are not slot indices - layer_next_.assign((size_t) (n_layers > 0 ? n_layers : 0), 0); - for (int64_t l = 0; l < n_layers; ++l) { - int64_t lo = 0, hi = 0; - layer_slot_range(l, lo, hi); - layer_next_[(size_t) l] = (int32_t) lo; - } - return true; -} - -void ExpertCache::close() { -#if defined(STRATA_USE_HIP) - if (blocking_staging_) (void) cudaFreeHost(blocking_staging_); - blocking_staging_ = nullptr; - blocking_staging_bytes_ = 0; -#endif - off_.clear(); - if (!segs_.empty()) { - release_segmented(); - } else if (base_ != nullptr) { - cudaFree(base_); - base_ = nullptr; - } - residency_.clear(); - slots_ = 0; - live_slots_ = 0; - n_layers_ = 0; - n_expert_ = 0; - blob_ = 0; - next_free_ = 0; - fills_ = 0; - admitted_ = 0; - layer_next_.clear(); -} - -/// R4.2g. Layer `l` owns `[l*q, (l+1)*q)` with `q = slots_ / n_layers_`; the LAST layer takes whatever is -/// left over, so the ranges always cover `0..slots_` exactly and no slot is orphaned by the division. -void ExpertCache::layer_slot_range(int64_t layer, int64_t& lo, int64_t& hi) const { - lo = 0; - hi = 0; - if (n_layers_ <= 0 || slots_ <= 0 || layer < 0 || layer >= n_layers_) return; - const int64_t q = slots_ / n_layers_; - lo = layer * q; - hi = (layer == n_layers_ - 1) ? slots_ : (layer + 1) * q; -} - -int32_t ExpertCache::slot_of(int64_t layer, int64_t expert) const { - if (layer < 0 || layer >= n_layers_ || expert < 0 || expert >= n_expert_) return kNotResident; - return residency_[(size_t) (layer * n_expert_ + expert)]; -} - -int32_t ExpertCache::admit(int64_t layer, int64_t expert) { - if (layer < 0 || layer >= n_layers_ || expert < 0 || expert >= n_expert_) return kNotResident; - const size_t at = (size_t) (layer * n_expert_ + expert); - if (residency_[at] != kNotResident) return residency_[at]; - // R4.2g: THE PER-LAYER PATH. Same "no eviction" rule, but the ceiling is this layer's own range rather - // than one counter shared by all 48 - which is what confined the measured hit rate to 2.97%. - if (per_layer_) { - if (layer_next_.empty()) return kNotResident; - int64_t lo = 0, hi = 0; - layer_slot_range(layer, lo, hi); - if ((int64_t) layer_next_[(size_t) layer] >= hi) return kNotResident; // this layer's quota is full - residency_[at] = layer_next_[(size_t) layer]++; - ++admitted_; - return residency_[at]; - } - if (next_free_ >= slots_) return kNotResident; // full: no eviction, deliberately - see the header - residency_[at] = (int32_t) next_free_; - return (int32_t) next_free_++; -} - -uint8_t* ExpertCache::device_slot(int32_t slot) { - if (slot < 0 || slot >= slots_) return nullptr; - if (!off_.empty()) return base_ + off_[(size_t) slot]; - return base_ + (size_t) slot * (size_t) blob_; -} - -const uint8_t* ExpertCache::device_slot(int32_t slot) const { - if (slot < 0 || slot >= slots_) return nullptr; - if (!off_.empty()) return base_ + off_[(size_t) slot]; - return base_ + (size_t) slot * (size_t) blob_; -} - -bool ExpertCache::fill_slot(int32_t slot, const uint8_t* host_blob, void* stream, std::string& err, int64_t bytes) { - const size_t n = (size_t) (bytes > 0 && bytes <= blob_ ? bytes : blob_); - uint8_t* dst = device_slot(slot); - if (dst == nullptr) { - err = "ExpertCache::fill_slot: slot " + std::to_string(slot) + " is outside 0.." + - std::to_string(slots_ - 1); - return false; - } - if (host_blob == nullptr) { - err = "ExpertCache::fill_slot: the host blob is null"; - return false; - } - const cudaError_t e = cudaMemcpyAsync(dst, host_blob, n, cudaMemcpyHostToDevice, - (cudaStream_t) stream); - if (e != cudaSuccess) { - err = std::string("ExpertCache::fill_slot: ") + cudaGetErrorString(e); - return false; - } - ++fills_; - return true; -} - -bool ExpertCache::fill_slot_blocking(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes) { - const size_t n = (size_t) (bytes > 0 && bytes <= blob_ ? bytes : blob_); - uint8_t* dst = device_slot(slot); - if (dst == nullptr) { - err = "ExpertCache::fill_slot_blocking: slot outside the arena"; - return false; - } - if (host_blob == nullptr) { - err = "ExpertCache::fill_slot_blocking: the host blob is null"; - return false; - } -#if defined(STRATA_USE_HIP) - // Bound HIP's pageable-source staging to one expert instead of repeatedly - // registering regions of the mmap. The blocking copy completes before reuse. - if (!blocking_staging_ || n > blocking_staging_bytes_) { - err = "ExpertCache::fill_slot_blocking: HIP staging buffer is too small"; - return false; - } - std::memcpy(blocking_staging_, host_blob, n); - const cudaError_t e = cudaMemcpy(dst, blocking_staging_, n, cudaMemcpyHostToDevice); -#else - const cudaError_t e = cudaMemcpy(dst, host_blob, n, cudaMemcpyHostToDevice); -#endif - if (e != cudaSuccess) { - err = std::string("ExpertCache::fill_slot_blocking: ") + cudaGetErrorString(e); - return false; - } - ++fills_; - return true; -} - -bool ExpertCache::fill_slot_queued(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes) { - const size_t n = (size_t) (bytes > 0 && bytes <= blob_ ? bytes : blob_); - uint8_t* dst = device_slot(slot); - if (dst == nullptr || host_blob == nullptr) { - err = dst == nullptr ? "ExpertCache::fill_slot_queued: slot outside the arena" - : "ExpertCache::fill_slot_queued: the host blob is null"; - return false; - } - const cudaError_t e = cudaMemcpyAsync(dst, host_blob, n, cudaMemcpyHostToDevice, (cudaStream_t) 0); - if (e != cudaSuccess) { - err = std::string("ExpertCache::fill_slot_queued: ") + cudaGetErrorString(e); - return false; - } - ++fills_; - return true; -} - -bool ExpertCache::sync_queued(std::string& err) { - const cudaError_t e = cudaStreamSynchronize((cudaStream_t) 0); - if (e != cudaSuccess) { - err = std::string("ExpertCache::sync_queued: ") + cudaGetErrorString(e); - return false; - } - return true; -} - -bool ExpertCache::verify_slot(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes) { - const int64_t nb = bytes > 0 && bytes <= blob_ ? bytes : blob_; - const uint8_t* src = device_slot(slot); - if (src == nullptr) { - err = "ExpertCache::verify_slot: slot outside the arena"; - return false; - } - // `cudaMemcpy` and not `cudaMemcpyAsync`: this is a startup check, and a check that can be read before it - // has happened is not a check. It also synchronises the fills queued before it, which is what makes the - // comparison meaningful. - std::vector got((size_t) nb); - const cudaError_t e = cudaMemcpy(got.data(), src, (size_t) nb, cudaMemcpyDeviceToHost); - if (e != cudaSuccess) { - err = std::string("ExpertCache::verify_slot: ") + cudaGetErrorString(e); - return false; - } - if (std::memcmp(got.data(), host_blob, (size_t) nb) != 0) { - size_t first = 0; - while (first < (size_t) nb && got[first] == host_blob[first]) ++first; - char buf[256]; - std::snprintf(buf, sizeof buf, - "ExpertCache::verify_slot: slot %d differs from the arena at byte %llu (of %lld)", - (int) slot, (unsigned long long) first, (long long) blob_); - err = buf; - return false; - } - return true; -} - -} // namespace strata::core diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp deleted file mode 100644 index 397196f..0000000 --- a/src/core/expert_source.cpp +++ /dev/null @@ -1,3046 +0,0 @@ -// src/core/expert_source.cpp - the adapter. See the header for the three clauses of the contract. -#include "strata/core/expert_source.hpp" -#include "strata/core/remote_experts.hpp" -#include "strata/core/peer_experts.hpp" -#include "strata/kernels/cpu/expert_layout.hpp" -#include "strata/artifact/gguf_reader.hpp" - -#include "strata/core/pinned.hpp" -#include "strata/platform/memory.hpp" -#include "strata/platform/robust_read.hpp" -#include "strata/kernels/elementwise.hpp" -#include "strata/kernels/quantize_act.hpp" -#include "strata/kernels/s2_expert_grouped.hpp" -#include "strata/kernels/cpu/kq_avx1.hpp" -#include "strata/kernels/cpu/kq_avx2.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(_WIN32) -#define WIN32_LEAN_AND_MEAN -#ifndef NOMINMAX -#define NOMINMAX // std::numeric_limits::max() below -#endif -#include -#else -#include -#include -#include -#include -#endif - -// a 64-bit seek (as in pinned.cu): the 32-bit `fseek` wraps past 4 GiB, and the spelling differs per platform -#ifndef STRATA_FSEEK64 -#ifdef _WIN32 -#define STRATA_FSEEK64(f, o) _fseeki64((f), (long long) (o), SEEK_SET) -#else -#define STRATA_FSEEK64(f, o) fseeko((f), (off_t) (o), SEEK_SET) -#endif -#endif - -namespace strata::core { - -namespace detail { - -bool cgroup_available_bytes(uint64_t limit, const CgroupMemoryStat& stat, uint64_t& bytes) { - bytes = 0; - if (!stat.valid) return false; - - // memory.stat's inactive_file can race memory.current, so bound it to charged usage first. - uint64_t reclaimable = std::min(stat.inactive_file, stat.current); - reclaimable = stat.file_dirty >= reclaimable ? 0 : reclaimable - stat.file_dirty; - reclaimable = stat.file_writeback >= reclaimable ? 0 : reclaimable - stat.file_writeback; - - // Reclaiming clean file pages reduces usage; saturating subtraction also handles a transient over-limit read. - const uint64_t usage_after_reclaim = stat.current - reclaimable; - bytes = usage_after_reclaim < limit ? limit - usage_after_reclaim : 0; - return true; -} - -bool make_cache_complement_plan( - int64_t n_layers, int64_t n_expert, const std::vector& layer_blob_bytes, - const std::vector>& primary_gpu_pairs, - const std::vector>& additional_gpu_pairs, - std::vector& offsets, uint64_t& bytes, std::string& err) { - offsets.clear(); - bytes = 0; - err.clear(); - if (n_layers <= 0 || n_expert <= 0 || layer_blob_bytes.size() != (size_t) n_layers) { - err = "FileExpertSource: invalid geometry for the cache complement plan"; - return false; - } - if ((uint64_t) n_layers > (uint64_t) std::numeric_limits::max() / (uint64_t) n_expert) { - err = "FileExpertSource: cache complement index table is too large"; - return false; - } - const size_t count = (size_t) n_layers * (size_t) n_expert; - std::vector omitted(count, 0); - auto mark_pairs = [&](const std::vector>& pairs, uint8_t bit, - const char* label) -> bool { - for (const auto& pair : pairs) { - if (pair.first < 0 || pair.second < 0 || pair.first >= n_layers || pair.second >= n_expert) { - err = std::string("FileExpertSource: ") + label + " pair is outside the expert geometry"; - return false; - } - const size_t index = (size_t) pair.first * (size_t) n_expert + (size_t) pair.second; - if ((omitted[index] & bit) != 0) { - err = std::string("FileExpertSource: duplicate ") + label + " pair in the cache complement plan"; - return false; - } - if (bit == 2 && (omitted[index] & 1) != 0) { - err = "FileExpertSource: the primary and additional GPU expert tiers overlap"; - return false; - } - omitted[index] |= bit; - } - return true; - }; - if (!mark_pairs(primary_gpu_pairs, 1, "primary GPU") || - !mark_pairs(additional_gpu_pairs, 2, "additional GPU")) return false; - for (uint64_t blob_bytes : layer_blob_bytes) { - if (blob_bytes == 0) { - err = "FileExpertSource: cache complement layer has zero-sized expert blobs"; - return false; - } - } - - offsets.assign(count, kNoCacheComplement); - for (int64_t layer = 0; layer < n_layers; ++layer) { - const uint64_t blob_bytes = layer_blob_bytes[(size_t) layer]; - for (int64_t expert = 0; expert < n_expert; ++expert) { - const size_t index = (size_t) layer * (size_t) n_expert + (size_t) expert; - if (omitted[index] != 0) continue; - if (bytes > std::numeric_limits::max() - blob_bytes) { - offsets.clear(); - bytes = 0; - err = "FileExpertSource: cache complement size overflows"; - return false; - } - offsets[index] = bytes; - bytes += blob_bytes; - } - } - if (bytes > (uint64_t) std::numeric_limits::max()) { - offsets.clear(); - bytes = 0; - err = "FileExpertSource: cache complement exceeds the host address space"; - return false; - } - return true; -} - -const uint8_t* cache_complement_blob_or_fallback( - size_t index, const std::vector& offsets, const uint8_t* complement_host, - const uint8_t* mapped_fallback) { - if (complement_host != nullptr && index < offsets.size() && offsets[index] != kNoCacheComplement) - return complement_host + (size_t) offsets[index]; - return mapped_fallback; -} - -int64_t choose_resident_keep_from(const std::vector& slot_bytes, uint64_t base_bytes, uint64_t budget, - int64_t lend_from) { - if (base_bytes > budget) return -1; - const int64_t slots = (int64_t) slot_bytes.size(); - if (lend_from < 0 || lend_from > slots) lend_from = slots; // no lend region: only the experts no slot holds - int64_t keep = slots; - uint64_t bytes = base_bytes; - while (keep > lend_from) { - const uint64_t b = slot_bytes[(size_t) keep - 1]; - if (b > budget - bytes) break; - bytes += b; - --keep; - } - return keep; -} - -bool exchange_cache_complement(std::vector& offsets, size_t in, size_t out) { - if (in == out || in >= offsets.size() || out >= offsets.size() || offsets[in] == kNoCacheComplement || - offsets[out] != kNoCacheComplement) return false; - offsets[out] = offsets[in]; - offsets[in] = kNoCacheComplement; - return true; -} - -} // namespace detail - -namespace { - -#if defined(__linux__) -bool read_cgroup_memory_stat(const std::filesystem::path& path, uint64_t current, - detail::CgroupMemoryStat& stat) { - std::ifstream input(path / "memory.stat"); - if (!input) return false; - - bool inactive_file = false, file_dirty = false, file_writeback = false; - std::string line; - while (std::getline(input, line)) { - std::istringstream fields(line); - std::string key; - uint64_t value = 0; - if (!(fields >> key >> value)) return false; - fields >> std::ws; - if (!fields.eof()) return false; - - if (key == "inactive_file") { - if (inactive_file) return false; - inactive_file = true; - stat.inactive_file = value; - } else if (key == "file_dirty") { - if (file_dirty) return false; - file_dirty = true; - stat.file_dirty = value; - } else if (key == "file_writeback") { - if (file_writeback) return false; - file_writeback = true; - stat.file_writeback = value; - } - } - if (!input.eof() || !inactive_file || !file_dirty || !file_writeback) return false; - stat.current = current; - stat.valid = true; - return true; -} -#endif - -} // namespace - -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; - MEMORYSTATUSEX status{}; - status.dwLength = sizeof(status); - if (!GlobalMemoryStatusEx(&status)) return false; - m.available = (uint64_t) status.ullAvailPhys; - return m.available > 0; -#elif defined(__linux__) - // MemAvailable includes reclaimable page cache, unlike _SC_AVPHYS_PAGES. - std::ifstream info(meminfo); - std::string line; - uint64_t bytes = 0; - while (std::getline(info, line)) { - std::istringstream fields(line); - std::string key, unit; - uint64_t value = 0; - if (fields >> key >> value >> unit && key == "MemAvailable:" && unit == "kB" && - value <= std::numeric_limits::max() / 1024) bytes = value * 1024; - } - if (bytes == 0) return false; - // Account for the tightest cgroup ancestor limit when its normal mount is visible. - // This is a point-in-time guard, not a reservation against concurrent allocations. - std::ifstream groups(self_cgroup); - if (!groups) return false; - const std::filesystem::path root(cgroup_root); - bool v2 = false; - std::string v1_path; // the memory controller's group (cgroup v1), when there is no v2 line - while (std::getline(groups, line)) { - if (line.rfind("0::/", 0) != 0) { - // v1: "N:controller[,controller]:/path" - const size_t c1 = line.find(':'), c2 = c1 == std::string::npos ? c1 : line.find(':', c1 + 1); - if (c2 == std::string::npos) continue; - std::istringstream ctl(line.substr(c1 + 1, c2 - c1 - 1)); - for (std::string c; std::getline(ctl, c, ',');) - if (c == "memory") v1_path = line.substr(c2 + 1); - continue; - } - auto path = (root / line.substr(4)).lexically_normal(); - if (path.string().rfind(root.string(), 0) != 0 || !std::filesystem::is_directory(path)) return false; - v2 = true; - while (path.string().rfind(root.string(), 0) == 0) { - std::ifstream limit_file(path / "memory.max"), current_file(path / "memory.current"); - std::string limit; - uint64_t current = 0; - const bool readable = bool(limit_file >> limit) && bool(current_file >> current); - // The host's root cgroup has no memory.max; ordinary child groups must expose their limits. - if (!readable && !(path == root && !std::filesystem::exists(path / "memory.max") && - std::filesystem::exists(path / "cgroup.controllers"))) return false; - if (readable && limit != "max") { - try { - size_t consumed = 0; - const uint64_t cap = std::stoull(limit, &consumed); - if (consumed != limit.size()) return false; - CgroupMemoryStat stat; - if (!read_cgroup_memory_stat(path, current, stat)) return false; - uint64_t cgroup_available = 0; - if (!cgroup_available_bytes(cap, stat, cgroup_available)) return false; - bytes = std::min(bytes, cgroup_available); - m.cgroup_limit = std::min(m.cgroup_limit, cap); - } catch (...) { return false; } - } - if (path == root) break; - path = path.parent_path(); - } - } - if (!v2 && !v1_path.empty()) { - // #633: cgroup v1 (older Docker hosts, RHEL 7/8): the memory controller's group and its ancestors. An - // unlimited group says a number near 2^63 (rounded to its page size); a group whose files are not - // visible (no mount in this namespace) is skipped - MemAvailable alone, as with no cgroup at all. - const std::filesystem::path mroot = root / "memory"; - auto path = (mroot / v1_path.substr(v1_path.rfind('/', 0) == 0 ? 1 : 0)).lexically_normal(); - while (path.string().rfind(mroot.string(), 0) == 0) { - std::ifstream limit_file(path / "memory.limit_in_bytes"), usage_file(path / "memory.usage_in_bytes"); - uint64_t cap = 0, usage = 0; - if (limit_file >> cap && usage_file >> usage && cap < (1ull << 62)) { - bytes = std::min(bytes, usage < cap ? cap - usage : 0); - m.cgroup_limit = std::min(m.cgroup_limit, cap); - } - if (path == mroot) break; - path = path.parent_path(); - } - } - m.available = bytes; - return true; -#else - (void) meminfo; (void) self_cgroup; (void) cgroup_root; - const long pages = sysconf(_SC_AVPHYS_PAGES); - const long page_bytes = sysconf(_SC_PAGESIZE); - if (pages <= 0 || page_bytes <= 0 || - (uint64_t) pages > std::numeric_limits::max() / (uint64_t) page_bytes) return false; - m.available = (uint64_t) pages * (uint64_t) page_bytes; - return m.available > 0; -#endif -} -} // namespace - -} // namespace detail - -namespace { - -bool available_memory_bytes(uint64_t& bytes) { - detail::HostMemory m; - if (!detail::host_available_memory(m)) return false; - bytes = m.available; - return bytes > 0; -} - -} // namespace - -// ================================ THE FILE-BACKED SOURCE ================================ - -FileExpertSource::~FileExpertSource() { close(); } - -bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err) { - close(); - if (n_layers <= 0 || n_expert <= 0) { err = "FileExpertSource: the geometry is empty"; return false; } - const auto& layout = strata::kernels::cpu::expert_layout(); - if (layout.n_layers != n_layers || layout.n_expert != n_expert) { - err = "FileExpertSource: the requested geometry does not match the loaded expert layout"; - return false; - } - if ((uint64_t) n_layers > (uint64_t) std::numeric_limits::max() / (uint64_t) n_expert) { - err = "FileExpertSource: the expert count overflows"; - return false; - } - const uint64_t blob_count = (uint64_t) n_layers * (uint64_t) n_expert; - if (blob_count > (uint64_t) std::numeric_limits::max() || - (uint64_t) n_layers > (uint64_t) std::numeric_limits::max()) { - err = "FileExpertSource: the expert count overflows"; - return false; - } - - std::vector layer_offsets((size_t) n_layers), layer_blob_bytes((size_t) n_layers); - const uint64_t want = layout.total; - if (want == 0 || want > (uint64_t) std::numeric_limits::max()) { - err = "FileExpertSource: the loaded expert layout has an invalid size"; - return false; - } - if (!layout.native) { - if (blob_count > std::numeric_limits::max() / (uint64_t) strata::kernels::cpu::BLOB) { - err = "FileExpertSource: the canonical expert size overflows"; - return false; - } - const uint64_t canonical_size = blob_count * (uint64_t) strata::kernels::cpu::BLOB; - if (want != canonical_size) { - err = "FileExpertSource: the canonical expert layout has an inconsistent size"; - return false; - } - const uint64_t bytes = (uint64_t) strata::kernels::cpu::BLOB; - const uint64_t layer_bytes = (uint64_t) n_expert * bytes; - for (int64_t layer = 0; layer < n_layers; ++layer) { - layer_offsets[(size_t) layer] = (uint64_t) layer * layer_bytes; - layer_blob_bytes[(size_t) layer] = bytes; - } - } else { - if (layout.offset.size() != (size_t) n_layers || layout.bytes.size() != (size_t) n_layers || - layout.fmt.size() != (size_t) n_layers) { - err = "FileExpertSource: the native expert layout is incomplete"; - return false; - } - uint64_t at = 0; - for (int64_t layer = 0; layer < n_layers; ++layer) { - const size_t i = (size_t) layer; - const uint64_t bytes = (uint64_t) layout.fmt[i].bytes; - if (layout.offset[i] != at || bytes == 0 || layout.bytes[i] != bytes || - bytes > std::numeric_limits::max() / (uint64_t) n_expert) { - err = "FileExpertSource: the native expert layout is invalid at layer " + std::to_string(layer); - return false; - } - const uint64_t layer_bytes = bytes * (uint64_t) n_expert; - if (at > want || layer_bytes > want - at) { - err = "FileExpertSource: the native expert layout exceeds its declared size at layer " + - std::to_string(layer); - return false; - } - layer_offsets[i] = layout.offset[i]; - layer_blob_bytes[i] = bytes; - at += layer_bytes; - } - if (at != want) { - err = "FileExpertSource: the native expert layout has an inconsistent size"; - return false; - } - } - const std::string path = pack_dir + "/experts.bin"; - if (layout.native && !gguf_.empty() && !std::filesystem::exists(path)) { - // CS-T: no experts.bin - the model's GGUF shards, read in place - blobs_ = (int64_t) blob_count; - n_layers_ = n_layers; - n_expert_ = n_expert; - layer_offsets_ = std::move(layer_offsets); - layer_blob_bytes_ = std::move(layer_blob_bytes); - if (!open_gguf(err)) { close(); return false; } - return true; - } - -#if defined(_WIN32) - // UTF-8 -> UTF-16: the pack may live under a path with non-ASCII characters, and `CreateFileA` would - // silently mangle it into a file-not-found. - const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0); - std::vector wpath((size_t) (wide > 0 ? wide : 1)); - if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide); - // **`FILE_FLAG_RANDOM_ACCESS` WAS HERE AND IT COST 14x.** - // - // The design depends on the OS page cache holding the whole 34 GB expert set, because this machine has - // 64 GB of DDR5 and `L9` measured the CPU path at 44.14 GB/s from DRAM. `FILE_FLAG_RANDOM_ACCESS` tells - // the cache manager the opposite: it disables read-ahead AND it lets the manager drop the pages again - // quickly, on the assumption that a large randomly-accessed file will not be re-read. Measured, on - // `strata generate --max-new 24`: **1.93 GB/s** - disk speed, 344 ms/token, and it never warmed up over 25 - // tokens, because the pages were being evicted as fast as they were faulted in. - // - // The correct flag is NO flag. The access pattern IS random (10 of 512 experts per layer, a different 10 - // each layer), but every byte read is read again on the next token, so retention is the whole game. - HANDLE f = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, nullptr); - if (f == INVALID_HANDLE_VALUE) { - err = "FileExpertSource: cannot open " + path; - return false; - } - LARGE_INTEGER sz{}; - if (!GetFileSizeEx(f, &sz)) { - CloseHandle(f); - err = "FileExpertSource: cannot size " + path; - return false; - } - if ((uint64_t) sz.QuadPart != want) { - char buf[400]; - std::snprintf(buf, sizeof buf, - "FileExpertSource: %s is %llu B but the loaded expert layout requires %llu B - this is not " - "the pack this geometry came from", - path.c_str(), (unsigned long long) sz.QuadPart, (unsigned long long) want); - CloseHandle(f); - err = buf; - return false; - } - HANDLE m = CreateFileMappingW(f, nullptr, PAGE_READONLY, 0, 0, nullptr); - if (m == nullptr) { - CloseHandle(f); - err = "FileExpertSource: CreateFileMapping failed on " + path; - return false; - } - void* view = MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0); - if (view == nullptr) { - CloseHandle(m); - CloseHandle(f); - err = "FileExpertSource: MapViewOfFile failed on " + path; - return false; - } - file_ = f; - mapping_ = m; - base_ = (const uint8_t*) view; - paths_.assign(1, path); -#else - const int fd = ::open(path.c_str(), O_RDONLY); - if (fd < 0) { err = "FileExpertSource: cannot open " + path; return false; } - struct stat st{}; - if (fstat(fd, &st) != 0) { ::close(fd); err = "FileExpertSource: cannot stat " + path; return false; } - if (st.st_size < 0 || (uint64_t) st.st_size != want) { - char buf[400]; - std::snprintf(buf, sizeof buf, - "FileExpertSource: %s is %llu B but the loaded expert layout requires %llu B - this is not " - "the pack this geometry came from", - path.c_str(), (unsigned long long) (st.st_size < 0 ? 0 : st.st_size), - (unsigned long long) want); - ::close(fd); - err = buf; - return false; - } - void* view = mmap(nullptr, (size_t) want, PROT_READ, MAP_SHARED, fd, 0); - if (view == MAP_FAILED) { ::close(fd); err = "FileExpertSource: mmap failed on " + path; return false; } - fd_ = fd; - base_ = (const uint8_t*) view; -#endif - blobs_ = (int64_t) blob_count; - n_layers_ = n_layers; - n_expert_ = n_expert; - mapped_bytes_ = want; - layer_offsets_ = std::move(layer_offsets); - layer_blob_bytes_ = std::move(layer_blob_bytes); - return true; -} - -void FileExpertSource::close() { - if (complement_arena_ != nullptr) { - if (complement_pinned_ && !complement_partial_) (void) cudaFreeHost(complement_arena_); - else { - if (complement_partial_) (void) cudaHostUnregister(complement_arena_); - if (complement_locked_ > 0) - strata::platform::unlock_resident((uint8_t*) complement_arena_ + complement_lock_off_, complement_locked_); - std::free(complement_arena_); - } - } - if (xstage_ != nullptr) { - if (xstage_pinned_) (void) cudaFreeHost(xstage_); - else std::free(xstage_); - } - xstage_ = nullptr; - xstage_pinned_ = false; - xstage_cap_ = 0; - xstage_blob_ = 0; - override_.clear(); - staged_.clear(); - exchanges_ = 0; - file_reads_.store(0); - complement_arena_ = nullptr; - complement_host_ = nullptr; - complement_device_ = nullptr; - complement_bytes_ = 0; - complement_offsets_.clear(); - complement_pinned_ = false; - complement_partial_ = false; - complement_pin_limit_ = 0; - complement_lock_off_ = 0; - complement_ready_ = false; - complement_locked_ = 0; - complement_lent_slots_ = 0; - if (!maps_.empty()) { - for (Map& m : maps_) { -#if defined(_WIN32) - if (m.base != nullptr) UnmapViewOfFile((LPCVOID) m.base); - if (m.mapping != nullptr) CloseHandle((HANDLE) m.mapping); - if (m.file != nullptr) CloseHandle((HANDLE) m.file); -#else - if (m.base != nullptr) munmap((void*) m.base, (size_t) m.bytes); - if (m.fd >= 0) ::close(m.fd); -#endif - } - maps_.clear(); - base_ = nullptr; // one of the views above - } - role_ptr_.clear(); - role_bytes_.clear(); - role_file_.clear(); - paths_.clear(); -#if defined(_WIN32) - for (void* h : direct_) CloseHandle((HANDLE) h); -#endif - direct_.clear(); - { - std::lock_guard lk(stage_mu_); - stage_buf_.clear(); - stage_key_.clear(); - stage_epoch_.clear(); - stage_used_.clear(); - stage_busy_.clear(); - stage_of_.clear(); - stage_blob_ = 0; - stage_seq_ = 0; - epoch_ = 0; - last_layer_ = -1; - stage_grew_ = false; - } - ram_reads_.store(0); - warm_stamp_.reset(); - warm_hits_.store(0); - warm_count_.store(0); - file_read_bytes_.store(0); - file_blob_bytes_.store(0); - file_us_.store(0); -#if defined(_WIN32) - if (base_ != nullptr) UnmapViewOfFile((LPCVOID) base_); - if (mapping_ != nullptr) CloseHandle((HANDLE) mapping_); - if (file_ != nullptr) CloseHandle((HANDLE) file_); - mapping_ = nullptr; - file_ = nullptr; -#else - if (base_ != nullptr) munmap((void*) base_, (size_t) mapped_bytes_); - if (fd_ >= 0) ::close(fd_); - fd_ = -1; -#endif - base_ = nullptr; - blobs_ = 0; - n_layers_ = 0; - n_expert_ = 0; - mapped_bytes_ = 0; - layer_offsets_.clear(); - layer_blob_bytes_.clear(); - reads_ = 0; -} - - -bool ExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) { - const uint8_t* b = blob(layer, expert); - if (b == nullptr || dst == nullptr) return false; - std::memcpy(dst, b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(layer)); - return true; -} - -// ================================ CS-T: THE GGUF SHARDS IN PLACE ================================ -// -// A native pack without experts.bin: every file native_experts.txt names is mapped (MapViewOfFile / mmap, no -// flag - the same retention argument as experts.bin above), and an expert's blob [gate rows | up rows | down rows] -// is three slices of three tensors, possibly in two shards (UD-Q4_K_XL's layer 11). Nothing is read at open; a -// blob is assembled when it is asked for (`blob`, into a small pool of buffers) or copied where it is needed -// (`copy_blob`: the RAM copy, the prompt path's pinned stager buffers). -bool FileExpertSource::open_gguf(std::string& err) { - const auto& lay = strata::kernels::cpu::expert_layout(); - if (!check_experts_gguf(gguf_, lay, err)) { err = "FileExpertSource: " + err; return false; } - const size_t cut = gguf_.find_last_of("/\\"); - const std::string dir = cut == std::string::npos ? std::string() : gguf_.substr(0, cut + 1); - std::map index; - role_ptr_.assign((size_t) (3 * n_layers_), nullptr); - role_bytes_.assign((size_t) (3 * n_layers_), 0); - role_file_.assign((size_t) (3 * n_layers_), 0); - for (int64_t l = 0; l < n_layers_; ++l) { - const auto& fm = lay.fmt[(size_t) l]; - const uint64_t per[3] = {fm.up_off, fm.up_off, lay.bytes[(size_t) l] - fm.down_off}; - for (int r = 0; r < 3; ++r) { - const size_t i = (size_t) (3 * l + r); - const std::string path = lay.gguf_file.size() > i && !lay.gguf_file[i].empty() ? dir + lay.gguf_file[i] - : gguf_; - auto it = index.find(path); - if (it == index.end()) { - Map m; -#if defined(_WIN32) - const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0); - std::vector wpath((size_t) (wide > 0 ? wide : 1)); - if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide); - HANDLE f = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, nullptr); - LARGE_INTEGER sz{}; - if (f == INVALID_HANDLE_VALUE || !GetFileSizeEx(f, &sz)) { - if (f != INVALID_HANDLE_VALUE) CloseHandle(f); - err = "FileExpertSource: cannot open " + path; - return false; - } - HANDLE mh = CreateFileMappingW(f, nullptr, PAGE_READONLY, 0, 0, nullptr); - void* view = mh != nullptr ? MapViewOfFile(mh, FILE_MAP_READ, 0, 0, 0) : nullptr; - if (view == nullptr) { - if (mh != nullptr) CloseHandle(mh); - CloseHandle(f); - err = "FileExpertSource: cannot map " + path; - return false; - } - m.file = f; - m.mapping = mh; - m.bytes = (uint64_t) sz.QuadPart; - m.base = (const uint8_t*) view; -#else - const int fd = ::open(path.c_str(), O_RDONLY); - struct stat st{}; - if (fd < 0 || fstat(fd, &st) != 0 || st.st_size <= 0) { - if (fd >= 0) ::close(fd); - err = "FileExpertSource: cannot open " + path; - return false; - } - void* view = mmap(nullptr, (size_t) st.st_size, PROT_READ, MAP_SHARED, fd, 0); - if (view == MAP_FAILED) { ::close(fd); err = "FileExpertSource: cannot map " + path; return false; } - m.fd = fd; - m.bytes = (uint64_t) st.st_size; - m.base = (const uint8_t*) view; -#endif - maps_.push_back(m); - paths_.push_back(path); - it = index.emplace(path, maps_.size() - 1).first; - } - const Map& m = maps_[it->second]; - role_file_[i] = (int) it->second; - const uint64_t at = lay.gguf_off[i], bytes = per[r] * (uint64_t) n_expert_; - if (at > m.bytes || bytes > m.bytes - at) { // check_experts_gguf proved it; the mapping must agree - err = "FileExpertSource: an expert span runs past the end of " + path; - return false; - } - role_ptr_[i] = m.base + (size_t) at; - role_bytes_[i] = per[r]; - } - } - base_ = maps_.front().base; // "opened"; mapped_blob answers nullptr in this mode - warm_stamp_.reset(new std::atomic[(size_t) (n_layers_ * n_expert_)]()); - for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b); - return true; -} - -bool FileExpertSource::copy_from_files(int64_t layer, int64_t expert, uint8_t* dst) const { - if (dst == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false; - if (!direct_.empty()) { // #286: from the drive; a failed read falls back to the mapping below - const Fill f{0, layer, expert, dst}; - if (read_direct(&f, 1)) return true; - } - if (!role_ptr_.empty()) { - uint64_t at = 0; - for (int r = 0; r < 3; ++r) { - const size_t i = (size_t) (3 * layer + r); - const uint64_t per = role_bytes_[i]; - std::memcpy(dst + at, role_ptr_[i] + (size_t) ((uint64_t) expert * per), (size_t) per); - at += per; - } - return true; - } - const uint8_t* b = mapped_blob(layer, expert); - if (b == nullptr) return false; - std::memcpy(dst, b, (size_t) layer_blob_bytes_[(size_t) layer]); - return true; -} - -// A blob assembled from the three role slices. The buffer of a (layer, expert) is reused for another only once -// its blob has not been asked for during `kStageAge` layers (begin_layer) or 256 assemblies, whichever comes -// first, and never while it is being filled: the pool computes a layer's misses before it starts the next, and a -// fill (the GPU cache at startup, an adaptive swap, a helper GPU) copies the blob right away. -// -// `claim_stage` finds or reserves the buffer of `key` (stage_mu_ held): true when the blob is already there (or -// being filled by another thread - the caller then waits), false when the caller must fill buffer `v`. -bool FileExpertSource::claim_stage(int64_t key, size_t& v, bool& fill) { - constexpr uint64_t kStageSeq = 256; - const uint64_t seq = ++stage_seq_; - auto it = stage_of_.find(key); - fill = false; - if (it != stage_of_.end()) { - v = it->second; - stage_epoch_[v] = epoch_; - stage_used_[v] = seq; - return true; - } - v = stage_buf_.size(); - uint64_t oldest = std::numeric_limits::max(); - for (size_t i = 0; i < stage_buf_.size(); ++i) - if (!stage_busy_[i] && (stage_epoch_[i] + kStageAge <= epoch_ || stage_used_[i] + kStageSeq <= seq) && - stage_used_[i] < oldest) { - oldest = stage_used_[i]; - v = i; - } - if (v == stage_buf_.size()) { - stage_buf_.emplace_back(new (std::nothrow) uint8_t[(size_t) stage_blob_]); - if (!stage_buf_.back()) { stage_buf_.pop_back(); return false; } - stage_key_.push_back(-1); - stage_epoch_.push_back(0); - stage_used_.push_back(0); - stage_busy_.push_back(0); - if (stage_buf_.size() == 512 && !stage_grew_) { - stage_grew_ = true; - std::fprintf(stderr, "FileExpertSource: %zu blobs assembled from the GGUF are in use at once (%.2f GiB)\n", - stage_buf_.size(), (double) stage_buf_.size() * (double) stage_blob_ / 1073741824.0); - } - } else { - stage_of_.erase(stage_key_[v]); - } - stage_key_[v] = key; - stage_epoch_[v] = epoch_; - stage_used_[v] = seq; - stage_busy_[v] = 1; - stage_of_[key] = v; - fill = true; - return false; -} - -// Fills buffer `v` (reserved by claim_stage) outside the lock, then publishes it. -bool FileExpertSource::fill_stage(size_t v, int64_t layer, int64_t expert, uint8_t* dst) { - const auto t0 = std::chrono::steady_clock::now(); - const bool ok = copy_from_files(layer, expert, dst); - publish_stage(v, layer, ok, std::chrono::duration(std::chrono::steady_clock::now() - t0).count()); - return ok; -} - -void FileExpertSource::publish_stage(size_t v, int64_t layer, bool ok, double us) { - file_us_.fetch_add((uint64_t) us, std::memory_order_relaxed); - if (ok) { - file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed); - file_blob_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed); - } - { - std::lock_guard lk(stage_mu_); - stage_busy_[v] = 0; - if (!ok) { - stage_of_.erase(stage_key_[v]); - stage_key_[v] = -1; - } - } - stage_cv_.notify_all(); -} - -const uint8_t* FileExpertSource::staged_blob(int64_t layer, int64_t expert) { - const int64_t key = layer * n_expert_ + expert; - size_t v = 0; - bool fill = false; - uint8_t* dst = nullptr; - { - std::unique_lock lk(stage_mu_); - const bool have = claim_stage(key, v, fill); - if (!have && !fill) return nullptr; - dst = stage_buf_[v].get(); - if (have) { - // another thread (a prefetch, the adaptive tier) is filling it: wait for that - stage_cv_.wait(lk, [&] { return !stage_busy_[v] || stage_key_[v] != key; }); - if (stage_key_[v] != key) return nullptr; // its fill failed - return dst; - } - } - return fill_stage(v, layer, expert, dst) ? dst : nullptr; -} - -void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n) { - if (!staged() || n <= 0 || layer < 0 || layer >= n_layers_) return; - std::vector todo; - { - std::lock_guard lk(stage_mu_); - for (int64_t i = 0; i < n; ++i) { - const int64_t e = experts[i]; - if (e < 0 || e >= n_expert_) continue; - const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e; - if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement) - continue; // in the RAM copy - if (!override_.empty() && override_[index] != nullptr) continue; - size_t v = 0; - bool fill = false; - if (!claim_stage(layer * n_expert_ + e, v, fill) && fill) { - todo.push_back({v, layer, e, stage_buf_[v].get()}); - if (warm_stamp_) { - const uint32_t s = warm_stamp_[index].load(std::memory_order_relaxed); - if (s != 0 && (uint64_t) s + 3 >= epoch_ + 1) warm_hits_.fetch_add(1, std::memory_order_relaxed); - } - } - } - } - fill_many(todo); -} - -void FileExpertSource::prefetch_pairs(const std::pair* pairs, int64_t n) { - if (direct_.empty() || pairs == nullptr || n <= 0) return; // unbuffered only: the mapped fill stays as it was - std::vector todo; - { - std::lock_guard lk(stage_mu_); - for (int64_t i = 0; i < std::min(n, 64); ++i) { - const int64_t l = pairs[i].first, e = pairs[i].second; - if (l < 0 || e < 0 || l >= n_layers_ || e >= n_expert_) continue; - size_t v = 0; - bool fill = false; - if (!claim_stage(l * n_expert_ + e, v, fill) && fill) todo.push_back({v, l, e, stage_buf_[v].get()}); - } - } - fill_many(todo); -} - -void FileExpertSource::fill_many(const std::vector& todo) { - if (todo.empty()) return; - if (!direct_.empty()) { - // #286: overlapped batches - every role window of 16 blobs in flight at once; a big batch (the profile - // fill) on up to 4 threads, a decode layer's few misses on this one - std::atomic next{0}; - auto work = [&] { - for (size_t at; (at = next.fetch_add(16)) < todo.size();) { - const size_t k = std::min(16, todo.size() - at); - const auto t0 = std::chrono::steady_clock::now(); - const bool ok = read_direct(todo.data() + at, k); - const double us = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - for (size_t i = at; i < at + k; ++i) { - const Fill& f = todo[i]; - // a failed batch: each blob again on its own (copy_from_files falls back to the mapping) - if (ok) publish_stage(f.v, f.layer, true, us / (double) k); - else (void) fill_stage(f.v, f.layer, f.e, f.dst); - } - } - }; - const size_t nt = std::min(4, (todo.size() + 15) / 16); - std::vector th; - for (size_t t = 1; t < nt; ++t) th.emplace_back(work); - work(); - for (auto& t : th) t.join(); - return; - } -#if defined(_WIN32) - // One PrefetchVirtualMemory call for every slice about to be copied: the memory manager reads them in large - // requests, all queued at once, where the copies' page faults would read a few clusters each. The copies below - // then find the pages resident (or in flight). STRATA_FETCH_PVM=0 is the A/B arm. - { - using Pvm = BOOL(WINAPI*)(HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG); - static const Pvm pvm = [] { - const char* v = std::getenv("STRATA_FETCH_PVM"); - if (v != nullptr && std::atoi(v) == 0) return (Pvm) nullptr; - return (Pvm) (void*) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "PrefetchVirtualMemory"); - }(); - if (pvm != nullptr) { - std::vector ranges; - ranges.reserve(todo.size() * 3); - for (const Fill& f : todo) - for (int r = 0; r < 3; ++r) { - const size_t i = (size_t) (3 * f.layer + r); - ranges.push_back({(PVOID) (role_ptr_[i] + (size_t) ((uint64_t) f.e * role_bytes_[i])), - (SIZE_T) role_bytes_[i]}); - } - (void) pvm(GetCurrentProcess(), (ULONG_PTR) ranges.size(), ranges.data(), 0); - } - } -#endif - // the page faults of a mapped read are one outstanding request each: several threads keep the SSD's queue full - std::atomic next{0}; - auto work = [&] { - for (size_t i; (i = next.fetch_add(1)) < todo.size();) - (void) fill_stage(todo[i].v, todo[i].layer, todo[i].e, todo[i].dst); - }; - const size_t nt = std::min(todo.size(), (size_t) fetch_threads_); - std::vector th; - for (size_t t = 1; t < nt; ++t) th.emplace_back(work); - work(); - for (auto& t : th) t.join(); -} - -uint64_t FileExpertSource::expert_bytes() const { - uint64_t total = 0; - for (uint64_t b : layer_blob_bytes_) total += b * (uint64_t) n_expert_; - return total; -} - -bool FileExpertSource::open_direct(std::string& why) { -#if defined(_WIN32) - for (const std::string& path : paths_) { - const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0); - std::vector w((size_t) (wide > 0 ? wide : 1), L'\0'); - if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, w.data(), wide); - HANDLE h = CreateFileW(w.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, - FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED, nullptr); - if (h == INVALID_HANDLE_VALUE) { - why += "; cannot open " + path + " unbuffered (error " + std::to_string((unsigned long long) GetLastError()) + - "), read through the file cache"; - for (void* d : direct_) CloseHandle((HANDLE) d); - direct_.clear(); - return false; - } - direct_.push_back(h); - } - if (role_ptr_.empty()) { // experts.bin: blob() now assembles into the stage buffers, sized for the largest blob - std::lock_guard lk(stage_mu_); - for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b); - } - return true; -#else - (void) why; - return false; -#endif -} - -bool FileExpertSource::set_unbuffered(uint64_t ram_bytes, std::string& why) { -#if defined(_WIN32) - if (base_ == nullptr || paths_.empty() || !direct_.empty()) { - why = !direct_.empty() ? "already unbuffered" : "no expert files open"; - return !direct_.empty(); - } - // #577: the file tier reads the experts outside the RAM copy, not every byte of the shards (dense weights, the - // PLE table), and the copy holds at most every expert - the budget asked for can be more than that - const uint64_t experts = expert_bytes(); - const uint64_t arena = std::min(ram_bytes, experts); - if (!experts_unbuffered(paths_, arena, why, /*cache_counts=*/false, experts - arena)) return false; - return open_direct(why); -#else - (void) ram_bytes; - why = "through the file cache (not Windows)"; - return false; -#endif -} - -bool FileExpertSource::recheck_unbuffered(std::string& why) { -#if defined(_WIN32) - if (const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); env != nullptr && env[0] != '\0') { - why = std::string("STRATA_UNBUFFERED_LOAD=") + env; - return !direct_.empty(); - } - if (base_ == nullptr || paths_.empty()) { - why = "no expert files open"; - return false; - } - // #577: the RAM copy is built (and already out of the available RAM), so what the file cache would have to keep - // is exactly the experts outside it - the GPU cache's (refilled after a prompt borrowed their slots) and the - // ones neither holds - const uint64_t experts = expert_bytes(); - const uint64_t read = experts > complement_bytes_ ? experts - complement_bytes_ : 0; - std::string w; - const bool ub = experts_unbuffered(paths_, 0, w, /*cache_counts=*/false, read); - char head[96]; - std::snprintf(head, sizeof head, "re-checked with the RAM copy built (%.2f GiB): ", - (double) complement_bytes_ / 1073741824.0); - why = head + w; - if (ub == !direct_.empty()) return ub; - if (ub) return open_direct(why); - // through the file cache after all: the mapped reads take over (staged() stays true for the GGUF in place) - for (void* d : direct_) CloseHandle((HANDLE) d); - direct_.clear(); - return false; -#else - why = "through the file cache (not Windows)"; - return false; -#endif -} - -bool FileExpertSource::read_direct(const Fill* fills, size_t n) const { -#if defined(_WIN32) - // NTFS runs the unbuffered reads of a file one at a time while the file is mapped or cached anywhere (the engine - // maps the GGUF shards for the token embedding and the PLE table): measured on a PCIe 5 drive, 512 KiB reads at - // queue depth 48 make 10.4 GB/s on a file nobody maps and 3.4 GB/s on a mapped one, 8 MiB reads 8.6 GB/s. So - // windows less than kGap apart (the same role of nearby experts) are merged into requests of up to kMerge bytes. - constexpr uint64_t kSector = 4096, kGap = 1ull << 20, kMerge = 32ull << 20; - struct Window { int file; uint64_t a0, size, skip, n, at; uint8_t* dst; size_t req; uint64_t in_req; }; - struct Req { HANDLE h; uint64_t a0, size, pos; }; - // this thread's aligned buffer and events, kept for its next batch - struct Scratch { - uint8_t* buf = nullptr; - size_t cap = 0; - std::vector ev; - std::vector ov; - std::vector win; - std::vector order; - std::vector req; - std::vector got; - ~Scratch() { - if (buf != nullptr) VirtualFree(buf, 0, MEM_RELEASE); - for (HANDLE e : ev) CloseHandle(e); - } - }; - thread_local Scratch sc; - sc.win.clear(); - for (size_t k = 0; k < n; ++k) { - const Fill& f = fills[k]; - if (f.dst == nullptr || f.layer < 0 || f.e < 0 || f.layer >= n_layers_ || f.e >= n_expert_) return false; - if (role_ptr_.empty()) { // experts.bin: the blob is one contiguous range - const uint64_t per = layer_blob_bytes_[(size_t) f.layer]; - const uint64_t off = layer_offsets_[(size_t) f.layer] + (uint64_t) f.e * per; - const uint64_t a0 = off / kSector * kSector, a1 = (off + per + kSector - 1) / kSector * kSector; - sc.win.push_back({0, a0, a1 - a0, off - a0, per, 0, f.dst, 0, 0}); - continue; - } - uint64_t at = 0; - for (int r = 0; r < 3; ++r) { - const size_t i = (size_t) (3 * f.layer + r); - const uint64_t per = role_bytes_[i]; - const Map& m = maps_[(size_t) role_file_[i]]; - const uint64_t off = (uint64_t) (role_ptr_[i] - m.base) + (uint64_t) f.e * per; - const uint64_t a0 = off / kSector * kSector, a1 = (off + per + kSector - 1) / kSector * kSector; - sc.win.push_back({role_file_[i], a0, a1 - a0, off - a0, per, at, f.dst, 0, 0}); - at += per; - } - } - sc.order.resize(sc.win.size()); - for (size_t w = 0; w < sc.win.size(); ++w) sc.order[w] = w; - std::sort(sc.order.begin(), sc.order.end(), [&](size_t a, size_t b) { - return sc.win[a].file != sc.win[b].file ? sc.win[a].file < sc.win[b].file : sc.win[a].a0 < sc.win[b].a0; - }); - sc.req.clear(); - uint64_t total = 0; - int last_file = -1; - for (size_t w : sc.order) { - Window& x = sc.win[w]; - if (!sc.req.empty() && x.file == last_file) { - Req& q = sc.req.back(); - const uint64_t end = q.a0 + q.size, xend = x.a0 + x.size; - if (x.a0 <= end + kGap && std::max(end, xend) - q.a0 <= kMerge) { - if (xend > end) { - total += xend - end; - q.size = xend - q.a0; - } - x.req = sc.req.size() - 1; - x.in_req = x.a0 - q.a0; - continue; - } - } - sc.req.push_back({(HANDLE) direct_[(size_t) x.file], x.a0, x.size, total}); - total += x.size; - last_file = x.file; - x.req = sc.req.size() - 1; - x.in_req = 0; - } - if (total > sc.cap) { - if (sc.buf != nullptr) VirtualFree(sc.buf, 0, MEM_RELEASE); - sc.cap = (size_t) ((total + (1u << 20) - 1) >> 20 << 20); - sc.buf = (uint8_t*) VirtualAlloc(nullptr, sc.cap, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); - if (sc.buf == nullptr) { sc.cap = 0; return false; } - } - while (sc.ev.size() < sc.req.size()) { - HANDLE e = CreateEventW(nullptr, TRUE, FALSE, nullptr); - if (e == nullptr) return false; - sc.ev.push_back(e); - } - sc.ov.assign(sc.req.size(), OVERLAPPED{}); - // every request in flight before the first wait: the drive sees the whole batch as one queue - size_t issued = 0; - bool ok = true; - for (size_t q = 0; q < sc.req.size(); ++q) { - const Req& r = sc.req[q]; - OVERLAPPED& o = sc.ov[q]; - o.Offset = (DWORD) r.a0; - o.OffsetHigh = (DWORD) (r.a0 >> 32); - o.hEvent = sc.ev[q]; - if (!ReadFile(r.h, sc.buf + r.pos, (DWORD) r.size, nullptr, &o) && GetLastError() != ERROR_IO_PENDING) { - ok = false; - break; - } - ++issued; - } - std::vector& got = sc.got; - got.assign(sc.req.size(), 0); - for (size_t q = 0; q < issued; ++q) - if (!GetOverlappedResult(sc.req[q].h, &sc.ov[q], &got[q], TRUE)) ok = false; - if (!ok || issued < sc.req.size()) return false; - for (const Window& x : sc.win) { - // a request may run past the end of the file: only the role's own bytes have to arrive - if ((uint64_t) got[x.req] < x.in_req + x.skip + x.n) return false; - std::memcpy(x.dst + x.at, sc.buf + sc.req[x.req].pos + x.in_req + x.skip, (size_t) x.n); - } - return true; -#else - (void) fills; (void) n; - return false; -#endif -} - -void FileExpertSource::warm(int64_t layer, const int64_t* experts, int64_t n) { - if (role_ptr_.empty() || n <= 0 || layer < 0 || layer >= n_layers_) return; - uint32_t stamp; - { - std::lock_guard lk(stage_mu_); - stamp = (uint32_t) epoch_ + 1; - } -#if defined(_WIN32) - using Pvm = BOOL(WINAPI*)(HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG); - static const Pvm pvm = (Pvm) (void*) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "PrefetchVirtualMemory"); - std::vector ranges; -#endif - for (int64_t j = 0; j < n; ++j) { - const int64_t e = experts[j]; - if (e < 0 || e >= n_expert_) continue; - const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e; - if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement) - continue; // in the RAM copy - if (warm_stamp_) warm_stamp_[index].store(stamp, std::memory_order_relaxed); - warm_count_.fetch_add(1, std::memory_order_relaxed); - for (int r = 0; r < 3; ++r) { - const size_t i = (size_t) (3 * layer + r); - const uint8_t* p = role_ptr_[i] + (size_t) ((uint64_t) e * role_bytes_[i]); -#if defined(_WIN32) - ranges.push_back({(PVOID) p, (SIZE_T) role_bytes_[i]}); -#else - const uintptr_t pg = 4096, a = (uintptr_t) p & ~(pg - 1); - (void) madvise((void*) a, (size_t) ((uintptr_t) p + role_bytes_[i] - a), MADV_WILLNEED); -#endif - } - } -#if defined(_WIN32) - if (pvm != nullptr && !ranges.empty()) (void) pvm(GetCurrentProcess(), (ULONG_PTR) ranges.size(), ranges.data(), 0); -#endif -} - -RouterLookahead::~RouterLookahead() { - { - std::lock_guard lk(mu_); - quit_ = true; - } - cv_.notify_all(); - if (thread_.joinable()) thread_.join(); -} - -bool RouterLookahead::start(std::vector> routers, int64_t n_embd, int64_t n_expert, int k, - ExpertSource* src, std::string& err) { - if (src == nullptr || !src->warms()) { err = "RouterLookahead: the expert source does not warm"; return false; } - if (n_embd % 8 != 0) { err = "RouterLookahead: n_embd is not a multiple of 8"; return false; } - for (const auto& r : routers) - if (r.size() != (size_t) (n_embd * n_expert)) { err = "RouterLookahead: a router of another shape"; return false; } - routers_ = std::move(routers); - n_embd_ = n_embd; - n_expert_ = n_expert; - k_ = k < 1 ? 1 : k > (int) n_expert ? (int) n_expert : k; - src_ = src; - x_.assign((size_t) (8 * n_embd), 0.f); - thread_ = std::thread([this] { run(); }); - return true; -} - -void RouterLookahead::submit(int64_t layer, const float* x, int64_t n_tok, const int32_t* host_res) { - if (layer + 1 >= (int64_t) routers_.size() || n_tok <= 0 || x == nullptr) return; - { - std::lock_guard lk(mu_); - if (busy_ || pending_) { skipped_.fetch_add(1, std::memory_order_relaxed); return; } - n_tok_ = std::min(n_tok, 8); - std::memcpy(x_.data(), x, (size_t) (n_tok_ * n_embd_) * sizeof(float)); - layer_ = layer + 1; - host_res_ = host_res; - pending_ = true; - } - cv_.notify_one(); -} - -void RouterLookahead::run() { - std::vector logits((size_t) (8 * n_expert_)); - std::vector order((size_t) n_expert_); - std::vector want; - for (;;) { - int64_t layer, nt; - const int32_t* host_res; - { - std::unique_lock lk(mu_); - cv_.wait(lk, [&] { return quit_ || pending_; }); - if (quit_) return; - pending_ = false; - busy_ = true; - layer = layer_; - nt = n_tok_; - host_res = host_res_; - } - const auto t0 = std::chrono::steady_clock::now(); - want.clear(); - // The router dot is AVX2 (kq_avx2.cpp); a CPU without AVX2 (the experimental older-CPU builds) takes the AVX1 - // one (kq_avx1.cpp) or, without AVX, the same sums in plain C++. From the Strata_Dirigo fork (rwkeyes): an - // AVX-only Xeon E5-2687W died here (vpmovzxwd) on its first request. An estimate only (which experts to - // prefetch); the order of the additions differs between the three, the output does not depend on it. - if (strata::kernels::cpu::cpu_avx2_ok()) { - strata::kernels::cpu::bf16_rows_dot_multi(routers_[(size_t) layer].data(), (int) n_expert_, (int) n_embd_, - x_.data(), (int) nt, logits.data()); - } else if (strata::kernels::cpu::cpu_avx1_ok()) { - strata::kernels::cpu::bf16_rows_dot_multi_avx1(routers_[(size_t) layer].data(), (int) n_expert_, - (int) n_embd_, x_.data(), (int) nt, logits.data()); - } else { - // a mul and an add, not std::fma: without an FMA instruction that is a libm call per element (74x - // slower on a Xeon E5-2665, measured by the fork) - const uint16_t* rw = routers_[(size_t) layer].data(); - for (int64_t r = 0; r < n_expert_; ++r) { - const uint16_t* wr = rw + (size_t) r * (size_t) n_embd_; - for (int64_t t = 0; t < nt; ++t) { - const float* xr = x_.data() + (size_t) t * (size_t) n_embd_; - float acc = 0.0f; - for (int64_t c = 0; c < n_embd_; ++c) { - const uint32_t bits = (uint32_t) wr[c] << 16; - float wf; - std::memcpy(&wf, &bits, sizeof wf); - acc += wf * xr[c]; - } - logits[(size_t) t * (size_t) n_expert_ + (size_t) r] = acc; - } - } - } - for (int64_t t = 0; t < nt; ++t) { - const float* lt = logits.data() + (size_t) (t * n_expert_); - for (int64_t e = 0; e < n_expert_; ++e) order[(size_t) e] = (int32_t) e; - std::partial_sort(order.begin(), order.begin() + k_, order.end(), - [&](int32_t a, int32_t b) { return lt[(size_t) a] > lt[(size_t) b]; }); - for (int j = 0; j < k_; ++j) { - const int64_t e = order[(size_t) j]; - if (host_res != nullptr && host_res[(size_t) (layer * n_expert_ + e)] >= 0) continue; // on the GPU - if (std::find(want.begin(), want.end(), e) == want.end()) want.push_back(e); - } - } - src_->warm(layer, want.data(), (int64_t) want.size()); - predicted_.fetch_add((int64_t) want.size(), std::memory_order_relaxed); - busy_us_.fetch_add((uint64_t) std::chrono::duration(std::chrono::steady_clock::now() - t0).count(), - std::memory_order_relaxed); - { - std::lock_guard lk(mu_); - busy_ = false; - } - } -} - -void FileExpertSource::begin_layer(int64_t layer, const int32_t* ids, int64_t k) { - (void) ids; - (void) k; - if (!staged()) return; - std::lock_guard lk(stage_mu_); - if (layer != last_layer_) { - ++epoch_; - last_layer_ = layer; - } -} - -bool FileExpertSource::transient(int64_t layer, int64_t expert) const { - if (!staged() || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false; - const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; - if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement) - return false; - return override_.empty() || override_[index] == nullptr; -} - -bool FileExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) { - if (base_ == nullptr || dst == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) - return false; - const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; - const uint64_t bytes = layer_blob_bytes_[(size_t) layer]; - if (complement_ready_) { - const uint8_t* held = - detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr); - if (held == nullptr && !override_.empty()) held = override_[index]; - if (held != nullptr) { - std::memcpy(dst, held, (size_t) bytes); - return true; - } - } - const auto t0 = std::chrono::steady_clock::now(); - if (!copy_from_files(layer, expert, dst)) return false; - file_us_.fetch_add((uint64_t) std::chrono::duration(std::chrono::steady_clock::now() - t0).count(), - std::memory_order_relaxed); - file_read_bytes_.fetch_add(bytes, std::memory_order_relaxed); - return true; -} - -const uint8_t* FileExpertSource::mapped_blob(int64_t layer, int64_t expert) const { - if (!role_ptr_.empty()) return nullptr; // the GGUF in place: no contiguous blob in any file - if (base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return nullptr; - const size_t i = (size_t) layer; - if (i >= layer_offsets_.size() || i >= layer_blob_bytes_.size()) return nullptr; - const uint64_t blob_bytes = layer_blob_bytes_[i]; - if (blob_bytes == 0 || (uint64_t) expert > std::numeric_limits::max() / blob_bytes) return nullptr; - const uint64_t expert_offset = (uint64_t) expert * blob_bytes; - const uint64_t layer_offset = layer_offsets_[i]; - if (layer_offset > mapped_bytes_ || expert_offset > mapped_bytes_ - layer_offset) return nullptr; - const uint64_t offset = layer_offset + expert_offset; - if (blob_bytes > mapped_bytes_ - offset) return nullptr; - return base_ + (size_t) offset; -} - -bool FileExpertSource::pin_cache_complement( - const ExpertCache& cache, std::string& err, bool pin, - const std::vector>& additional_gpu_pairs, int64_t lend_from_slot, - uint64_t headroom_bytes, uint64_t budget_bytes, const std::vector>* rank) { - err.clear(); - if (base_ == nullptr) { err = "FileExpertSource: open the mapped experts before pinning a complement"; return false; } - if (complement_ready_) { err = "FileExpertSource: the cache complement is already pinned"; return false; } - if (!cache.valid()) { err = "FileExpertSource: the GPU expert cache is not open"; return false; } - if (cache.fills() != cache.resident()) { - err = "FileExpertSource: the GPU expert cache is not fully filled"; - return false; - } - const cudaError_t sync = cudaDeviceSynchronize(); - if (sync != cudaSuccess) { - err = std::string("FileExpertSource: GPU expert cache is not ready: ") + cudaGetErrorString(sync); - (void) cudaGetLastError(); - return false; - } - - // The GPU cache's experts, and the bytes each slot's expert takes here (for the lend region below). - const int64_t n_slots = cache.slots(); - std::vector> primary_gpu_pairs; - std::vector pair_slot; - std::vector slot_bytes((size_t) std::max(n_slots, 0), 0); - primary_gpu_pairs.reserve((size_t) cache.resident()); - pair_slot.reserve((size_t) cache.resident()); - for (int64_t layer = 0; layer < n_layers_; ++layer) { - for (int64_t expert = 0; expert < n_expert_; ++expert) { - const int32_t slot = cache.slot_of(layer, expert); - if (slot == kNotResident) continue; - primary_gpu_pairs.emplace_back((int32_t) layer, (int32_t) expert); - pair_slot.push_back(slot); - if (slot >= 0 && slot < n_slots) slot_bytes[(size_t) slot] = layer_blob_bytes_[(size_t) layer]; - } - } - std::vector offsets; - uint64_t bytes = 0; - if (!detail::make_cache_complement_plan(n_layers_, n_expert_, layer_blob_bytes_, primary_gpu_pairs, - additional_gpu_pairs, offsets, bytes, err)) return false; -#if defined(_WIN32) - // #467: the GPU cache's pre-fill touched its experts through the mapping (~19 GiB on a 24 GB card), and Windows - // counts those file pages in this process's working set, not as available: a 32 GB PC read 0.44 GiB here - // (20.7 GiB before the start). Trimmed, they move to the standby list (still cached, counted as available). - // Resident mode only: nothing else calls this function. Locked/pinned pages stay; the rest fault back softly. - { - uint64_t before = 0, after = 0; - const bool read_before = available_memory_bytes(before); - (void) SetProcessWorkingSetSize(GetCurrentProcess(), (SIZE_T) -1, (SIZE_T) -1); - if (read_before && available_memory_bytes(after)) - std::fprintf(stderr, "FileExpertSource: available RAM %.2f GiB, %.2f GiB after the mapped experts left the " - "process working set (#467)\n", - (double) before / 1073741824.0, (double) after / 1073741824.0); - } -#endif - const bool what_fits = budget_bytes == kResidentWhatFits; // #467: the soft mode's second try - uint64_t budget_physical = 0; // #403: the RAM reading a budget was sized from (0: no budget) - if (budget_bytes > 0) { - // CS-T: a RAM budget. The complement's experts in `rank` order (the expert profile, hottest first) while - // they fit, the rest left on the mapped files; clamped to what the RAM has room for. - uint64_t physical = 0; - if (!available_memory_bytes(physical)) { - err = "FileExpertSource: cannot determine available RAM for --resident-budget-gib"; - return false; - } - budget_physical = physical; - const uint64_t room = physical > headroom_bytes ? physical - headroom_bytes : 0; - if (budget_bytes > room) { - // #403: 256 MiB under the room, so the engine's own allocations after this reading still leave the - // headroom (a budget clamped to exactly the room failed the safety check below on a reading a few MB - // lower). An unclamped budget is unchanged. - const uint64_t margin = 256ull << 20; - const uint64_t clamped = room > margin ? room - margin : 0; - if (what_fits) - std::fprintf(stderr, "FileExpertSource: RAM room for the complement: %.2f GiB (%.2f GiB available " - "minus %.0f GiB headroom and a 0.25 GiB margin)\n", - (double) clamped / 1073741824.0, (double) physical / 1073741824.0, - (double) headroom_bytes / 1073741824.0); - else - std::fprintf(stderr, "FileExpertSource: --resident-budget-gib %.2f is more than the RAM has room for " - "(%.2f GiB available minus %.0f GiB headroom and a 0.25 GiB margin): %.2f GiB\n", - (double) budget_bytes / 1073741824.0, (double) physical / 1073741824.0, - (double) headroom_bytes / 1073741824.0, (double) clamped / 1073741824.0); - budget_bytes = clamped; - } - std::vector ranked(offsets.size(), kNoComplement); - uint64_t at = 0; - int64_t held = 0; - if (rank != nullptr) - for (const auto& pr : *rank) { - if (pr.first < 0 || pr.second < 0 || pr.first >= n_layers_ || pr.second >= n_expert_) continue; - const size_t i = (size_t) pr.first * (size_t) n_expert_ + (size_t) pr.second; - if (offsets[i] == kNoComplement || ranked[i] != kNoComplement) continue; // on a GPU, or twice - const uint64_t b = layer_blob_bytes_[(size_t) pr.first]; - if (b > budget_bytes - at) continue; - ranked[i] = at; - at += b; - ++held; - } - if (what_fits && held == 0) { // #467: nothing to keep - the caller's plain mmap fallback, not an empty copy - err = "FileExpertSource: the RAM has no room for any expert of the complement"; - return false; - } - std::fprintf(stderr, "FileExpertSource: RAM budget %.2f GiB: %lld of the %.2f GiB of experts the GPU cache does " - "not hold, by profile rank; the rest are read from the files\n", - (double) budget_bytes / 1073741824.0, (long long) held, (double) bytes / 1073741824.0); - offsets.swap(ranked); - bytes = at; - lend_from_slot = -1; - } - - const bool lend = lend_from_slot >= 0 && lend_from_slot < n_slots && additional_gpu_pairs.empty(); - uint64_t budget = std::numeric_limits::max(); - if (bytes > 0 || lend) { - // #403: with a budget, the reading it was sized from - a second reading a few MB lower (the engine's own - // allocations, the file cache) failed a budget the first one had clamped. (A budget turns `lend` off.) - uint64_t physical = budget_physical; - if (physical == 0 && !available_memory_bytes(physical)) { - err = "FileExpertSource: cannot determine available RAM for the resident-memory safety check"; - return false; - } - budget = physical > headroom_bytes ? physical - headroom_bytes : 0; - if (bytes > budget) { - char message[320]; - std::snprintf(message, sizeof message, - "FileExpertSource: resident complement %.2f GiB exceeds available RAM (%.2f GiB) minus the " - "%.0f GiB safety headroom", - (double) bytes / 1073741824.0, (double) physical / 1073741824.0, - (double) headroom_bytes / 1073741824.0); - err = message; - return false; - } - } - // The prompt path's lend region: its slots' experts are streamed from here during a prompt and copied back into - // their slots after it, so the ones that fit are kept here too (from the last slot down: a short prompt lends - // only the last few). The rest keep the mapped-file fallback. - int64_t keep_from = n_slots; - if (lend) { - keep_from = detail::choose_resident_keep_from(slot_bytes, bytes, budget, lend_from_slot); - if (keep_from < 0) keep_from = n_slots; - if (keep_from < n_slots) { - std::vector> core; - core.reserve(primary_gpu_pairs.size()); - for (size_t i = 0; i < primary_gpu_pairs.size(); ++i) - if (pair_slot[i] < keep_from) core.push_back(primary_gpu_pairs[i]); - if (!detail::make_cache_complement_plan(n_layers_, n_expert_, layer_blob_bytes_, core, - additional_gpu_pairs, offsets, bytes, err)) return false; - } - } - - void* arena = nullptr; - const uint8_t* host = nullptr; - const uint8_t* device = nullptr; - bool pinned_ok = false; - uint64_t locked = 0; - uint64_t partial_pin = 0; ///< CS-T: a registered prefix of a locked arena - uint64_t lock_off = 0; ///< where the working-set lock starts (after the registered prefix) - std::string note; - auto release = [&]() { - if (arena == nullptr) return; - if (pinned_ok) (void) cudaFreeHost(arena); - else { - if (partial_pin > 0) (void) cudaHostUnregister(arena); - if (locked > 0) strata::platform::unlock_resident((uint8_t*) arena + lock_off, locked); - std::free(arena); - } - arena = nullptr; - }; - if (bytes > 0) { - std::fprintf(stderr, "FileExpertSource: allocating %.2f GiB %s cache complement\n", - (double) bytes / 1073741824.0, pin ? "page-locked" : "pageable resident"); - std::fflush(stderr); - if (pin) { - const cudaError_t allocated = cudaHostAlloc(&arena, (size_t) bytes, - cudaHostAllocMapped | cudaHostAllocPortable); - if (allocated == cudaSuccess) { - void* alias = nullptr; - const cudaError_t aliased = cudaHostGetDevicePointer(&alias, arena, 0); - if (aliased == cudaSuccess && alias != nullptr) { - device = (const uint8_t*) alias; - pinned_ok = true; - note = "page-locked and mapped"; - } else { - note = std::string("no device alias (") + cudaGetErrorString(aliased) + ")"; - (void) cudaGetLastError(); - (void) cudaFreeHost(arena); - arena = nullptr; - } - } else { - // Refused (the driver's page-locked limit): the same bytes in ordinary memory, locked in the working - // set instead, as the arena does - resident either way, only copied by the CPU instead of by DMA. - note = std::string("page-locking refused (") + cudaGetErrorString(allocated) + ")"; - (void) cudaGetLastError(); - arena = nullptr; - } - } - if (arena == nullptr) { - arena = std::malloc((size_t) bytes); - if (arena == nullptr) { - err = "FileExpertSource: pageable resident complement allocation failed"; - return false; - } - if (pin) { - // CS-T, a RAM budget: its bytes are in profile order, hottest first, so the driver is asked to - // register the largest prefix it takes (from the cap down in 2 GiB steps). Those experts can be - // read by the GPU over PCIe (--pcie-frac) and copied by DMA; only the rest is locked in the working - // set (the registered prefix is page-locked by the driver already - locking it twice made the next - // device allocation fail). - // opt-in (STRATA_PARTIAL_PIN=1): on the RTX 5070 PC the GPU's PCIe share of the misses measured no - // faster than the CPU computing them (7.30 / 7.44 tok/s with 24 / 16 GiB registered against 7.05-7.74 - // unpinned at a 40 GiB budget), and registering adds startup time and driver memory pressure - static const bool partial_on = [] { - const char* v = std::getenv("STRATA_PARTIAL_PIN"); - return v != nullptr && std::atoi(v) != 0; - }(); - // at most STRATA_PARTIAL_PIN_GIB (default 24): registering 30 GiB of a 40 GiB arena left the driver - // unable to page-lock the prompt path's small buffers afterwards (RTX 5070, WDDM) - static const uint64_t pin_cap = [] { - const char* v = std::getenv("STRATA_PARTIAL_PIN_GIB"); - return (uint64_t) ((v != nullptr && std::atof(v) > 0 ? std::atof(v) : 24.0) * 1073741824.0); - }(); - if (budget_bytes > 0 && partial_on) { - const uint64_t step = 2ull << 30; - for (uint64_t want = std::min(bytes, pin_cap); want >= step; want = want > step ? want - step : 0) { - // cut at an expert boundary: a blob that started inside the registered range and ran past it - // would be taken as page-locked by a cudaMemcpyAsync and refused ("adaptive refill failed") - uint64_t w = want; - for (size_t i = 0; i < offsets.size(); ++i) { - if (offsets[i] == kNoComplement) continue; - const uint64_t b = layer_blob_bytes_[i / (size_t) n_expert_]; - if (offsets[i] < want && offsets[i] + b > want) { w = offsets[i]; break; } - } - if (w == 0) break; - if (cudaHostRegister(arena, (size_t) w, cudaHostRegisterMapped | cudaHostRegisterPortable) == - cudaSuccess) { - void* alias = nullptr; - if (cudaHostGetDevicePointer(&alias, arena, 0) == cudaSuccess && alias != nullptr) { - device = (const uint8_t*) alias; - partial_pin = w; - } else { - (void) cudaGetLastError(); - (void) cudaHostUnregister(arena); - } - break; - } - (void) cudaGetLastError(); - if (want <= step) break; - } - char msg[160]; - std::snprintf(msg, sizeof msg, "%.2f GiB of it registered for the GPU (the hottest)", - (double) partial_pin / 1073741824.0); - note += std::string("; ") + msg; - } - lock_off = partial_pin; - const strata::platform::LockResult lr = - strata::platform::lock_resident((uint8_t*) arena + lock_off, bytes - lock_off); - locked = lr.locked_bytes; - note += (note.empty() ? "" : "; ") + lr.note; - } - } - host = (const uint8_t*) arena; - } - - // Copied layer by layer on a few threads: the page faults of the mapped file are the cost, and they overlap. -#if !defined(_WIN32) - const long page_size = sysconf(_SC_PAGESIZE); - if (page_size <= 0) { - err = "FileExpertSource: cannot determine page size for mapped-page release"; - release(); - return false; - } -#endif - std::atomic next_layer{0}, layers_done{0}; - std::atomic copied{0}; - std::atomic failed{false}; - std::mutex fail_mu; - std::string fail_msg; - auto fail = [&](const std::string& m) { - std::lock_guard lock(fail_mu); - if (fail_msg.empty()) fail_msg = m; - failed.store(true); - }; - auto worker = [&]() { - for (;;) { - const int64_t layer = next_layer.fetch_add(1); - if (layer >= n_layers_ || failed.load()) return; - const uint64_t blob_bytes = layer_blob_bytes_[(size_t) layer]; - std::vector batch; // #286, unbuffered: 32 blobs' reads in flight at once, merged where near - auto flush = [&]() { - if (batch.empty()) return true; - bool ok = read_direct(batch.data(), batch.size()); - for (size_t i = 0; !ok && i < batch.size(); ++i) - if (!copy_from_files(batch[i].layer, batch[i].e, batch[i].dst)) return false; - copied.fetch_add(blob_bytes * (uint64_t) batch.size()); - batch.clear(); - return true; - }; - for (int64_t expert = 0; expert < n_expert_; ++expert) { - const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; - const uint64_t offset = offsets[index]; - if (offset == kNoComplement) continue; - if (offset > bytes || blob_bytes > bytes - offset) { - fail("FileExpertSource: invalid blob bounds while building the cache complement"); - return; - } - uint8_t* dst = (uint8_t*) host + (size_t) offset; - if (!direct_.empty()) { - batch.push_back({0, layer, expert, dst}); - if (batch.size() == 32 && !flush()) { - fail("FileExpertSource: an expert could not be read while building the cache complement"); - return; - } - continue; - } - if (!copy_from_files(layer, expert, dst)) { - fail("FileExpertSource: invalid blob bounds while building the cache complement"); - return; - } - copied.fetch_add(blob_bytes); - } - if (!flush()) { - fail("FileExpertSource: an expert could not be read while building the cache complement"); - return; - } -#if !defined(_WIN32) - if (role_ptr_.empty()) { // experts.bin; the GGUF in place leaves its pages to the OS - const uint64_t layer_offset = layer_offsets_[(size_t) layer]; - const uint64_t layer_bytes = blob_bytes * (uint64_t) n_expert_; - const uint64_t layer_end = layer_offset + layer_bytes; - const uint64_t page = (uint64_t) page_size; - const uint64_t advice_start = layer_offset - layer_offset % page; - const uint64_t end_remainder = layer_end % page; - const uint64_t extra = end_remainder == 0 ? 0 : page - end_remainder; - const uint64_t advice_end = extra > mapped_bytes_ - layer_end ? mapped_bytes_ : layer_end + extra; - if (advice_end > advice_start && - madvise((void*) (base_ + (size_t) advice_start), (size_t) (advice_end - advice_start), MADV_DONTNEED) != 0) { - fail("FileExpertSource: madvise could not release mapped expert layer " + std::to_string(layer)); - return; - } - if (posix_fadvise(fd_, (off_t) layer_offset, (off_t) layer_bytes, POSIX_FADV_DONTNEED) != 0) { - fail("FileExpertSource: posix_fadvise could not release expert layer " + std::to_string(layer)); - return; - } - } -#endif - const int64_t done = layers_done.fetch_add(1) + 1; - if (done % 8 == 0 || done == n_layers_) - std::fprintf(stderr, "FileExpertSource: copied cache complement through layer %lld/%lld (%.2f GiB)\n", - (long long) done, (long long) n_layers_, (double) copied.load() / 1073741824.0); - } - }; - { - const int threads = (int) std::max(1, std::min(6, n_layers_)); - std::vector pool; - for (int i = 1; i < threads; ++i) pool.emplace_back(worker); - worker(); - for (auto& t : pool) t.join(); - } - std::fflush(stderr); - if (failed.load()) { - err = fail_msg; - release(); - return false; - } -#if defined(_WIN32) - // The mapped pages this process touched (the GPU cache's fill and this copy) leave its working set for the - // standby list: VirtualUnlock on pages that are not locked does exactly that (it then reports ERROR_NOT_LOCKED). - if (maps_.empty()) (void) VirtualUnlock((LPVOID) base_, (SIZE_T) mapped_bytes_); - for (const Map& m : maps_) (void) VirtualUnlock((LPVOID) m.base, (SIZE_T) m.bytes); -#endif - - complement_arena_ = arena; - complement_host_ = host; - complement_device_ = device; - complement_bytes_ = bytes; - complement_offsets_ = std::move(offsets); - complement_pinned_ = (pinned_ok || partial_pin > 0) && bytes > 0; - complement_pin_limit_ = pinned_ok ? bytes : partial_pin; - complement_partial_ = !pinned_ok && partial_pin > 0; - complement_locked_ = locked; - 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, - note.empty() ? "" : "; ", note.c_str()); - if (lend) - std::fprintf(stderr, "FileExpertSource: %lld of the prompt path's %lld lendable slots keep their experts in RAM " - "too%s\n", (long long) complement_lent_slots_, (long long) (n_slots - lend_from_slot), - complement_lent_slots_ < n_slots - lend_from_slot - ? " (the others are read from the file when lent: not enough RAM for them)" : ""); - if (!additional_gpu_pairs.empty()) { - std::fprintf(stderr, "FileExpertSource: %zu verified additional-GPU experts remain on the mmap fallback\n", - additional_gpu_pairs.size()); - } - std::fflush(stderr); - return true; -} - -bool FileExpertSource::has_resident(int64_t layer, int64_t expert) const { - if (!complement_ready_ || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false; - const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; - return index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement; -} - -bool FileExpertSource::reserve_exchanges(int64_t n, std::string& err) { - err.clear(); - if (n <= xstage_cap_) return true; - if (!staged_.empty()) { err = "FileExpertSource: exchange buffers are in use"; return false; } - uint64_t blob = 0; - for (const uint64_t b : layer_blob_bytes_) blob = std::max(blob, b); - if (blob == 0 || n <= 0) { err = "FileExpertSource: no expert geometry for the exchange buffers"; return false; } - if (xstage_ != nullptr) { - if (xstage_pinned_) (void) cudaFreeHost(xstage_); - else std::free(xstage_); - xstage_ = nullptr; - xstage_cap_ = 0; - } - const size_t total = (size_t) n * (size_t) blob; - void* p = nullptr; - if (cudaHostAlloc(&p, total, cudaHostAllocDefault) == cudaSuccess && p != nullptr) { - xstage_pinned_ = true; - } else { - (void) cudaGetLastError(); - p = std::malloc(total); - xstage_pinned_ = false; - if (p == nullptr) { err = "FileExpertSource: cannot allocate the exchange buffers"; return false; } - } - xstage_ = (uint8_t*) p; - xstage_cap_ = n; - xstage_blob_ = blob; - return true; -} - -uint8_t* FileExpertSource::exchange_buffer(int64_t q) const { - if (xstage_ == nullptr || q < 0 || q >= xstage_cap_) return nullptr; - return xstage_ + (size_t) q * (size_t) xstage_blob_; -} - -bool FileExpertSource::stage_exchange(int64_t layer, int64_t in, int64_t out, int64_t q) { - if (!has_resident(layer, in) || has_resident(layer, out) || exchange_buffer(q) == nullptr) return false; - const size_t i_in = (size_t) layer * (size_t) n_expert_ + (size_t) in; - const size_t i_out = (size_t) layer * (size_t) n_expert_ + (size_t) out; - if (override_.empty()) override_.assign((size_t) blobs_, nullptr); - if (override_[i_out] != nullptr) return false; - for (const Exchange& x : staged_) - if (x.in == i_in || x.q == q) return false; - override_[i_out] = exchange_buffer(q); - staged_.push_back({i_in, i_out, q, layer_blob_bytes_[(size_t) layer]}); - return true; -} - -int64_t FileExpertSource::commit_exchanges() { - int64_t n = 0; - for (const Exchange& x : staged_) { - const uint8_t* src = override_[x.out]; - const uint64_t at = complement_offsets_[x.in]; - if (src != nullptr && at != kNoComplement && at <= complement_bytes_ && x.bytes <= complement_bytes_ - at && - complement_host_ != nullptr) { - std::memcpy((uint8_t*) complement_host_ + (size_t) at, src, (size_t) x.bytes); - if (detail::exchange_cache_complement(complement_offsets_, x.in, x.out)) ++n; - } - override_[x.out] = nullptr; - } - staged_.clear(); - exchanges_ += n; - return n; -} - -const uint8_t* FileExpertSource::blob(int64_t layer, int64_t expert) { - if (base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return nullptr; - const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; - const uint8_t* result = nullptr; - bool from_files = true; - if (complement_ready_) { - result = detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr); - if (result != nullptr) { - ram_reads_.fetch_add(1, std::memory_order_relaxed); - from_files = false; - } else if (!override_.empty() && override_[index] != nullptr) { - result = override_[index]; - from_files = false; - } - } - if (from_files) { - if (staged()) { - result = staged_blob(layer, expert); // counts its bytes - } else { - result = mapped_blob(layer, expert); - if (result != nullptr) - file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed); - } - if (complement_ready_ && result != nullptr) file_reads_.fetch_add(1, std::memory_order_relaxed); - } - if (result != nullptr) ++reads_; - 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; - const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; - if (index >= complement_offsets_.size() || complement_offsets_[index] == kNoComplement) return false; - // a partial pin (CS-T): only the registered prefix - return !complement_partial_ || - complement_offsets_[index] + layer_blob_bytes_[(size_t) layer] <= complement_pin_limit_; -} - -const uint8_t* FileExpertSource::device_alias(int64_t layer, int64_t expert) const { - if (!pinned(layer, expert) || complement_device_ == nullptr) return nullptr; - const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; - return complement_device_ + (size_t) complement_offsets_[index]; -} - -bool FileExpertSource::pcie_layer(int64_t layer) const { - if (complement_ready_ && complement_pinned_ && complement_device_ != nullptr) - return layer >= 0 && layer < n_layers_; - return device_alias(layer, 0) != nullptr; -} - -// ================================ THE ADAPTER ================================ - -void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, const float* weights, int64_t n_embd, - int64_t k, float* out) { - (void) weights; // clause 2: `moe_combine` applies it on the device. Not an oversight. - ExpertDispatch& d = *(ExpertDispatch*) user; - if (d.failed) return; // a previous layer already failed; do not make it worse - - using namespace strata::kernels::cpu; - // Clause 3: the blob's internal offsets are compile-time constants, so a mismatched geometry does not - // produce a wrong answer - it produces a walk off the end of the blob into the next expert's bytes, which - // is finite and plausible. Refuse, name the number, and let the driver report it. - if (n_embd != H) { - d.failed = true; - d.fail = "the expert kernel is compiled for a 2560-wide activation"; - d.fail_layer = d.layers; - return; - } - if (expert_layout().native) { - // plan v0.3 P6: a native pack runs its experts in verify windows only (the driver guarantees it) - d.failed = true; - d.fail = "the single-token expert path does not take a native (IQ) pack"; - d.fail_layer = d.layers; - return; - } - if (k > (int64_t) d.jobs.size()) d.jobs.resize((size_t) k); - - d.src->begin_layer(d.layers, ids, k); - - // Clause 1: rebuilt from `x_f` on EVERY call. `x_f` is mapped pinned memory whose address never changes, - // so anything cached against it would be layer 0's activation reused 48 times. - act_quant_q8_1(x_f, H, d.act); - - // ---- R4.2c: THE POOL'S HALF OF THE SPLIT. **IT DOES NOT DECIDE ANYTHING - `Launch` ALREADY DID.** - // - // The decision has to be made on THIS layer's ids, and `Launch` is the only callback that runs before the - // pool while the ids are known (the doorbell publishes them when the ring fires). So `expert_hit_run` - // decides, and this consumes `d.is_hit`. The first version decided here instead, which meant `Launch` - // computed the PREVIOUS layer's experts into this layer's rows: C1 went from mean KL 9.69e-02 to 1.03e+00. - // - // `njobs` indexes the JOB ARRAY and `i` indexes the OUTPUT - they are the same only when nothing is a hit. - const bool graph_hits = d.host_res != nullptr; - const bool use_hits = graph_hits || (d.hits_ready() && d.decided); - int64_t njobs = 0; - - if (d.remote_count > 0) { - int32_t kind[32]; - if (k > 32) { - d.failed = true; d.fail = "remote experts: routing width exceeds 32"; return; - } - for (int64_t i = 0; i < k; ++i) - kind[i] = use_hits && ids[i] >= 0 && ids[i] < d.n_expert && (graph_hits - ? d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) ids[i]] >= 0 - : d.is_hit[(size_t) i] != 0) ? 0 : -1; - static thread_local std::string remote_error; - for (int r = 0; r < d.remote_count; ++r) - if (!d.remote[r]->begin(d.layers, x_f, ids, 1, k, kind, d.host_res, remote_error)) { - d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return; - } - } - - for (int64_t i = 0; i < k; ++i) { - const int64_t e = ids[i]; - if (e < 0 || e >= d.n_expert) { - d.failed = true; - d.fail = "a routed expert id is out of range"; - d.fail_layer = d.layers; - d.fail_expert = e; - return; - } - const uint8_t* b = d.src->blob(d.layers, e); - if (b == nullptr) { - // The one failure the loop cannot see. Leaving `out` at its previous contents would feed the NEXT - // layer a stale expert vector, which `moe_combine` would weight and add - the token would still be - // finite and would still be wrong, 48 layers deep. - d.failed = true; - d.fail = "the expert source could not produce a blob"; - d.fail_layer = d.layers; - d.fail_expert = e; - ++d.missing; - return; - } - // A hit's row was zeroed by `Launch` and belongs to the GPU; the pool must not touch it. - if (use_hits && (graph_hits ? d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] >= 0 - : d.is_hit[(size_t) i] != 0)) { - if (graph_hits) ++d.cache_hits; - // The GPU owns this row and `hit_out` is zeroed, so the CPU's contribution is zero - but - // `y_miss` is a REUSED pinned buffer, so the row must be written, not merely skipped. - std::memset(out + (size_t) i * (size_t) n_embd, 0, (size_t) n_embd * sizeof(float)); - continue; - } - if (graph_hits) ++d.cache_refused; // token graph: a miss (nothing is admitted during a token) - - bool remote_owns = false; - for (int r = 0; r < d.remote_count; ++r) remote_owns |= d.remote[r]->owns(i); - if (remote_owns) { - std::memset(out + (size_t) i * (size_t) n_embd, 0, (size_t) n_embd * sizeof(float)); - continue; - } - - // `njobs` indexes the JOB ARRAY and `i` indexes the OUTPUT - they are the same only when nothing is a - // hit, and using one for the other is how a hit's row would get two experts summed into it. - ExpertJob& j = d.jobs[(size_t) njobs++]; - j.blob = b; - j.act = &d.act; // SHARED across the batch: one conversion serves all ten experts - j.out = out + (size_t) i * (size_t) n_embd; - j.weight = 1.0f; // clause 2: a diagnostic field, NOT the router weight - j.slot = (int) i; - } - - // Plan v0.3 P4: rows of every expert across all threads (bitwise the same as `run`). - if (d.split_rows) d.pool->run_split(d.jobs.data(), (int) njobs); - else d.pool->run(d.jobs.data(), (int) njobs); - if (d.remote_count > 0) { - static thread_local std::string remote_error; - for (int r = 0; r < d.remote_count; ++r) - if (!d.remote[r]->finish(out, remote_error)) { - d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return; - } - } - ++d.layers; - d.experts += k; -} - -namespace { -// the verify window's per-entry tables in `expert_pool_dispatch_multi` (`kind`, `distinct`, `first_of`) -// are fixed arrays of this many entries: MAXT tokens of the model's 10 routed experts must fit, and a larger k is -// refused at run time rather than written past them. -constexpr int64_t kMaxWindowEntries = 128; -static_assert(strata::kernels::cpu::MAXT * 10 <= kMaxWindowEntries, "a verify window's entries overflow the tables"); -} // namespace - -void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k, - float* out) { - using namespace strata::kernels::cpu; - if (d.failed) return; - if (n_tok < 1 || n_tok > MAXT) { - d.failed = true; - d.fail = "a verify window has more tokens than the multi-token expert kernel takes"; - d.fail_layer = d.layers; - return; - } - if (d.lookahead != nullptr) d.lookahead->submit(d.layers, x_f, n_tok, d.host_res); // CS-T: warm layer + 1 - if (k < 1 || n_tok * k > kMaxWindowEntries) { - d.failed = true; - d.fail = "a verify window routes more entries than the expert pool's window tables hold"; - d.fail_layer = d.layers; - return; - } - if ((int64_t) d.act_multi.size() < n_tok) d.act_multi.resize((size_t) MAXT); - 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; - auto pt = [&](const char* what, long long a = -1) { - if (ptrace) { std::fprintf(stderr, "pool trace: layer %lld %s %lld\n", (long long) d.layers, what, a); std::fflush(stderr); } - }; - const auto c0 = std::chrono::steady_clock::now(); - pt("begin"); - d.src->begin_layer(d.layers, ids, n_tok * k); - pt("begun"); - if (!d.usage.empty()) - for (int64_t i = 0; i < n_tok * k; ++i) - if (ids[i] >= 0 && ids[i] < d.n_expert) d.usage[(size_t) d.layers * (size_t) d.n_expert + (size_t) ids[i]] += 1.0f; - // ---- plan v0.3 P6: the GPU's share, decided and published FIRST so the GPU starts while the CPU works. - // Distinct experts in routing order; resident ones and the last pcie_num/256 of the missed ones go to the GPU. - const int64_t n = n_tok * k; - int32_t kind[kMaxWindowEntries]; // per entry: -1 CPU, 0 VRAM, 1 PCIe - if (d.plan != nullptr && n <= kMaxWindowEntries && n <= d.plan->cap) { - int64_t distinct[kMaxWindowEntries], first_of[kMaxWindowEntries]; - int nd = 0, nmiss = 0; - for (int64_t i = 0; i < n; ++i) { - first_of[i] = i; - for (int64_t j = 0; j < i; ++j) - if (ids[j] == ids[i]) { first_of[i] = first_of[j]; break; } - if (first_of[i] == i) { - distinct[nd++] = i; - const int32_t e = ids[i]; - if (e >= 0 && e < d.n_expert && d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] < 0 && - !(d.peer != nullptr && d.peer->has(d.layers, e))) ++nmiss; - } - } - const bool pcie_ok = d.pcie_num > 0 && d.src->pcie_layer(d.layers); - const int m = pcie_ok ? (nmiss * d.pcie_num) >> 8 : 0; - int miss_rank = 0, groups = 0, entries = 0, fetches = 0; - GpuPlanSink& P = *d.plan; - const uint8_t* dma_src[64]; - int64_t pcie_i0[64]; - for (int q = 0; q < nd; ++q) { - const int64_t i0 = distinct[q]; - const int32_t e = ids[i0]; - int kd = -1; - unsigned long long ptr = 0; - if (e >= 0 && e < d.n_expert) { - const int32_t slot = d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e]; - if (slot >= 0) { - kd = 0; - ptr = (unsigned long long) (d.cache_base + (d.cache_slot_off ? (size_t) d.cache_slot_off[slot] - : (size_t) slot * (size_t) d.cache_blob)); - } else if (d.peer != nullptr && d.peer->has(d.layers, e)) { - kd = 2; // multi-GPU: the second GPU computes it - } else { - if (miss_rank >= nmiss - m && fetches < P.staging_cap && fetches < 64) { - const uint8_t* src = d.src->pinned(d.layers, e) ? d.src->blob(d.layers, e) : nullptr; - if (src != nullptr) { - kd = 1; - dma_src[fetches] = src; - pcie_i0[fetches] = i0; - ++fetches; - } - } - ++miss_rank; - } - } - for (int64_t i = i0; i < n; ++i) - if (first_of[i] == i0) kind[i] = kd; - if (kd != 0) continue; // the VRAM groups first; the PCIe groups below - P.ptr[groups] = ptr; - P.start[groups] = entries; - for (int64_t i = i0; i < n; ++i) - if (first_of[i] == i0) { - P.dst[entries] = (int32_t) i; - P.tok[entries] = (int32_t) (i / k); - ++entries; - } - ++groups; - } - P.start[groups] = entries; - const uint64_t bb = lay.blob_bytes(d.layers); - for (int q = 0; q < fetches; ++q) { // the PCIe groups: staging slot q, entries after the VRAM ones - const int64_t i0 = pcie_i0[q]; - P.ptr2[q] = P.pcie_mode != 0 ? (unsigned long long) d.src->device_alias(d.layers, ids[i0]) - : P.staging + (unsigned long long) q * (unsigned long long) bb; - P.start2[q] = entries; - for (int64_t i = i0; i < n; ++i) - if (first_of[i] == i0) { - P.dst[entries] = (int32_t) i; - P.tok[entries] = (int32_t) (i / k); - ++entries; - } - ++d.pcie_experts; - } - P.start2[fetches] = entries; - P.counts[0] = groups; - P.counts[1] = entries; - P.counts[2] = fetches; - std::atomic_thread_fence(std::memory_order_seq_cst); - pt("publish", fetches); - if (P.publish) P.publish(P.ctx); - pt("fetch", fetches); - if (P.fetch) P.fetch(P.ctx, dma_src, P.pcie_mode != 0 ? 0 : fetches, (size_t) bb); // the copy engine, beside the CPU's work - } else { - for (int64_t i = 0; i < n; ++i) { - const int32_t e = ids[i]; - kind[i] = (e >= 0 && e < d.n_expert && d.host_res != nullptr && - d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] >= 0) ? 0 - : (e >= 0 && e < d.n_expert && d.peer != nullptr && d.peer->has(d.layers, e)) ? 2 : -1; - } - } - if (d.peer != nullptr) { // multi-GPU: start the second GPU's share before the CPU's own work - std::string perr; - if (!d.peer->launch(d.layers, x_f, ids, n_tok, k, kind, perr, out)) { - std::fprintf(stderr, "strata: %s (layer %lld)\n", perr.c_str(), (long long) d.layers); - d.failed = true; - d.fail = "the peer GPU's experts could not be launched"; - d.fail_layer = d.layers; - return; - } - } - if (d.remote_count > 0) { - static thread_local std::string remote_error; - for (int r = 0; r < d.remote_count; ++r) { - if (!d.remote[r]->begin(d.layers, x_f, ids, n_tok, k, kind, d.host_res, remote_error)) { - d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return; - } - for (int64_t i = 0; i < n; ++i) if (d.remote[r]->owns(i)) kind[i] = 2; - } - } - static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }(); - // the GPU's copy_rows_from_mapped zeroes the rows it computed itself (dec_batch); STRATA_VERIFY_DEVICE_PLAN's - // copy_or_zero_from_mapped copies every row, so there the host still zeroes them - static const bool device_plan = [] { const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN"); return v != nullptr && std::atoi(v) != 0; }(); - const bool gpu_zeroes_hits = (d.plan != nullptr && n <= kMaxWindowEntries && n <= d.plan->cap && dec_batch && !device_plan); - bool any_cpu = false; - for (int64_t i = 0; i < n; ++i) - if (kind[i] < 0) { any_cpu = true; break; } - const auto c1 = std::chrono::steady_clock::now(); - if (any_cpu) { - // #578 --remote-expert-opt: a token whose experts all run on a GPU (CUDA0 or a helper) needs no CPU activation - const bool ep = d.remote_count > 0 && d.remote[0]->optimized_decode(); - for (int64_t t = 0; t < n_tok; ++t) { - if (ep && std::all_of(kind + t * k, kind + (t + 1) * k, [](int32_t v) { return v >= 0; })) continue; - if (native && strata::kernels::cpu::q2_native_kernels(lay.fmt[(size_t) d.layers].gu_type)) // a native Q2_0 pack: the Q2_0 kernels' activations - act_quant_any(x_f + (size_t) t * W, (int) W, d.act_multi[(size_t) t]); - else if (native) - native_quant_act(lay.fmt[(size_t) d.layers], x_f + (size_t) t * W, d.nact_multi.data() + (size_t) t * kNativeActBytes); - else - 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(); - if (any_cpu) { // CS-T: the experts the CPU computes, fetched together (the GGUF in place reads them on several threads) - static thread_local std::vector miss; - miss.clear(); - for (int64_t i = 0; i < n_tok * k; ++i) - if (kind[i] < 0 && ids[i] >= 0 && ids[i] < d.n_expert && - std::find(miss.begin(), miss.end(), (int64_t) ids[i]) == miss.end()) - miss.push_back(ids[i]); - d.src->prefetch(d.layers, miss.data(), (int64_t) miss.size()); - } - int njobs = 0; - for (int64_t t = 0; t < n_tok; ++t) - for (int64_t j = 0; j < k; ++j) { - const int64_t i = t * k + j; - const int64_t e = ids[i]; - float* row = out + (size_t) i * W; - if (e < 0 || e >= d.n_expert) { - d.failed = true; - d.fail = "a routed expert id is out of range"; - d.fail_layer = d.layers; - d.fail_expert = e; - return; - } - if (kind[i] >= 0) { // CUDA0, PCIe, or a remote/peer result staged into this row below - if (kind[i] == 0) ++d.cache_hits; - else ++d.offload_entries; // #588: PCIe or another GPU - if (kind[i] == 2 && d.peer != nullptr) ++d.peer_entries; - // multi-GPU: a direct peer launch is writing this row right now - zeroing it would race it; - // dec_batch: copy_rows_from_mapped_kernel already zeroes kind 0/1 rows on the GPU - if (!((kind[i] == 2 && d.peer != nullptr && d.peer->launched_direct()) || - (gpu_zeroes_hits && (kind[i] == 0 || kind[i] == 1)))) - std::memset(row, 0, (size_t) W * sizeof(float)); - continue; - } - ++d.cache_refused; - int16_t& jo = d.job_of[(size_t) e]; - if (jo < 0) { - const uint8_t* b = d.src->blob(d.layers, e); - if (b == nullptr) { - d.failed = true; - d.fail = "the expert source could not produce a blob"; - d.fail_layer = d.layers; - d.fail_expert = e; - ++d.missing; - return; - } - jo = (int16_t) njobs++; - ExpertJobMulti& nj = d.jobs_multi[(size_t) jo]; - nj.blob = b; - nj.nt = 0; - } - ExpertJobMulti& jb = d.jobs_multi[(size_t) jo]; - jb.act[jb.nt] = &d.act_multi[(size_t) t]; - jb.nact[jb.nt] = native ? d.nact_multi.data() + (size_t) t * kNativeActBytes : nullptr; - jb.out[jb.nt] = row; - ++jb.nt; - ++d.multi_entries; - } - const auto c3 = std::chrono::steady_clock::now(); - pt("run", njobs); - if (njobs > 0) { - if (native) d.pool->run_split_multi_native(lay.fmt[(size_t) d.layers], d.jobs_multi.data(), njobs); - else d.pool->run_split_multi(d.jobs_multi.data(), njobs); - } - if (d.remote_count > 0) { - static thread_local std::string remote_error; - for (int r = 0; r < d.remote_count; ++r) - if (!d.remote[r]->finish(out, remote_error)) { - d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return; - } - } - if (d.peer != nullptr) { // multi-GPU: the second GPU's rows, into the same mapped rows - std::string perr; - if (!d.peer->finish(out, perr)) { - std::fprintf(stderr, "strata: %s (layer %lld)\n", perr.c_str(), (long long) d.layers); - d.failed = true; - d.fail = "the peer GPU's experts failed"; - d.fail_layer = d.layers; - return; - } - } - const auto c4 = std::chrono::steady_clock::now(); - pt("ran"); - auto ms = [](auto a, auto b) { return std::chrono::duration(b - a).count(); }; - d.ms_plan += ms(c0, c1); - d.ms_actq += ms(c1, c2); - d.ms_jobs += ms(c2, c3); - d.ms_run += ms(c3, c4); - for (int64_t i = 0; i < n_tok * k; ++i) { - const int64_t e = ids[i]; - if (e >= 0 && e < d.n_expert) d.job_of[(size_t) e] = -1; - } - d.multi_misses += njobs; - ++d.layers; - d.experts += n_tok * k; -} - -void expert_hit_run(void* user, void* stream, HitPhase phase, const int32_t* ids, int64_t k) { - ExpertDispatch& d = *(ExpertDispatch*) user; - if (d.failed) return; - cudaStream_t cs = (cudaStream_t) stream; - - if (phase == HitPhase::Launch) { - d.decided = false; - d.hit_pending = false; - if (!d.hits_ready() || ids == nullptr || k <= 0) return; - if ((int64_t) d.is_hit.size() < k) d.is_hit.resize((size_t) k); - - // ================================ THE DECISION, ONCE, ON THIS LAYER'S IDS ================================ - // - // Every routed expert is asked of the cache. Resident -> the GPU computes it. Not resident -> it is - // admitted and filled if there is room (which makes it a hit on THIS call, because the fill and the - // kernel are on one stream in that order), and otherwise it stays a miss for the CPU. - d.n_hits = 0; - for (int64_t i = 0; i < k; ++i) { - const int64_t e = ids[i]; - d.is_hit[(size_t) i] = 0; - if (e < 0 || e >= d.n_expert) continue; // out of range: the pool refuses it, with a message - int32_t slot = d.cache->slot_of(d.layers, e); - if (slot == kNotResident) { - const int32_t cand = d.cache->admit(d.layers, e); - if (cand == kNotResident) { - ++d.cache_refused; - continue; - } - // `blob` is asked ONLY for an expert about to be filled, so the source's read counter stays a - // count of distinct experts moved rather than of looks. - const uint8_t* b = d.src->blob(d.layers, e); - std::string ferr; - if (b == nullptr || !d.cache->fill_slot(cand, b, cs, ferr, (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(d.layers))) { - d.failed = true; - d.fail = "the expert cache could not fill a slot"; - d.fail_layer = d.layers; - d.fail_expert = e; - return; - } - ++d.cache_admitted; - slot = cand; - } else { - ++d.cache_hits; - } - d.is_hit[(size_t) i] = 1; - d.h_slot[(size_t) d.n_hits] = slot; - d.h_dst[(size_t) d.n_hits] = (int32_t) i; - ++d.n_hits; - } - d.decided = true; - if (d.n_hits <= 0) return; // nothing resident yet: no GPU work, and nothing for `Combine` to add - - const size_t list_bytes = (size_t) d.n_hits * sizeof(int32_t); - // `hit_out` is ZEROED rather than overwritten: the kernel writes only the rows this layer's hits own, - // so a row that was a hit last layer and a miss this one would still hold last layer's expert and - // `add_inplace` would sum it in. Finite, plausible, wrong. - if (cudaMemsetAsync(d.hit_out, 0, (size_t) d.parts_elems * sizeof(float), cs) != cudaSuccess || - cudaMemcpyAsync(d.d_slot, d.h_slot.data(), list_bytes, cudaMemcpyHostToDevice, cs) != cudaSuccess || - cudaMemcpyAsync(d.d_dst, d.h_dst.data(), list_bytes, cudaMemcpyHostToDevice, cs) != cudaSuccess) { - d.hit_fail = "the hit list could not be staged"; - d.failed = true; - d.fail = d.hit_fail; - return; - } - // The activation is quantized HERE rather than reused from `s.moe.x_q8_0`, which `post[l-1]` wrote from - // the PREVIOUS layer's `mixed`. `pre[l]` has since overwritten `mixed`, so that buffer is a layer stale - // - and a stale activation produces a perfectly finite expert for the wrong input. - // **R4.2h: THE SCALED QUANTIZER, SO A HIT REPRODUCES A MISS.** The CPU pool quantizes this same - // activation with `act_quant_q8_1` and multiplies by the fp32 `ActQ::scale`; `quantize_q8_0` writes - // an fp16 `d` instead, and `bench/micro/act_quant_parity.cu` measured **80 of 80 chunks differing by - // up to 4.761e-04 relative**. `quantize_q8_0_scaled` adopts the CPU's rule and scale, and the kernel - // takes the fp32 array. Falling back to the old path would silently reintroduce the divergence, so - // the scales are required here rather than optional. - if (d.x_q8_0_hit_scale == nullptr) { - d.failed = true; - d.fail = "the hit path has no fp32 activation scales (R4.2h)"; - return; - } - strata::kernels::quantize_q8_0_scaled(d.mixed, d.x_q8_0_hit, d.x_q8_0_hit_scale, strata::kernels::cpu::H, - cs); - if (d.hit_cpu_order) - strata::kernels::moe_hit_grouped_s2_cpu_order(d.cache_base, d.d_slot, d.d_dst, d.n_hits, - d.cache_blob, d.x_q8_0_hit, d.hit_scratch, d.hit_out, cs, d.x_q8_0_hit_scale); - else - strata::kernels::moe_hit_grouped_s2(d.cache_base, d.d_slot, d.d_dst, d.n_hits, d.cache_blob, - d.x_q8_0_hit, d.hit_scratch, d.hit_out, cs, d.x_q8_0_hit_scale); - d.hit_pending = true; - if (d.hit_done != nullptr) cudaEventRecord((cudaEvent_t) d.hit_done, cs); - // The A/B arm: ONE driver entry here, and nothing else changes. If the work was waiting for the host - // to enter the driver, this is what lets it start while the pool runs. - if (d.hit_poke && d.hit_done != nullptr) (void) cudaEventQuery((cudaEvent_t) d.hit_done); - return; - } - - // Combine: `parts += hit_out`, stream-ordered after the misses were copied into `parts`. - if (!d.hit_pending) return; - d.hit_pending = false; - // Did the GPU get the hit work done while the CPU was in the pool? This query is itself a driver entry, - // so it is the LAST chance to observe a late start: a NOT-READY here means the work had not finished by the - // time the pool returned, and with no poke in front of it that can only be because it began after. - if (d.hit_done != nullptr) { - if (cudaEventQuery((cudaEvent_t) d.hit_done) == cudaSuccess) ++d.hit_ready; - else ++d.hit_late; - } - strata::kernels::add_inplace(d.parts_out, d.hit_out, d.parts_elems, cs); -} - -// ================================ THE RESIDENT ARENA (R2.1) ================================ - -namespace { - -void hash_u64(uint64_t& h, uint64_t v) { - h = fnv1a64((const uint8_t*) &v, sizeof v, h); -} - -void hash_text(uint64_t& h, const std::string& s) { - h = fnv1a64((const uint8_t*) s.data(), (uint64_t) s.size(), h); -} - -bool hash_small_file(const std::filesystem::path& path, uint64_t& h, std::string& err) { - hash_text(h, path.filename().string()); - std::ifstream f(path, std::ios::binary); - if (!f) { - hash_u64(h, 0); - return true; - } - hash_u64(h, 1); - std::vector buf(64u << 10); - for (;;) { - f.read((char*) buf.data(), (std::streamsize) buf.size()); - const std::streamsize n = f.gcount(); - if (n > 0) h = fnv1a64(buf.data(), (uint64_t) n, h); - if (f.eof()) break; - if (!f) { - err = "ArenaExpertSource: cannot hash pack metadata " + path.string(); - return false; - } - } - return true; -} - -bool hash_sampled_file(const std::filesystem::path& path, uint64_t& h, std::string& err) { - std::ifstream f(path, std::ios::binary | std::ios::ate); - if (!f) { - err = "ArenaExpertSource: cannot sample pack source " + path.string(); - return false; - } - const std::streamoff end = f.tellg(); - if (end < 0) { - err = "ArenaExpertSource: cannot size pack source " + path.string(); - return false; - } - const uint64_t bytes = (uint64_t) end; - hash_text(h, path.filename().string()); - hash_u64(h, bytes); - constexpr uint64_t sample = 64u << 10; - const uint64_t starts[3] = {0, bytes / 2, bytes > sample ? bytes - sample : 0}; - std::vector buf((size_t) std::min(sample, bytes)); - for (uint64_t off : starts) { - if (buf.empty()) break; - const uint64_t at = std::min(off, bytes - (uint64_t) buf.size()); - f.clear(); - f.seekg((std::streamoff) at); - f.read((char*) buf.data(), (std::streamsize) buf.size()); - if ((size_t) f.gcount() != buf.size()) { - err = "ArenaExpertSource: short read while hashing pack source " + path.string(); - return false; - } - hash_u64(h, at); - h = fnv1a64(buf.data(), (uint64_t) buf.size(), h); - } - return true; -} - -bool shared_arena_pack_hash(const std::string& pack_dir, const std::string& experts_path, - const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay, - uint64_t& out, std::string& err) { - uint64_t h = 1469598103934665603ull; - hash_text(h, "strata-shared-expert-arena-pack-v1"); - hash_u64(h, (uint64_t) lay.n_layers); - hash_u64(h, (uint64_t) lay.n_expert); - hash_u64(h, lay.total); - hash_u64(h, lay.max_blob); - hash_u64(h, lay.native ? 1 : 0); - - const std::filesystem::path pack(pack_dir); - for (const char* name : {"manifest.json", "index.txt", "native_experts.txt"}) { - if (!hash_small_file(pack / name, h, err)) return false; - } - - if (std::filesystem::exists(experts_path)) { - if (!hash_sampled_file(experts_path, h, err)) return false; - } else if (!gguf.empty()) { - // Native packs may read experts straight from one or more GGUF shards. Sample every distinct source - // file named by native_experts.txt; this keeps the fingerprint cheap while still tying it to the model - // bytes rather than only to an equal-size layout. - const std::filesystem::path first(gguf); - std::vector sources{first}; - for (const std::string& name : lay.gguf_file) { - if (name.empty()) continue; - const std::filesystem::path p = first.parent_path() / name; - if (std::find(sources.begin(), sources.end(), p) == sources.end()) sources.push_back(p); - } - for (const auto& p : sources) { - if (!hash_sampled_file(p, h, err)) return false; - } - } - - out = h == 0 ? 1 : h; - return true; -} - -} // namespace - -namespace { -/// The GGUF file that holds role `r` (0 gate, 1 up, 2 down) of layer `l`: a name beside the --native shard -/// (native_experts.txt v3 per layer, v4 per role), or the --native shard itself. -std::string expert_gguf_file(const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay, int64_t l, int r) { - const size_t i = (size_t) (3 * l + r); - if (lay.gguf_file.size() <= i || lay.gguf_file[i].empty()) return gguf; - const size_t cut = gguf.find_last_of("/\\"); - return (cut == std::string::npos ? std::string() : gguf.substr(0, cut + 1)) + lay.gguf_file[i]; -} -} // namespace - -bool check_experts_gguf(const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay, std::string& err) { - static const char* roles[3] = {"gate", "up", "down"}; - if (lay.gguf_off.size() != (size_t) (3 * lay.n_layers)) { - err = "native_experts.txt has no GGUF offsets (a pack older than v2): repack it with tools/iq_pack.py"; - return false; - } - try { - std::map> files; - for (int64_t l = 0; l < lay.n_layers; ++l) { - const auto& fm = lay.fmt[(size_t) l]; - const uint64_t blob = lay.bytes[(size_t) l]; - const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off}; - for (int r = 0; r < 3; ++r) { - const std::string path = expert_gguf_file(gguf, lay, l, r); - auto& f = files[path]; - if (!f) f = std::make_unique(path); - const std::string name = "blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight"; - const strata::TensorInfo* t = f->find(name); - const uint64_t want_type = (uint64_t) (r < 2 ? fm.gu_type : fm.d_type); - // GGUF order: dim 0 is the row (the input), dim 1 the rows, dim 2 the experts - const uint64_t cols = (uint64_t) (r < 2 ? fm.n_embd : fm.n_ff); - const uint64_t rows = (uint64_t) (r < 2 ? fm.n_ff : fm.n_embd); - const uint64_t bytes = per[r] * (uint64_t) lay.n_expert; - const uint64_t payload = f->file_size() - f->data_start(); - std::string why; - if (t == nullptr) why = "is not in it"; - else if (t->type != want_type) - why = std::string("is ") + t->type_name() + ", the pack says type " + std::to_string(want_type); - else if (t->shape.size() != 3 || t->shape[0] != cols || t->shape[1] != rows || - t->shape[2] != (uint64_t) lay.n_expert) - why = "is not [" + std::to_string(cols) + ", " + std::to_string(rows) + ", " + - std::to_string(lay.n_expert) + "]"; - else if (strata::tensor_payload_bytes(*t) != bytes) - why = "is not " + std::to_string(per[r]) + " B per expert"; - else if (f->data_start() + t->offset != lay.gguf_off[(size_t) (3 * l + r)]) - why = "starts at byte " + std::to_string(f->data_start() + t->offset) + ", the pack says " + - std::to_string(lay.gguf_off[(size_t) (3 * l + r)]); - else if (t->offset > payload || bytes > payload - t->offset) - why = "runs past the end of the file (a truncated shard?)"; - if (!why.empty()) { - err = "the pack's native_experts.txt does not match the model: " + name + " in " + path + " " + - why + " - repack with tools/iq_pack.py from this model's shards"; - return false; - } - } - } - return true; - } catch (const std::exception& e) { - err = std::string("native experts from the GGUF: ") + e.what(); - return false; - } -} - -// Plan v0.3 P6: the arena from the model's GGUF shards. Each layer's gate, up and down tensors hold the 512 -// experts one after another; they are read in chunks and each expert's slice lands at its place in the blob -// [gate rows | up rows | down rows] - the layout tools/iq_pack.py would have written to experts.bin. Each role -// is read from its own file (native_experts.txt v4: a shard boundary can fall inside a layer; per role as in -// #255, gopinath87607). The caller checks the spans first (check_experts_gguf). -// `unbuffered` (Windows, experts_unbuffered): each chunk's 4 KiB-aligned window is read with FILE_FLAG_NO_BUFFERING into -// an aligned buffer and scattered into the blobs - no copy through the file cache when the drive is read anyway. -LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata::kernels::cpu::ExpertLayout& lay, - int threads, bool unbuffered) { - LoadStats st; - st.layers = (uint64_t) lay.n_layers; - const auto t0 = std::chrono::steady_clock::now(); - std::atomic next{0}; - std::atomic bad{false}; -#if defined(_WIN32) - if (unbuffered) { - uint64_t max_chunk = 0; - for (int64_t l = 0; l < lay.n_layers; ++l) { - const auto& fm = lay.fmt[(size_t) l]; - max_chunk = std::max(max_chunk, std::max(fm.up_off, lay.bytes[(size_t) l] - fm.down_off) * 16); - } - std::mutex err_mu; - std::string err; - auto worker = [&]() { - constexpr uint64_t kSector = 4096; - const uint64_t cap = (max_chunk + 2 * kSector + kSector - 1) / kSector * kSector; - uint8_t* buf = (uint8_t*) VirtualAlloc(nullptr, (size_t) cap, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); - HANDLE h = INVALID_HANDLE_VALUE; - std::string open_name; - auto fail = [&](const std::string& what) { - std::lock_guard g(err_mu); - if (err.empty()) err = what; - bad = true; - }; - if (buf == nullptr) fail("cannot allocate a read buffer"); - for (;;) { - const int64_t l = next.fetch_add(1); - if (l >= lay.n_layers || bad) break; - const auto& fm = lay.fmt[(size_t) l]; - const uint64_t blob = lay.bytes[(size_t) l]; - const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off}; - const uint64_t at[3] = {0, fm.up_off, fm.down_off}; - for (int r = 0; r < 3 && !bad; ++r) { - // the handle is kept while consecutive roles share a file (every layer of a v3 pack) - const std::string name = expert_gguf_file(gguf, lay, l, r); - if (name != open_name) { - if (h != INVALID_HANDLE_VALUE) CloseHandle(h); - const int wide = MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, nullptr, 0); - std::vector w((size_t) std::max(wide, 1), L'\0'); - if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, w.data(), wide); - h = CreateFileW(w.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, - FILE_FLAG_NO_BUFFERING | FILE_FLAG_SEQUENTIAL_SCAN, nullptr); - if (h == INVALID_HANDLE_VALUE) { - fail("cannot open " + name + " (error " + std::to_string((unsigned long long) GetLastError()) + ")"); - break; - } - open_name = name; - } - const uint64_t src = lay.gguf_off[(size_t) (3 * l + r)]; - const uint64_t total = per[r] * (uint64_t) lay.n_expert; - const uint64_t chunk = per[r] * 16; // 16 experts per read - for (uint64_t done = 0; done < total; done += chunk) { - const uint64_t n = std::min(chunk, total - done); - const uint64_t a0 = (src + done) / kSector * kSector; - const uint64_t a1 = (src + done + n + kSector - 1) / kSector * kSector; - OVERLAPPED ov{}; - ov.Offset = (DWORD) a0; - ov.OffsetHigh = (DWORD) (a0 >> 32); - DWORD got = 0; - // the window may run past the end of the file: only the tensor's own bytes have to arrive - if (!ReadFile(h, buf, (DWORD) (a1 - a0), &got, &ov) || (uint64_t) got < src + done - a0 + n) { - fail("short unbuffered read of layer " + std::to_string(l) + " in " + name + " (error " + - std::to_string((unsigned long long) GetLastError()) + ")"); - break; - } - const uint8_t* q = buf + (src + done - a0); - for (uint64_t k = 0; k < n / per[r]; ++k) { - const uint64_t e = done / per[r] + k; - std::memcpy(dst + lay.blob_offset(l, (int64_t) e) + at[r], q + k * per[r], (size_t) per[r]); - } - } - } - } - if (h != INVALID_HANDLE_VALUE) CloseHandle(h); - if (buf != nullptr) VirtualFree(buf, 0, MEM_RELEASE); - }; - std::vector pool; - for (int i = 1; i < threads; ++i) pool.emplace_back(worker); - worker(); - for (auto& t : pool) t.join(); - if (bad) { - st.seconds = -1.0; - st.ok = false; - st.error = err.empty() ? "unreadable shard while reading the experts from the GGUF" : err; - return st; - } - st.bytes = lay.total; - st.seconds = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - return st; - } -#else - (void) unbuffered; -#endif - // UnbiasedStrata: positional reads through strata/platform/robust_read.hpp, so a network store that refuses a - // read for a moment (too many readers at once, a slow link) is waited for and retried instead of failing the - // start, and a failure names the file, the offset and the error. - strata::platform::ReadGate gate(threads); - std::mutex err_mu; - std::string err; - std::atomic loaded{0}; - auto fail = [&](const std::string& m) { - std::lock_guard lk(err_mu); - if (!bad.exchange(true)) err = m; - }; - auto worker = [&]() { - // The guard closes the handle on every return. - struct Closer { - int fd = -1; - ~Closer() { if (fd >= 0) ::close(fd); } - } file; - std::string open_name; - std::vector buf; - for (;;) { - const int64_t l = next.fetch_add(1); - if (l >= lay.n_layers || bad) break; - const auto& fm = lay.fmt[(size_t) l]; - const uint64_t blob = lay.bytes[(size_t) l]; - const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off}; - const uint64_t at[3] = {0, fm.up_off, fm.down_off}; - for (int r = 0; r < 3; ++r) { - // the handle is kept while consecutive roles share a file (every layer of a v3 pack) - const std::string name = expert_gguf_file(gguf, lay, l, r); - if (name != open_name) { - if (file.fd >= 0) ::close(file.fd); - file.fd = ::open(name.c_str(), O_RDONLY | O_CLOEXEC); - if (file.fd < 0) { fail("cannot open " + name + ": " + std::strerror(errno)); return; } - open_name = name; - } - const uint64_t src = lay.gguf_off[(size_t) (3 * l + r)]; - const uint64_t total = per[r] * (uint64_t) lay.n_expert; - const uint64_t chunk = per[r] * 16; // 16 experts per read - buf.resize((size_t) chunk); - for (uint64_t done = 0; done < total; done += chunk) { - if (bad) return; - const uint64_t n = std::min(chunk, total - done); - const int rc = strata::platform::read_at(file.fd, buf.data(), (size_t) n, src + done, gate); - if (rc != 0) { fail(strata::platform::read_error(name, src + done, rc)); return; } - for (uint64_t k = 0; k < n / per[r]; ++k) { - const uint64_t e = done / per[r] + k; - std::memcpy(dst + lay.blob_offset(l, (int64_t) e) + at[r], buf.data() + k * per[r], (size_t) per[r]); - } - const uint64_t was = loaded.fetch_add(n); - if ((was + n) >> 32 != was >> 32) { - const double s = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - std::fprintf(stderr, "strata generate: experts: %.0f of %.1f GiB read (%.0f MB/s)\n", - (double) (was + n) / 1073741824.0, (double) lay.total / 1073741824.0, - s > 0 ? (double) (was + n) / 1e6 / s : 0.0); - } - } - } - } - }; - std::vector pool; - for (int i = 1; i < threads; ++i) pool.emplace_back(worker); - worker(); - for (auto& t : pool) t.join(); - if (bad) { - st.seconds = -1.0; - st.ok = false; - st.error = err.empty() ? "unreadable shard while reading the experts from the GGUF" : err; - return st; - } - st.bytes = lay.total; - st.seconds = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - return st; -} - -ArenaExpertSource::~ArenaExpertSource() { close(); } - -bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int threads, - std::string& err, uint64_t max_pinned_bytes, - const std::string& shared_arena_file) { - close(); - const std::string path = pack_dir + "/experts.bin"; - // plan v0.3 P6: the layout (canonical, or a native pack's per-layer blobs) was loaded by the driver - const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout(); - if (lay.n_layers != n_layers || lay.n_expert != n_expert) { - err = "ArenaExpertSource: the expert layout was loaded for a different geometry"; - return false; - } - const int64_t blob = (int64_t) lay.max_blob; - const uint64_t want = lay.total; - - // plan v0.3 P6: no experts.bin in a native pack -> the experts come straight from the GGUF - const bool from_gguf = !std::ifstream(path, std::ios::binary) && lay.native && !lay.gguf_off.empty() && !gguf_.empty(); - // SIZE CHECK BEFORE THE ALLOCATION, not after. A wrong pack should name the two numbers rather than spend - // 34 GB and a minute of loading first. - if (from_gguf) { - // every (file, offset) of native_experts.txt must be the tensor it claims, of the pack's type and - // dimensions and inside its file - before the allocation, so a pack of another model or a truncated - // shard is a message rather than an arena of plausible wrong experts - if (!check_experts_gguf(gguf_, lay, err)) { err = "ArenaExpertSource: " + err; return false; } - } else { - std::ifstream f(path, std::ios::binary | std::ios::ate); - if (!f) { err = "ArenaExpertSource: cannot open " + path; return false; } - const uint64_t got = (uint64_t) f.tellg(); - if (got != want && got != want + (uint64_t) blob) { // + one blob: STRATA_ARENA_MMAP's padded file - char buf[400]; - std::snprintf(buf, sizeof buf, - "ArenaExpertSource: %s is %llu B but %lld layers x %lld experts (blobs up to %lld B) " - "make %llu B - this is not the pack this geometry came from", - path.c_str(), (unsigned long long) got, (long long) n_layers, (long long) n_expert, - (long long) blob, (unsigned long long) want); - err = buf; - return false; - } - } - - // STRATA_ARENA_MMAP=1 (a small-RAM machine whose GPUs hold most experts): the arena is the pack's experts.bin - // mapped READ-ONLY - not locked, not pinned. The page cache keeps what the CPU pool and the prompt path - // actually read (the experts no VRAM cache holds) and gives back the rest under memory pressure; a page - // dropped is re-read from the file, so a result never depends on what is resident. The GPUs then get no - // mapped alias: run with --pcie-frac 0. The first start writes experts.bin (arena layout, padded by one blob - // so a whole-slot copy may start at any expert), later ones map it. -#if defined(_WIN32) - static const bool arena_mmap = false; // POSIX mmap/madvise: Linux only for now -#else - static const bool arena_mmap = [] { const char* v = std::getenv("STRATA_ARENA_MMAP"); return v && v[0] == '1'; }(); - if (arena_mmap) { - const uint64_t file_bytes = want + (uint64_t) blob; - uint64_t have = 0; - { - std::ifstream f(path, std::ios::binary | std::ios::ate); - if (f) have = (uint64_t) f.tellg(); - } - if (have == file_bytes) { - const int fd = ::open(path.c_str(), O_RDONLY); - void* v = fd >= 0 ? mmap(nullptr, (size_t) file_bytes, PROT_READ, MAP_SHARED, fd, 0) : MAP_FAILED; - if (fd >= 0) ::close(fd); - if (v == MAP_FAILED) { err = "ArenaExpertSource: mmap of " + path + " failed"; return false; } - map_ = v; - map_bytes_ = file_bytes; - base_ = (const uint8_t*) v; - pinned_bytes_ = 0; - dev_slice_.clear(); - slice_bytes_ = 0; - blobs_ = n_layers * n_expert; - n_expert_ = n_expert; - reads_ = 0; - note_ = "mapped read-only from " + path + " (STRATA_ARENA_MMAP: not locked, not pinned)"; - gib_per_s_ = 0.0; - load_seconds_ = load_read_s_ = load_copy_s_ = 0.0; - return true; - } - } -#endif - - // #633: THE RAM BEFORE THE ALLOCATION. On Linux the arena is an anonymous mapping that succeeds whatever the host - // has; its pages are committed as the load writes them, so a container whose memory limit is below the arena was - // killed by the OOM killer part-way through the load, without a message. A hard cgroup limit below it is - // certain to end that way: refused, with the numbers. Less RAM available than the arena (another program, an - // engine still exiting) is only a warning - the OS may make room - per the recommend-not-force rule. - ram_warning_.clear(); - // (a shared arena, --shared-expert-arena, may already be in RAM for another engine: not checked) - if (detail::HostMemory hm; shared_arena_file.empty() && detail::host_available_memory(hm)) { - const uint64_t need = want + (uint64_t) blob; - const double gib = 1073741824.0; - char buf[512]; - if (hm.cgroup_limit < need) { - std::snprintf(buf, sizeof buf, - "ArenaExpertSource: the expert arena needs %.2f GiB of RAM but this process's memory limit " - "(cgroup memory.max / memory.limit_in_bytes) is %.2f GiB: it would be killed while loading. " - "Raise the container's limit, or run with less RAM: --mmap-experts with " - "--resident-budget-gib N keeps only the hottest experts in RAM", - (double) need / gib, (double) hm.cgroup_limit / gib); - err = buf; - return false; - } - if (hm.available < need) { - std::snprintf(buf, sizeof buf, - "the expert arena needs %.2f GiB of RAM but %.2f GiB is available (%.2f GiB short): the load " - "may swap or be stopped by the OS. Close other programs (or wait for an engine that is " - "still exiting), or run with less RAM: --mmap-experts with --resident-budget-gib N", - (double) need / gib, (double) hm.available / gib, (double) (need - hm.available) / gib); - ram_warning_ = buf; - } - } - - uint64_t pack_hash = 0; - if (!shared_arena_file.empty() && - !shared_arena_pack_hash(pack_dir, path, gguf_, lay, pack_hash, err)) return false; - - // one layer per registration slice, so no expert straddles two registrations. The arena is one blob - // longer than the file: a copy of a whole VRAM slot (the largest blob) may then start at any expert. - std::vector bounds, loff, lbytes; - for (int64_t l = 0; l < n_layers; ++l) { - bounds.push_back(lay.layer_offset(l)); - loff.push_back(lay.layer_offset(l)); - lbytes.push_back(lay.blob_bytes(l) * (uint64_t) n_expert); - } - bounds.push_back(want); - PinnedArena* a = new PinnedArena(want + (uint64_t) blob, bounds, max_pinned_bytes, - shared_arena_file, pack_hash); - if (!a->valid()) { - const std::string why = a->note; - delete a; - err = "ArenaExpertSource: the arena could not be reserved (" + - std::to_string(want + (uint64_t) blob) + " B)" + - (why.empty() ? std::string{} : ": " + why); - return false; - } - // #285: unbuffered when the drive is read anyway and the file cache could not keep the experts for the next - // start either (a 64 GB PC); otherwise the buffered readers, which a warm restart serves from the cache - std::vector files; - if (from_gguf) { - for (int64_t l = 0; l < n_layers; ++l) - for (int r = 0; r < 3; ++r) { - const std::string f = expert_gguf_file(gguf_, lay, l, r); - if (std::find(files.begin(), files.end(), f) == files.end()) files.push_back(f); - } - } else { - files.push_back(path); - } - std::string why; - const bool unbuffered = experts_unbuffered(files, want + (uint64_t) blob, why); - const int readers = unbuffered ? std::max(threads, 16) : threads; // 16 keep a PCIe 5 drive's queue full - LoadStats st; - if (from_gguf) { - st = load_experts_gguf(gguf_, a->data(), lay, readers, unbuffered); - } else { - if (unbuffered) st = load_experts_direct(path, a->data(), loff, lbytes, readers, /*chunk=*/8u << 20); - if (!unbuffered || (!st.ok && st.error.empty())) // unaligned ranges: the buffered reader - st = load_experts_ranges(path, a->data(), loff, lbytes, threads, /*chunk=*/8u << 20); - } - std::fprintf(stderr, "strata generate: expert arena read %s (%s)\n", unbuffered ? "unbuffered" : "through the file cache", - why.c_str()); - if (!st.ok) { - delete a; - err = "ArenaExpertSource: the expert load was refused: " + (st.error.empty() ? std::string("unknown") : st.error); - return false; - } - if (st.bytes != want) { - delete a; - err = "ArenaExpertSource: the load read " + std::to_string(st.bytes) + " B of " + std::to_string(want); - return false; - } - // the first start: write experts.bin for the mapped starts after this one - only when the drive has room for it - // and 2 GiB more (a full drive fails other writes too); otherwise this start says so and runs pinned as before - std::error_code space_ec; - const uint64_t free_disk = arena_mmap && from_gguf ? (uint64_t) std::filesystem::space( - std::filesystem::path(path).parent_path(), space_ec).available : 0; - const bool room = !space_ec && free_disk >= want + (uint64_t) blob + (2ull << 30); - if (arena_mmap && from_gguf && !room) - std::fprintf(stderr, "strata generate: STRATA_ARENA_MMAP: NOT writing %s - %.1f GiB free on that drive, it needs " - "%.1f GiB plus 2 GiB to spare; this start keeps the arena in RAM\n", path.c_str(), - (double) free_disk / 1073741824.0, (double) (want + (uint64_t) blob) / 1073741824.0); - if (arena_mmap && from_gguf && room) { - const std::string tmp = path + ".tmp"; - std::FILE* f = std::fopen(tmp.c_str(), "wb"); - bool ok = f != nullptr && std::fwrite(a->data(), 1, (size_t) want, f) == (size_t) want; - if (ok) { - std::vector pad((size_t) blob, 0); - ok = std::fwrite(pad.data(), 1, pad.size(), f) == pad.size(); - } - if (f) ok = std::fclose(f) == 0 && ok; - if (ok) ok = std::rename(tmp.c_str(), path.c_str()) == 0; - if (!ok) std::remove(tmp.c_str()); - std::fprintf(stderr, "strata generate: STRATA_ARENA_MMAP: %s %s (the next start maps it)\n", - ok ? "wrote" : "could NOT write", path.c_str()); - } - arena_ = a; - base_ = a->data(); - pinned_bytes_ = a->registered_bytes; - // plan v0.3 P6: device aliases of the mapped registration, for the PCIe share of the misses - dev_slice_.clear(); - slice_bytes_ = a->slice_bytes; - if (a->registered_bytes > 0) { - std::vector starts = a->slice_bytes > 0 ? a->slice_starts : std::vector{0}; - for (uint64_t off : starts) { - void* d = nullptr; - if (cudaHostGetDevicePointer(&d, (void*) (base_ + off), 0) != cudaSuccess) { - (void) cudaGetLastError(); - dev_slice_.clear(); - break; - } - dev_slice_.push_back((const uint8_t*) d); - } - } - blobs_ = n_layers * n_expert; - n_expert_ = n_expert; - reads_ = 0; - note_ = a->note; - gib_per_s_ = st.gib_per_second(); - load_seconds_ = st.seconds; - load_read_s_ = st.read_seconds; - load_copy_s_ = st.copy_seconds; - return true; -} - -void ArenaExpertSource::close() { -#if !defined(_WIN32) - if (map_ != nullptr) munmap(map_, (size_t) map_bytes_); -#endif - map_ = nullptr; - map_bytes_ = 0; - if (arena_ != nullptr) { - delete (PinnedArena*) arena_; - arena_ = nullptr; - } - base_ = nullptr; - blobs_ = 0; - n_expert_ = 0; -} - -void ArenaExpertSource::prefetch(int64_t layer, int64_t expert) { -#if defined(_WIN32) - (void) layer; (void) expert; -#else - if (map_ == nullptr || layer < 0 || expert < 0 || expert >= n_expert_) return; - const auto& lay = strata::kernels::cpu::expert_layout(); - const uint64_t off = lay.blob_offset(layer, expert) & ~(uint64_t) 4095; - const uint64_t end = lay.blob_offset(layer, expert) + lay.blob_bytes(layer); - madvise((uint8_t*) map_ + off, (size_t) (end - off), MADV_WILLNEED); -#endif -} - -// Only the pages wholly inside the blob: a page shared with a neighbour the CPU may still read stays. MADV_DONTNEED -// unmaps them from this process; they stay in the page cache as clean, unmapped pages - the first the kernel takes -// back under pressure, and a minor fault away when the CPU needs the expert again (an adaptive swap evicts it). -// Dropping them from the cache too (POSIX_FADV_DONTNEED) made every eviction a re-read from the disk: ~200 major -// faults a second in decode, +8 ms a window. The memory the arena used to hold was never the cache itself but -// ROCclr's pin-in-place locks on it (see main) - locked pages are the ones the kernel cannot take back. -uint64_t ArenaExpertSource::release(int64_t layer, int64_t expert) { -#if defined(_WIN32) - (void) layer; (void) expert; - return 0; -#else - if (map_ == nullptr || layer < 0 || expert < 0 || expert >= n_expert_) return 0; - const auto& lay = strata::kernels::cpu::expert_layout(); - const uint64_t off = (lay.blob_offset(layer, expert) + 4095) & ~(uint64_t) 4095; - const uint64_t end = (lay.blob_offset(layer, expert) + lay.blob_bytes(layer)) & ~(uint64_t) 4095; - if (end <= off) return 0; - if (madvise((uint8_t*) map_ + off, (size_t) (end - off), MADV_DONTNEED) != 0) return 0; - return end - off; -#endif -} - -bool ArenaExpertSource::pinned(int64_t layer, int64_t expert) const { - if (base_ == nullptr || layer < 0 || expert < 0 || expert >= n_expert_) return false; - const auto& lay = strata::kernels::cpu::expert_layout(); - return lay.blob_offset(layer, expert) + lay.blob_bytes(layer) <= pinned_bytes_; -} - -const uint8_t* ArenaExpertSource::device_alias(int64_t layer, int64_t expert) const { - if (dev_slice_.empty() || !pinned(layer, expert)) return nullptr; - const auto& lay = strata::kernels::cpu::expert_layout(); - if (slice_bytes_ == 0) return dev_slice_[0] + lay.blob_offset(layer, expert); - // one registration slice per layer - if ((size_t) layer >= dev_slice_.size()) return nullptr; - return dev_slice_[(size_t) layer] + (uint64_t) expert * lay.blob_bytes(layer); -} - -const uint8_t* ArenaExpertSource::blob(int64_t layer, int64_t expert) { - if (base_ == nullptr) return nullptr; - if (layer < 0 || expert < 0 || expert >= n_expert_) return nullptr; - const int64_t idx = layer * n_expert_ + expert; - if (idx < 0 || idx >= blobs_) return nullptr; - ++reads_; - // Pointer arithmetic into resident memory. No fault, no copy, no mapping - which is the entire point of - // this class over `FileExpertSource`. - return base_ + strata::kernels::cpu::expert_layout().blob_offset(layer, expert); -} - -} // namespace strata::core diff --git a/src/core/graph.cpp b/src/core/graph.cpp deleted file mode 100644 index 2e9c7e7..0000000 --- a/src/core/graph.cpp +++ /dev/null @@ -1,146 +0,0 @@ -// src/core/graph.cpp - P2.S5: the GraphRegistry implementation. -#include "strata/core/graph.hpp" - -#include - -#include -#include - -namespace strata::core { -namespace { - -/// Fills `err` from the CUDA runtime, naming the call that failed. A bare "invalid argument" with no call -/// site is the least useful error this API can produce and the easiest to avoid. -bool fail(std::string& err, const char* what, cudaError_t e) { - err = std::string(what) + ": " + cudaGetErrorString(e); - return false; -} - -} // namespace - -CapturedGraph& CapturedGraph::operator=(CapturedGraph&& o) noexcept { - if (this != &o) { - reset(); - graph_ = o.graph_; - exec_ = o.exec_; - done_ = o.done_; - nodes_ = o.nodes_; - o.graph_ = nullptr; - o.exec_ = nullptr; - o.done_ = nullptr; - o.nodes_ = 0; - } - return *this; -} - -void CapturedGraph::reset() { - // ORDER MATTERS: destroying a graph exec BLOCKS until the launch it is destroying has completed, so - // destroying it before the event is harmless but destroying it after a spin that was supposed to observe - // completion would silently become the thing that caused it. `bench/micro/graph_capture.cu` was fooled by - // exactly this once - it looked like captured graphs made a doorbell visible and direct launches did not. - if (exec_) { cudaGraphExecDestroy(exec_); exec_ = nullptr; } - if (graph_) { cudaGraphDestroy(graph_); graph_ = nullptr; } - if (done_) { cudaEventDestroy(done_); done_ = nullptr; } - nodes_ = 0; -} - -bool CapturedGraph::begin(void* stream, std::string& err) { - if (graph_ || exec_) { err = "begin: this CapturedGraph is already recorded"; return false; } - const cudaError_t e = cudaStreamBeginCapture((cudaStream_t) stream, cudaStreamCaptureModeThreadLocal); - if (e != cudaSuccess) return fail(err, "cudaStreamBeginCapture", e); - return true; -} - -bool CapturedGraph::end(void* stream, std::string& err) { - cudaError_t e = cudaStreamEndCapture((cudaStream_t) stream, &graph_); - if (e != cudaSuccess) { graph_ = nullptr; return fail(err, "cudaStreamEndCapture", e); } - - nodes_ = 0; - e = cudaGraphGetNodes(graph_, nullptr, &nodes_); - if (e != cudaSuccess) return fail(err, "cudaGraphGetNodes", e); - // A capture that recorded NOTHING is a wiring mistake, and a graph that replays nothing produces no error - // and no output - the silent kind of failure this project keeps paying for. - if (nodes_ == 0) { err = "end: the capture recorded ZERO nodes - the body launched nothing"; reset(); return false; } - - e = cudaGraphInstantiate(&exec_, graph_, nullptr, nullptr, 0); - if (e != cudaSuccess) return fail(err, "cudaGraphInstantiate", e); - - // The completion event is recorded ONCE and reused: `launch` records it again after each replay, which is - // what makes `wait_ms` a query rather than a sync. - e = cudaEventCreateWithFlags(&done_, cudaEventDisableTiming); - if (e != cudaSuccess) return fail(err, "cudaEventCreateWithFlags", e); - return true; -} - -bool CapturedGraph::launch(void* stream, std::string& err) const { - if (!exec_) { err = "launch: not recorded"; return false; } - cudaError_t e = cudaGraphLaunch(exec_, (cudaStream_t) stream); - if (e != cudaSuccess) return fail(err, "cudaGraphLaunch", e); - e = cudaEventRecord(done_, (cudaStream_t) stream); - if (e != cudaSuccess) return fail(err, "cudaEventRecord", e); - return true; -} - -bool CapturedGraph::wait_ms(int timeout_ms) const { - if (!done_) return false; - // A BOUNDED wait, and the bound is the point: an unbounded spin turns a protocol bug into a hung run, and - // a hung run says nothing about which side is stuck. `cudaEventQuery` is a QUERY - it does not block and - // it does not synchronise - so this satisfies P2.X3 while still giving the driver the call it needs to - // flush the submission. See NOTE 1 in the header: without a driver call here the work never starts. - // - // The deadline is a REAL CLOCK, not a count of pause instructions: `_mm_pause` is a few cycles, so - // counting pauses as microseconds would make the timeout tens of times longer than the caller asked for - - // a timeout that does not time out is worse than none, because it reports a hang as a pass. - const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms); - for (;;) { - const cudaError_t q = cudaEventQuery(done_); - if (q == cudaSuccess) return true; - if (q != cudaErrorNotReady) return false; // a real error, not "not finished" - if (std::chrono::steady_clock::now() >= deadline) return false; - for (int i = 0; i < 64; ++i) _mm_pause(); - } -} - -bool GraphRegistry::record(LayerType type, int n_tokens, const std::function& body, std::string& err) { - const Key k{(int) type, n_tokens}; - if (graphs_.count(k)) return true; // already recorded: the point of a registry - - CapturedGraph g; - if (!g.begin(stream_, err)) return false; - body(); // the caller launches into the captured stream - // The body must not have failed silently. An error state left on the stream would make EndCapture - // succeed with a broken graph, so it is checked and cleared first. - const cudaError_t body_err = cudaGetLastError(); - if (body_err != cudaSuccess) { - // Abandon the capture without instantiating anything. - cudaGraph_t junk = nullptr; - cudaStreamEndCapture((cudaStream_t) stream_, &junk); - if (junk) cudaGraphDestroy(junk); - return fail(err, "the capture body left a CUDA error", body_err); - } - if (!g.end(stream_, err)) return false; - - graphs_.emplace(k, std::move(g)); - ++captures_; - return true; -} - -const CapturedGraph* GraphRegistry::find(LayerType type, int n_tokens) const { - const auto it = graphs_.find(Key{(int) type, n_tokens}); - return it == graphs_.end() ? nullptr : &it->second; -} - -bool GraphRegistry::launch(LayerType type, int n_tokens, int timeout_ms, std::string& err) const { - const CapturedGraph* g = find(type, n_tokens); - if (!g) { - char buf[128]; - std::snprintf(buf, sizeof buf, "launch: no graph recorded for %s n=%d", to_string(type), n_tokens); - err = buf; - return false; - } - if (!g->launch(stream_, err)) return false; - if (!g->wait_ms(timeout_ms)) { err = "launch: timed out waiting for the graph to complete"; return false; } - return true; -} - -} // namespace strata::core diff --git a/src/core/layer.cpp b/src/core/layer.cpp deleted file mode 100644 index 4d1e019..0000000 --- a/src/core/layer.cpp +++ /dev/null @@ -1,1517 +0,0 @@ - -// 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" -#include "strata/kernels/elementwise.hpp" -#include "strata/kernels/gdn.hpp" -#include "strata/kernels/qsa.hpp" -#include "strata/kernels/kv_q4.hpp" -#include "strata/kernels/kv_q8.hpp" -#include "strata/kernels/quantize_act.hpp" -#include "strata/kernels/rope.hpp" -#include "strata/kernels/router_top10.hpp" -#include "strata/kernels/s2_gemv_q8.hpp" -#include "strata/kernels/s_gemv.hpp" -#include "strata/kernels/shared_expert.hpp" -#include "strata/kernels/native_mmvq.hpp" -#include "strata/kernels/native_moe.hpp" -#include "strata/kernels/native_gdn.hpp" -#include "strata/kernels/native_gdn_preprocess.hpp" -#include "strata/kernels/native_router.hpp" -#include "strata/kernels/native_qsa.hpp" -#include "strata/kernels/native_qsa_indexer.hpp" -#include "strata/kernels/mrope.hpp" -#include "strata/kernels/native_rope.hpp" -#include "strata/kernels/native_flash_attn.hpp" -#include "strata/kernels/fused_gr.hpp" -#include "strata/kernels/cvec.hpp" -#include "strata/kernels/qsa_decode_attn.hpp" -#include "strata/kernels/fused_gdn.hpp" -#include "strata/kernels/qsa_select.hpp" -#include -#include -#include -#include -#include -#include -#include -#include -namespace strata::core { -namespace { bool g_shared_early = true; bool g_fused_gr = false; bool g_fast_attn = true; bool g_publish_kernel = true; bool g_fused_gdn = true; bool g_fast_select = true; } -namespace {constexpr int Q8K_BYTES_PER_BLOCK = 292; -constexpr int Q8K_ELEMS_PER_BLOCK = 256; -constexpr float RMS_EPS = 1e-6f; -const std::string EMBEDDING_NAME = "token_embd.weight"; -// qwen4exp.attention.layer_norm_rms_epsilon, used for BOTH norms here -/// A Q8_K buffer needs `n` a multiple of 256 and `n/256` blocks of 292 bytes. -uint64_t q8k_bytes(int64_t n) { return (uint64_t) (n / Q8K_ELEMS_PER_BLOCK) * Q8K_BYTES_PER_BLOCK; } -/// `s_gemv_q8k` takes the canonical-form attributes; a `WeightRef` carries them, and a tensor that is NOT -/// quantized has none. Returns false and names the tensor rather than building a form out of zeroes - which -/// would decode every code as `0 + bias` and produce a perfectly finite wrong answer. -bool sform_of(const WeightRef& r, strata::kernels::SForm& f, const std::string& name, std::string& err) { if (!r.quantized()) { err = name + " is not a quantized tensor, so it has no S-form"; return false; } f.code_bits = r.code_bits; f.code_bias = r.code_bias; f.group_elems = r.group_elems; f.codebook = r.codebook_iq4nl ? strata::kernels::Codebook::Iq4Nl : strata::kernels::Codebook::Affine; f.has_offset = r.has_offset; f.act_kind = r.act_kind; -// carried, not derived - see the note on `SForm::act_kind` -return true;} -/// The three canonical planes of a quantized tensor, located INSIDE the loaded region. -// -// -// **THIS FUNCTION USED TO RE-DERIVE THE LAYOUT, AND THAT IS HOW A WIDTH BUG SURVIVED A ROUND.** It computed -/// `n_groups = n_in / group_elems` and then `scales_bytes = n_out * n_groups * sizeof(float)` - 4 bytes per -/// scale for every tensor. 90 of the 303 quantized tensors hold fp16 scales in the pack (all 58 Q2_0 expert -/// tensors, plus Q4_0, Q5_0, Q8_0 and IQ4_NL), so for those the computed plane was TWICE the real one and the -/// three planes did not add up to the tensor. The first diagnosis was "the manifest's `group_elems` must be -/// wrong, the real group is 64"; it is not, and an audit of all 303 tensors against `scales_fp16` found zero -/// inconsistencies. **The unexamined input was the scale WIDTH, not the group COUNT.** -// -// -// The loader now widens fp16 scales to f32 on the way into the arena and records the resulting plane sizes in -/// the `WeightRef`, so this function has nothing left to derive - it reads what was loaded. The redundancy is -/// deliberate: the sizes come from ONE place (the index, checked against the manifest by `pack_index.py` and -/// against the span by the loader), and this function only checks that they describe the tensor it was given. -// -// -// **THE PLANE KEY IS `offsets`, NOT `mins`, AND THAT COST 136 MiB.** `tools/pack_index.py` and -/// `tools/pack_budget.py` both looked for `mins` and both therefore omitted the offset plane of 54 Q4_K/Q5_K -/// tensors - so the arena was sized without it AND the bytes were never copied. Two tools agreeing is only -/// evidence when they do not share the assumption that is wrong. This function refuses rather than guessing, -/// which is what caught it. -struct Planes { const uint8_t* codes = nullptr; const float* scales = nullptr; const float* offset = nullptr; -///< null when the form has none -}; -bool plane_ptrs(const WeightRef& r, const std::string& name, Planes& out, std::string& err) { -// S2, S4 AND S8 ALL SPLIT THE SAME WAY. The plane LOCATION does not depend on the code width - the three -// sizes come from the index and are checked against the tensor below - so the guard is here to catch a -// tensor that is not quantized at all, not to pick a decoder. WHICH KERNEL reads the planes is the -// caller's choice and the two differ: an S2 tensor's activation contract is Q8_0 (`s2_gemv_q8`) while a -// K-quant's is Q8_K (`s_gemv_q8k`). This used to accept only 4 and 8, which refused `attn_q` - a Q2_0 -// tensor and the reason the QSA layer could not be composed at all. -if (r.code_bits != 2 && r.code_bits != 4 && r.code_bits != 8) { err = name + ": code_bits " + std::to_string(r.code_bits) + " is not an S2/S4/S8 form"; return false; } const uint64_t end = r.codes_bytes + r.scales_bytes + r.offset_bytes; if (r.codes_bytes == 0 || r.scales_bytes == 0 || end != r.bytes) { char buf[320]; std::snprintf(buf, sizeof buf, "%s: the planes add up to %llu B but the tensor is %llu B (codes %llu, scales %llu, " "offsets %llu) - what the loader recorded is not the layout that was loaded", name.c_str(), (unsigned long long) end, (unsigned long long) r.bytes, (unsigned long long) r.codes_bytes, (unsigned long long) r.scales_bytes, (unsigned long long) r.offset_bytes); err = buf; return false; } if (r.has_offset != (r.offset_bytes != 0)) { err = name + ": has_offset is " + std::to_string(r.has_offset ? 1 : 0) + " but the offset plane is " + std::to_string(r.offset_bytes) + " B"; return false; } const uint8_t* base = (const uint8_t*) r.data; out.codes = base; out.scales = (const float*) (base + r.codes_bytes); out.offset = r.offset_bytes ? (const float*) (base + r.codes_bytes + r.scales_bytes) : nullptr; return true;} -constexpr int TPR = 32; -bool native_bf16_projections = false; -bool native_flash_attn_short = false; - -void project_bf16(const float* x, const uint16_t* x_bf16, const uint16_t* weights, float* out, - int64_t n_in, int64_t n_out, bool split, void* stream) { - using namespace strata::kernels; - if (native_bf16_projections) bf16_gemv_fp32_mmvf(x, weights, out, n_in, n_out, stream); - else if (split) bf16_gemv_split(x_bf16, weights, out, n_in, n_out, TPR, stream); - else bf16_gemv(x_bf16, weights, out, n_in, n_out, stream); -} -///< threads per row for the row-split GEMVs. -/// **MEASURED, NOT ASSUMED, AND 64 IS NOT BETTER.** `dense_pass.exe` drives the same split kernels at -/// threads_per_row 64 and reports 248.5 GB/s, so matching it looked like free performance. It is not: -/// TPR=64 gives 11.75 tok/s against 32's 11.99 with experts, and 20.19 against 20.26 without - identical -/// inside noise and marginally worse on both. That is also what the stage table predicts, because the GEMVs -/// are only ~16% of a token, so a few percent there cannot move the total. Kept at 32; the sweep that would -/// actually settle it is per-tensor, not global, and belongs with the fusion work rather than before it. -///< threads per row for the row-split GEMVs -/// Writes the sequence number into MAPPED PINNED memory. A KERNEL, not cudaEventRecord - round 199 found -/// that an event record inside a capture is silently dropped, while this is captured normally and the host can -/// read its result MID-GRAPH. One thread: it is a store. -// (the ring kernel lives in src/kernels/cuda/elementwise.cu; this file is HOST code) -/// WHICH ACTIVATION A QUANTIZED WEIGHT WANTS, AND IT IS A PROPERTY OF THE **TENSOR**, NOT OF ITS ROLE. -// -// -// Rounds 205-215 ran `gdn_layer` and `qsa_layer` on the assumption that a name implies a family: `attn_qkv` is -/// a K-quant, `attn_q` is Q2_0, and so on. **The pack does not work that way.** The same name is quantized -/// per LAYER, and the spread is wide: -// -// -// attn_qkv IQ4_XS x13, Q3_K x18, Q2_0 x1, Q4_K x4 (36 GDN layers) -/// attn_gate Q3_K x25, IQ4_XS x4, Q4_K x3, Q2_0 x4 -/// attn_q Q3_K x6, IQ4_XS x4, Q2_0 x2 (12 QSA layers) -// -// -// `docs/activation-contract.md` fixes the rule per TYPE, and it is short: -// -// -// code_bits == 2 -> Q8_0, via `quantize_q8_0` + `s2_gemv_q8` -/// anything else quantized -> Q8_K, via `quantize_q8_K` + `s_gemv_q8k_split` -// -// -// Getting it wrong is worth 0.6-1.4% on the GEMV - a plausible vector, not a broken one - which is exactly -/// what Gate C1 exists to find and what nothing before C1 would have. `s_gemv_q8k`'s own guard is what caught -/// it here (`code_bits 2 has no Q8_K contract`). -// -// -// `x80` and `xq8k` are the two quantized images of the SAME activation; a caller produces both once and this -/// picks. Producing only the one it thinks it needs is how the assumption gets baked in again. -bool gemv_quantized(const WeightRef& w, const Planes& p, const strata::kernels::SForm& f, const uint8_t* x80, const uint8_t* xq8k, float* y, int64_t n_in, int64_t n_out, const std::string& name, void* stream, std::string& err, const float* x_f32 = nullptr, bool x_q8_1_ready = false) { - using namespace strata::kernels; - if (w.native_data) { - if (!x_f32 || !w.native_q8_1 || !stream || n_in != w.ne0 || n_out != w.ne1) { - err = name + ": native projection requires matching FP32 input and session scratch"; - return false; - } - try { - // Plan v0.3 P3: a caller whose previous native projection quantized the SAME x into the shared - // scratch, with no native projection in between, passes x_q8_1_ready and the quantize is skipped. - if (!x_q8_1_ready) native_quantize_q8_1(x_f32, w.native_q8_1, (int) n_in, 1, stream); - native_mmvq(w.native_type, w.native_data, w.native_q8_1, y, - (int) n_in, (int) n_out, 1, stream); - } catch (const std::exception& error) { - err = name + ": " + error.what(); - return false; - } - return true; - } - if ((w.code_bits == 2 || !w.wants_q8k()) ? !x80 : !xq8k) { - err = name + ": missing canonical quantized activation"; - return false; - } - if (w.code_bits == 2) { -// S2 carries no offset plane and no SForm: its attributes are fixed (2 bits, group 64, bias -1), which -// is why `s2_gemv_q8` takes neither. -if (w.has_offset || p.offset != nullptr) { err = name + ": an S2 form must have no offset plane"; return false; } if (w.group_elems != 64 || w.code_bias != -1) { err = name + ": an S2 form must be group 64 with bias -1, this one is group " + std::to_string(w.group_elems) + " with bias " + std::to_string(w.code_bias); return false; } s2_gemv_q8(x80, p.codes, p.scales, y, n_in, n_out, TPR, stream); return true; } -// **A LEGACY 4/8-BIT FORM WANTS Q8_0, NOT Q8_K, AND `code_bits` CANNOT TELL YOU WHICH.** This used to be -// `code_bits == 2 ? Q8_0 : Q8_K`, which is CORRECT ONLY BY LUCK: every legacy tensor in this pack apart -// from `ffn_down_shexp` is Q2_0, whose attributes happen to be S2's. Q5_0 and Q5_K are both 8-bit with -// bias -16 and differ only in `has_offset`; IQ4_NL and IQ4_XS differ in NOTHING the S-form carries. The -// kind therefore comes from the manifest's `source_type`, through the index (LEDGER L54/L55). -if (!w.wants_q8k()) { s_gemv_q8_0_split(x80, p.codes, p.scales, p.offset, y, n_in, n_out, f, stream); return true; } s_gemv_q8k_split(xq8k, p.codes, p.scales, p.offset, y, n_in, n_out, f, stream); return true;}} -// namespace -void layer_set_native_bf16(bool enabled) { native_bf16_projections = enabled; } -void layer_set_native_flash_attn_short(bool enabled) { native_flash_attn_short = enabled; } -namespace { bool g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false, g_kv_int8_rot = false; } -void qsa_set_kv_int8(bool enabled) { g_kv_int8 = enabled; } -void qsa_set_kv_int8_rotate(bool enabled) { g_kv_int8_rot = enabled; } -bool qsa_kv_int8() { return g_kv_int8; } -void qsa_set_kv_q4(bool enabled) { g_kv_q4 = enabled; } -bool qsa_kv_q4() { return g_kv_q4; } -void qsa_set_kv_hybrid(bool enabled) { g_kv_hybrid = enabled; } -bool qsa_kv_hybrid() { return g_kv_hybrid; } -uint64_t gdn_buffers_bytes(const ModelGeometry& g) { const int64_t C = g.ssm_conv_channels; const int64_t V = g.ssm_value_dim; const uint64_t parts[] = { q8k_bytes(g.n_embd), -// x_q8k -(uint64_t) (g.n_embd / 32) * 34, -// x_q8_0 -(uint64_t) g.n_embd * 2, -// x_bf16 -(uint64_t) C * 4, -// qkv -(uint64_t) C * 4, -// conv_out -(uint64_t) C * 4, -// h -(uint64_t) g.ssm_v_heads * 4, -// alpha -(uint64_t) g.ssm_v_heads * 4, -// beta -(uint64_t) g.ssm_v_heads * 4, -// gate -(uint64_t) g.ssm_v_heads * g.ssm_state_size * 4, -// o -(uint64_t) V * 4, -// z -(uint64_t) V * 4, -// y -q8k_bytes(V), -// y_q8k -(uint64_t) (V / 32) * 34, -// y_q8_0 -(uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size * 4, -// state -(uint64_t) C * (g.ssm_d_conv - 1) * 4, -// conv_state -}; uint64_t total = 0; for (uint64_t v : parts) total += (v + 15) & ~(uint64_t) 15; return total;} -uint64_t gdn_buffers_init(const ModelGeometry& g, void* base, GdnBuffers& b) { const int64_t C = g.ssm_conv_channels; const int64_t V = g.ssm_value_dim; const uint64_t parts[] = { q8k_bytes(g.n_embd), (uint64_t) (g.n_embd / 32) * 34, (uint64_t) g.n_embd * 2, (uint64_t) C * 4, (uint64_t) C * 4, (uint64_t) C * 4, (uint64_t) g.ssm_v_heads * 4, (uint64_t) g.ssm_v_heads * 4, (uint64_t) g.ssm_v_heads * 4, (uint64_t) g.ssm_v_heads * g.ssm_state_size * 4, (uint64_t) V * 4, (uint64_t) V * 4, q8k_bytes(V), (uint64_t) (V / 32) * 34, (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size * 4, (uint64_t) C * (g.ssm_d_conv - 1) * 4, }; uint8_t* p = (uint8_t*) base; void* ptr[16]; uint64_t total = 0; for (int i = 0; i < 16; ++i) { ptr[i] = p; const uint64_t al = (parts[i] + 15) & ~(uint64_t) 15; p += al; total += al; } b.x_q8k = (uint8_t*) ptr[0]; b.x_q8_0 = (uint8_t*) ptr[1]; b.x_bf16 = (uint16_t*) ptr[2]; b.qkv = (float*) ptr[3]; b.conv_out = (float*) ptr[4]; b.h = (float*) ptr[5]; b.alpha = (float*) ptr[6]; b.beta = (float*) ptr[7]; b.gate = (float*) ptr[8]; b.o = (float*) ptr[9]; b.z = (float*) ptr[10]; b.y = (float*) ptr[11]; b.y_q8k = (uint8_t*) ptr[12]; b.y_q8_0 = (uint8_t*) ptr[13]; b.state = (float*) ptr[14]; b.conv_state = (float*) ptr[15]; return total;} -void gdn_buffers_zero_state(const GdnBuffers& b, const ModelGeometry& g, void* stream) { const uint64_t st = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size * sizeof(float); const uint64_t cs = (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1) * sizeof(float); cudaMemsetAsync(b.state, 0, st, (cudaStream_t) stream); cudaMemsetAsync(b.conv_state, 0, cs, (cudaStream_t) stream);} -// Forward-declared because `gdn_layer` and `qsa_layer` are both defined above the timer's own definition, and -// the sub-stage marks live inside them. -static void st_begin(int64_t layer, int slot, void* stream); -static void st_end(int64_t layer, int slot, void* stream); -bool gdn_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, const GdnBuffers& b, const float* mixed, float* out, void* stream, std::string& err) { const LayerView v(tables, layer); const int64_t C = g.ssm_conv_channels; -// ---- resolve. Every one of these was shape-checked by `check_layer` at load time, so a miss here is a -// NAME problem and not a geometry one, and the message says which name. -const WeightRef* w_qkv = v.get("attn_qkv.weight"); const WeightRef* w_gate = v.get("attn_gate.weight"); const WeightRef* w_out = v.get("ssm_out.weight"); const WeightRef* w_alpha = v.get("ssm_alpha.weight"); const WeightRef* w_beta = v.get("ssm_beta.weight"); const WeightRef* w_conv = v.get("ssm_conv1d.weight"); const WeightRef* w_norm = v.get("ssm_norm.weight"); const WeightRef* w_dt = v.get("ssm_dt.bias"); const WeightRef* w_a = v.get("ssm_a"); const char* missing = !w_qkv ? "attn_qkv.weight" : !w_gate ? "attn_gate.weight" : !w_out ? "ssm_out.weight" : !w_alpha ? "ssm_alpha.weight" : !w_beta ? "ssm_beta.weight" : !w_conv ? "ssm_conv1d.weight" : !w_norm ? "ssm_norm.weight" : !w_dt ? "ssm_dt.bias" : !w_a ? "ssm_a" : nullptr; if (missing) { err = v.name(missing) + " is missing"; return false; } -// The conv kernel and the two norms are F32 source types, and the loader copied them verbatim - so their -// device bytes ARE f32 and can be handed straight to the kernels that want `const float*`. -const float* conv_kernel = (const float*) w_conv->data; const float* ssm_norm = (const float*) w_norm->data; const float* dt = (const float*) w_dt->data; const float* ssm_a = (const float*) w_a->data; strata::kernels::SForm f_qkv, f_gate, f_out; if (!sform_of(*w_qkv, f_qkv, v.name("attn_qkv.weight"), err)) return false; if (!sform_of(*w_gate, f_gate, v.name("attn_gate.weight"), err)) return false; if (!sform_of(*w_out, f_out, v.name("ssm_out.weight"), err)) return false; Planes p_qkv, p_gate, p_out; if (!plane_ptrs(*w_qkv, v.name("attn_qkv.weight"), p_qkv, err)) return false; if (!plane_ptrs(*w_gate, v.name("attn_gate.weight"), p_gate, err)) return false; if (!plane_ptrs(*w_out, v.name("ssm_out.weight"), p_out, err)) return false; using namespace strata::kernels; cudaStream_t st = (cudaStream_t) stream; -// ---- 1. the activation, in EVERY format a weight on this layer might ask for. BOTH quantized images are -// produced, because which one is wanted is a property of the TENSOR and the pack mixes them by -// layer - producing only the "right" one is how the per-role assumption gets baked back in. -st_begin(layer, 8, stream); - // Plan v0.3 P3: the canonical activation images only when a canonical projection reads them. - if (!w_qkv->native_data || !w_gate->native_data) { - quantize_q8_K(mixed, b.x_q8k, g.n_embd, stream); - quantize_q8_0(mixed, b.x_q8_0, g.n_embd, stream); - } - st_end(layer, 8, stream); -// ---- 2. qkv = wqkv @ x, with the activation THIS layer's `attn_qkv` asks for -st_begin(layer, 9, stream); if (!gemv_quantized(*w_qkv, p_qkv, f_qkv, b.x_q8_0, b.x_q8k, b.qkv, g.n_embd, C, v.name("attn_qkv.weight"), stream, err, mixed)) return false; st_end(layer, 9, stream); -// ---- 3. conv, then SiLU on the WHOLE conv output - before the q|k|v split, which is what -// `ref/gdn.py` L262 says and what makes the split a reshape rather than a copy. -st_begin(layer, 10, stream); -// Plan v0.3 P3: under the native contract, conv + SiLU + both L2 norms are one kernel, and alpha/beta with their -// epilogues another (`fused_gdn.hpp`). -const bool fused_pre = g_fused_gdn && native_gdn_enabled() && native_bf16_projections && g.ssm_d_conv == 4 && - g.ssm_state_size == 128; -if (fused_pre) { - fused_gdn_conv_l2(b.conv_state, b.qkv, conv_kernel, b.h, (int) C, (int) (2 * g.ssm_k_heads), RMS_EPS, stream); -} else -try { - if (native_gdn_enabled()) native_gdn_conv_silu(b.conv_state, b.qkv, conv_kernel, b.conv_out, b.h, C, g.ssm_d_conv, stream); - else { - gdn_conv_step(b.conv_state, b.qkv, conv_kernel, b.conv_out, C, g.ssm_d_conv, stream); - cudaMemcpyAsync(b.h, b.conv_out, (size_t) C * 4, cudaMemcpyDeviceToDevice, st); - silu_inplace(b.h, C, stream); - } -} catch (const std::exception& error) { err = v.name("gdn_conv_silu") + ": " + error.what(); return false; } -st_end(layer, 10, stream); -// ---- 4. q,k = l2_norm; v is NOT normalised. The three views are contiguous runs of the same buffer: -// q at [0, 2048), k at [2048, 4096), v at [4096, 10240), each 128-wide heads. const -st_begin(layer, 11, stream); int64_t qk = g.ssm_state_size * g.ssm_k_heads; -if (!fused_pre) try { - if (native_gdn_enabled()) { - native_gdn_l2_norm(b.h, g.ssm_k_heads, g.ssm_state_size, RMS_EPS, stream); - native_gdn_l2_norm(b.h + qk, g.ssm_k_heads, g.ssm_state_size, RMS_EPS, stream); - } else { - gdn_l2_norm(b.h, g.ssm_k_heads, g.ssm_state_size, RMS_EPS, stream); - gdn_l2_norm(b.h + qk, g.ssm_k_heads, g.ssm_state_size, RMS_EPS, stream); - } -} catch (const std::exception& error) { err = v.name("gdn_l2_norm") + ": " + error.what(); return false; } -// The recurrence needs another 1/sqrt(S) beyond Q/K normalization. The legacy -// recurrence consumes prescaled Q; pinned CUDA applies it after the readout dot. -// Keep the scale at that backend-specific boundary to preserve rounding order. -if (!native_gdn_enabled()) scale_inplace(b.h, qk, 1.0f / std::sqrt((float) g.ssm_state_size), stream); -st_end(layer, 11, stream); -// ---- 5. beta and the gate. The weights are BF16. Native single-token CUDA MMVF -// consumes F32 activations; the legacy path rounds them to BF16 first. -// -// THE ROW-SPLIT FORM, and here the case is stronger than the router's: `ssm_v_heads` is **48**, so -// the plain one-thread-per-row form puts 48 threads on a 48-SM GPU and each walks 2,560 elements -// alone. Measured 0.1072 ms each, against 0.0277 for the split - and there are two of them, in all -// 36 GDN layers. -st_begin(layer, 12, stream); - if (fused_pre) { - fused_gdn_ab(mixed, (const uint16_t*) w_alpha->data, (const uint16_t*) w_beta->data, dt, ssm_a, b.gate, b.beta, - (int) g.n_embd, (int) g.ssm_v_heads, stream); - } else { - if (!native_bf16_projections) f32_to_bf16_bulk(mixed, b.x_bf16, g.n_embd, stream); - project_bf16(mixed, b.x_bf16, (const uint16_t*) w_alpha->data, b.alpha, g.n_embd, g.ssm_v_heads, true, stream); - project_bf16(mixed, b.x_bf16, (const uint16_t*) w_beta->data, b.beta, g.n_embd, g.ssm_v_heads, true, stream); - } - if (!fused_pre) try { - if (native_gdn_enabled()) { - native_gdn_beta_gate(b.beta, g.ssm_v_heads, stream); - native_gdn_gate(b.alpha, dt, ssm_a, b.gate, g.ssm_v_heads, stream); - } else { - gdn_beta_gate(b.beta, g.ssm_v_heads, stream); - gdn_gate(b.alpha, dt, ssm_a, b.gate, 1, g.ssm_v_heads, stream); - } - } catch (const std::exception& error) { err = v.name("gdn_gate") + ": " + error.what(); return false; } - st_end(layer, 12, stream); st_begin(layer, 13, stream); - GdnShapes gs{g.ssm_state_size, g.ssm_k_heads, g.ssm_v_heads}; - // Plan v0.3 P3: with the native contract the step and the output norm are one kernel (after the z GEMV). - const bool fused_gdn = g_fused_gdn && native_gdn_enabled() && g.ssm_state_size == 128; - if (!fused_gdn) try { - if (native_gdn_enabled()) native_gdn_step(b.state, b.h, b.h + qk, b.h + 2 * qk, b.gate, b.beta, b.o, gs, stream); - else gdn_step(b.state, b.h, b.h + qk, b.h + 2 * qk, b.gate, b.beta, b.o, gs, stream); - } catch (const std::exception& error) { - err = v.name("gdn_step") + ": " + error.what(); - return false; - } - st_end(layer, 13, stream); st_begin(layer, 14, stream); -// ---- 6. the recurrence. q and k are the (16, 128) views; v is the (48, 128) view. The stage marks for -// it live at the end of the alpha/beta/gate line above, because the gate and the step are one sequence. -// ---- 7. z, then y = rms_norm(o) * ssm_norm * act(z). SIGMOID for Flash-Next, SiLU for Qwen3.6: `g.gdn_gate()`. -// qkv's native quantize of `mixed` is still in the shared q8_1 scratch: nothing native ran in between. -if (!gemv_quantized(*w_gate, p_gate, f_gate, b.x_q8_0, b.x_q8k, b.z, g.n_embd, g.ssm_value_dim, v.name("attn_gate.weight"), stream, err, mixed, - w_qkv->native_data != nullptr && w_gate->native_data != nullptr)) return false; -try { - if (fused_gdn) fused_gdn_step_norm(b.state, b.h, b.h + qk, b.h + 2 * qk, b.gate, b.beta, b.z, ssm_norm, RMS_EPS, - g.gdn_gate(), b.y, (int) g.ssm_k_heads, (int) g.ssm_v_heads, stream); - else if (native_gdn_enabled()) native_gdn_out_norm(b.o, b.z, ssm_norm, b.y, g.ssm_v_heads, g.ssm_state_size, RMS_EPS, g.gdn_gate(), stream); - else gdn_out_norm(b.o, b.z, ssm_norm, b.y, g.ssm_v_heads, g.ssm_state_size, RMS_EPS, g.gdn_gate(), stream); -} 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 -st_begin(layer, 15, stream); - if (!w_out->native_data) { - quantize_q8_K(b.y, b.y_q8k, g.ssm_value_dim, stream); - quantize_q8_0(b.y, b.y_q8_0, g.ssm_value_dim, stream); - } if (!gemv_quantized(*w_out, p_out, f_out, b.y_q8_0, b.y_q8k, out, g.ssm_value_dim, g.n_embd, v.name("ssm_out.weight"), stream, err, b.y)) return false; st_end(layer, 15, stream); return true;} -// ================================ the MoE block ================================ -uint64_t moe_buffers_bytes(const ModelGeometry& g, int64_t k) { const uint64_t parts[] = { (uint64_t) g.n_embd * 2, -// x_bf16 -(uint64_t) g.n_embd * 2, -// x_f16 -(uint64_t) g.n_expert * 4, -// logits -(uint64_t) k * 4, -// ids (int32) -(uint64_t) k * 4, -// weights -(uint64_t) g.n_embd * 4, -// shared -strata::kernels::shared_expert_scratch_bytes(g.n_ff), -// the shared expert's own scratch -(uint64_t) (g.n_embd / 32) * 34, -// x_q8_0 -q8k_bytes(g.n_embd), -// x_q8k -}; uint64_t total = 0; for (uint64_t v : parts) total += (v + 15) & ~(uint64_t) 15; return total;} -uint64_t moe_buffers_init(const ModelGeometry& g, int64_t k, void* base, MoEBuffers& b) { const uint64_t parts[] = { (uint64_t) g.n_embd * 2, (uint64_t) g.n_embd * 2, (uint64_t) g.n_expert * 4, (uint64_t) k * 4, (uint64_t) k * 4, (uint64_t) g.n_embd * 4, strata::kernels::shared_expert_scratch_bytes(g.n_ff), (uint64_t) (g.n_embd / 32) * 34, q8k_bytes(g.n_embd), }; uint8_t* p = (uint8_t*) base; void* ptr[9]; uint64_t total = 0; for (int i = 0; i < 9; ++i) { ptr[i] = p; const uint64_t al = (parts[i] + 15) & ~(uint64_t) 15; p += al; total += al; } b.x_bf16 = (uint16_t*) ptr[0]; b.x_f16 = (uint16_t*) ptr[1]; b.logits = (float*) ptr[2]; b.ids = (int*) ptr[3]; b.weights = (float*) ptr[4]; b.shared = (float*) ptr[5]; b.sh_scratch = (float*) ptr[6]; b.x_q8_0 = (uint8_t*) ptr[7]; b.x_q8k = (uint8_t*) ptr[8]; return total;} -bool moe_route(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, const float* x, void* stream, std::string& err, const Doorbell* db) { using namespace strata::kernels; const LayerView v(tables, layer); const WeightRef* w_router = v.get("ffn_gate_inp.weight"); if (w_router == nullptr) { err = v.name("ffn_gate_inp.weight") + " is missing"; return false; } if (k < 1 || k > 64) { err = "moe_route: k must be 1..64"; return false; } -// ---- the router's activation. The router's weight is BF16 and that is the one `ref/moe.py` singles out. -if (!native_bf16_projections) f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream); -// ---- logits = ffn_gate_inp @ bf16(x). The weight is BF16, so this is `bf16_gemv` and not `s_gemv` - -// and using the fp16 activation here instead is the 8.100e-03 error that flips a selection. -// -// **THE ROW-SPLIT VARIANT, BECAUSE THE PLAIN ONE'S PARALLELISM IS THE OUTPUT WIDTH.** `bf16_gemv` is -// one thread per output row: for the router that is 512 threads over 48 SMs, each walking 2,560 -// elements sequentially, and it measured **0.2711 ms for a 2.6 MB weight** - about 65x its -// memory-bound floor and the largest single item left inside the MoE after the top-10 was fixed. -// `bf16_gemv_split` exists for precisely this case; its own header says so. Measured here: -// LEDGER L41 -> L42. -project_bf16(x, b.x_bf16, (const uint16_t*) w_router->data, b.logits, g.n_embd, g.n_expert, true, stream); -// ---- routing: softmax over ALL experts, stable descending argsort with ties by index, gather, renormalise -// the native fused router is canonical-512x10 only; anything else takes the generic top-k kernel -if (native_router_enabled() && g.n_expert == 512 && k == 10) { - try { native_router_top10(b.logits, b.ids, b.weights, stream); } - catch (const std::exception& error) { err = v.name("router") + ": " + error.what(); return false; } -} else router_top10(b.logits, 1, (int) g.n_expert, (int) k, b.ids, b.weights, stream); -// ---- THE DOORBELL, AND IT IS THE WHOLE POINT OF THE PROTOCOL. The routed experts' INPUT (`x`) and the -// miss list (`ids`, `weights`) are published to the host HERE, before anything that depends on them, -// so a CPU pool can start on them while the GPU keeps working. Both the copy and the ring are -// captured into `G[l]` like anything else - a kernel writing mapped pinned memory, which round 209 -// measured the host seeing 0.050 ms into a 39.8 ms graph. -if (db != nullptr && g_publish_kernel) { - strata::kernels::doorbell_publish(x, b.ids, b.weights, g.n_embd, k, db->d_x_f, db->d_ids, db->d_weights, db->d_seq, - stream); -} else if (db != nullptr) { if (cudaMemcpyAsync(db->d_x_f, x, (size_t) g.n_embd * 4, cudaMemcpyDeviceToDevice, (cudaStream_t) stream) != cudaSuccess || cudaMemcpyAsync(db->d_ids, b.ids, (size_t) k * 4, cudaMemcpyDeviceToDevice, (cudaStream_t) stream) != cudaSuccess || cudaMemcpyAsync(db->d_weights, b.weights, (size_t) k * 4, cudaMemcpyDeviceToDevice, (cudaStream_t) stream) != cudaSuccess) { err = "moe_route: the doorbell handoff copy failed"; return false; } -// THE RING IS LAST, so a host that sees it knows every byte above is in place. Ordering within a -// stream is what makes that true; it is not a timing assumption. -// THE RING LIVES IN A .cu: this file is compiled by the HOST compiler, where `__global__` and `<<<>>>` do -// not exist. The sequence value is read from the HOST copy and incremented, which is what makes the -// write idempotent across replays of the same graph - a captured literal would ring the same number -// forever and the host would never see a change. -strata::kernels::doorbell_ring(db->d_seq, stream); } return true;} -// The verify window's routing: n tokens' logits in one BF16 projection and their top-k in one launch, each token -// bitwise what `moe_route` gives it (the projection is the same kernel per column, the top-k kernel is per token). -// Anything else (a native router, the canonical BF16 GEMVs, a doorbell) takes the per-token `moe_route`. -bool moe_route_window(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, - const float* x, float* logits, int32_t* ids, float* weights, int n, void* stream, std::string& err) { - using namespace strata::kernels; - const bool batched = native_bf16_projections && !(native_router_enabled() && g.n_expert == 512 && k == 10) && - !std::getenv("STRATA_ROUTE_PER_TOKEN"); - if (!batched || n == 1) { - for (int t = 0; t < n; ++t) { - MoEBuffers mb = b; - mb.logits = logits + t * g.n_expert; mb.ids = ids + t * k; mb.weights = weights + t * k; - if (!moe_route(tables, g, layer, k, mb, x + t * g.n_embd, stream, err, nullptr)) return false; - } - return true; - } - const LayerView v(tables, layer); - const WeightRef* w_router = v.get("ffn_gate_inp.weight"); - if (w_router == nullptr) { err = v.name("ffn_gate_inp.weight") + " is missing"; return false; } - if (std::getenv("STRATA_ROUTE_PROJ_PER_TOKEN")) - for (int t = 0; t < n; ++t) - bf16_gemv_fp32_mmvf(x + t * g.n_embd, (const uint16_t*) w_router->data, logits + t * g.n_expert, g.n_embd, - g.n_expert, stream); - else - bf16_gemv_fp32_mmvf_cols(x, (const uint16_t*) w_router->data, logits, g.n_embd, g.n_expert, n, stream); - router_top10(logits, n, (int) g.n_expert, (int) k, ids, weights, stream); - return true; -} -bool moe_shared(const WeightTable& tables, const ModelGeometry& g, int64_t layer, const MoEBuffers& b, const float* x, void* stream, std::string& err) { using namespace strata::kernels; const LayerView v(tables, layer); const WeightRef* w_ginp = v.get("ffn_gate_inp_shexp.weight"); const WeightRef* w_sgate = v.get("ffn_gate_shexp.weight"); const WeightRef* w_sup = v.get("ffn_up_shexp.weight"); const WeightRef* w_sdown = v.get("ffn_down_shexp.weight"); const char* missing = !w_ginp ? "ffn_gate_inp_shexp.weight" : !w_sgate ? "ffn_gate_shexp.weight" : !w_sup ? "ffn_up_shexp.weight" : !w_sdown ? "ffn_down_shexp.weight" : nullptr; if (missing) { err = v.name(missing) + " is missing"; return false; } -// ---- the shared expert. Its three weights are quantized, so they need their planes. -SForm f_gate, f_up, f_down; if (!sform_of(*w_sgate, f_gate, v.name("ffn_gate_shexp.weight"), err)) return false; if (!sform_of(*w_sup, f_up, v.name("ffn_up_shexp.weight"), err)) return false; if (!sform_of(*w_sdown, f_down, v.name("ffn_down_shexp.weight"), err)) return false; Planes p_gate, p_up, p_down; if (!plane_ptrs(*w_sgate, v.name("ffn_gate_shexp.weight"), p_gate, err)) return false; if (!plane_ptrs(*w_sup, v.name("ffn_up_shexp.weight"), p_up, err)) return false; if (!plane_ptrs(*w_sdown, v.name("ffn_down_shexp.weight"), p_down, err)) return false; -// `ffn_gate_inp_shexp` is a 1-D BF16 vector, so THE ARENA HOLDS 2 BYTES PER ELEMENT, not 4 - the loader -// re-rounded it to the engine form like any other BF16 tensor. Reading it as f32 is 5120 bytes past the -// end of a 5120-byte tensor inside a 4.5 GiB arena, where nothing faults. Refuse here rather than trust -// the layout check to have run: this function is reachable without it. -if (w_ginp->kind != WeightKind::Bf16InF32) { err = v.name("ffn_gate_inp_shexp.weight") + " is engine form " + std::to_string((int) w_ginp->kind) + " (" + std::to_string(w_ginp->bytes) + " B); the scalar gate reads it as bf16, so it must be form 1 (" + std::to_string((uint64_t) g.n_embd * 2) + " B)"; return false; } -// THE SHARED EXPERT'S WEIGHTS ARE NOT ONE FAMILY: `ffn_gate_shexp` is Q2_0 on 21 layers and a K-quant on -// the rest, `ffn_up_shexp` Q2_0 on 13, and `ffn_down_shexp` is LEGACY in every layer (IQ4_NL/Q4_0/Q5_0/ -// Q8_0/Q2_0, `n_in` 640 so Q8_K is impossible). So BOTH quantized images of the activation are produced -// and each projection takes the one its own form asks for. -f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream); - if (!w_sgate->native_data || !w_sup->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); - } - NativeSharedWeights native; - native.gate_type = w_sgate->native_type; native.gate_data = w_sgate->native_data; - native.up_type = w_sup->native_type; native.up_data = w_sup->native_data; - native.down_type = w_sdown->native_type; native.down_data = w_sdown->native_data; - // The NativeDense owner publishes one shared workspace for this ordered session stream. - native.q8_1 = w_sgate->native_q8_1 ? w_sgate->native_q8_1 : - w_sup->native_q8_1 ? w_sup->native_q8_1 : w_sdown->native_q8_1; - try { - shared_expert(b.x_q8_0, b.x_q8k, b.x_bf16, f_gate, p_gate.codes, p_gate.scales, p_gate.offset, - f_up, p_up.codes, p_up.scales, p_up.offset, f_down, p_down.codes, p_down.scales, - p_down.offset, (const uint16_t*) w_ginp->data, b.sh_scratch, b.shared, - g.n_embd, g.n_ff, /*tpr=*/32, stream, x, &native); - } catch (const std::exception& error) { - err = v.name("shared_expert") + ": " + error.what(); - return false; - } - return true; -} -bool moe_combine_parts(const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, const float* parts, - float* out, void* stream, std::string& err) { - using namespace strata::kernels; - if (k < 1 || k > 64) { err = "moe_finish: k must be 1..64"; return false; } - // ---- the combination: sum of w[i] * parts[i], plus the shared output ADDED PLAIN. -// -// **`parts` IS COMBINED WITH `b.weights`, WHICH `moe_route` WROTE FOR *THIS* LAYER.** That is the whole -// reason this is a separate function: a caller that passes the previous layer's expert vectors gets -// `sum_j w_l[j] * expert_{ids_{l-1},j}(x_{l-1})`, which is finite, fluent and not the model. -try { - if (native_moe_combine_enabled()) native_moe_combine(parts, b.weights, b.shared, out, g.n_embd, k, stream); - else moe_combine(parts, b.weights, b.shared, out, g.n_embd, k, stream); -} catch (const std::exception& error) { - err = "blk." + std::to_string(layer) + ".moe_combine" + ": " + error.what(); - return false; -} -return true;} -bool moe_finish(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, - const float* x, const float* parts, float* out, void* stream, std::string& err) { - if (k < 1 || k > 64) { err = "moe_finish: k must be 1..64"; return false; } - if (!moe_shared(tables, g, layer, b, x, stream, err)) return false; - return moe_combine_parts(g, layer, k, b, parts, out, stream, err); -} -bool layer_verify_compatible(const ModelGeometry& g, std::string& why) { - // Plan v0.3 P6: the verify window reproduces exactly this configuration's per-token arithmetic. At hc = 1 the - // block has no hyper-connection read (the plain path, below) and without an indexer no selection to make. - if (!native_bf16_projections) why = "the native BF16 projections are off"; - else if (g.hc > 1 && !g_fused_gr) why = "the fused hyper-connection read is off"; - else if (!g_fused_gdn || !strata::kernels::native_gdn_enabled()) why = "the fused native GDN kernels are off"; - else if (!g_fast_attn || native_flash_attn_short) why = "the split-K decode attention is off"; - else if (g.has_indexer() && !g_fast_select) why = "the block top-k selection is off"; - else if (g.has_indexer() && !strata::kernels::native_qsa_indexer_enabled()) why = "the native QSA indexer is off"; - else 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; } -void layer_set_fast_attn(bool enabled) { g_fast_attn = enabled; } -void layer_set_fused_gr(bool enabled) { g_fused_gr = enabled; } -bool layer_fused_gr() { return g_fused_gr; } -void layer_set_shared_early(bool enabled) { g_shared_early = enabled; } -bool layer_shared_early() { return g_shared_early; } -bool moe_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, const float* x, const float* parts, float* out, void* stream, std::string& err, const Doorbell* db) { -// The two halves in sequence. `moe_route` publishes `ids`/`weights` for THIS layer and `moe_finish` -// combines `parts` with them, so a caller of this wrapper must have `parts` ready BEFORE the call - which -// is what `session_token` (the uncaptured path) does and what the captured loop CANNOT, which is why the -// loop uses the halves separately. -if (!moe_route(tables, g, layer, k, b, x, stream, err, db)) return false; return moe_finish(tables, g, layer, k, b, x, parts, out, stream, err);} -// ================================ the QSA mixer ================================ -namespace {using strata::kernels::QsaIndexerBuffers;using strata::kernels::QsaShapes; -/// The geometry the QSA kernels want, from the one place that defines it. `ModelGeometry` carries the widths -/// the LAYOUT needs; `QsaShapes` adds `n_rot`, `idx_block` and `idx_top_k`, which are kernel contracts. -using strata::core::qsa_shapes; // the one builder (strata/core/qsa_shapes.hpp): dense = the three indexer widths zero -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 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; }}; -// `TPR` and `gemv_quantized` live in the FIRST anonymous namespace, above, because `gdn_layer` needs the -// dispatch too and the two must not be able to drift. -} -// namespace -namespace { -// KV streaming (docs/kv-streaming-design.md): 0 keeps every cell in VRAM. -int64_t g_kv_resident = 0; -uint64_t g_kv_host_bytes = 0; - -/// How one state holds its K/V: `mode` as in QsaState::kv_mode, `slots` VRAM pages of `pages` logical ones. -struct KvPlan { - int mode = 0; - int64_t pages = 0, slots = 0, pooled_rows = 0; -}; -KvPlan kv_plan(const QsaShapes& s, int64_t max_cells, int64_t ring_cells) { - KvPlan p; - p.pages = (max_cells + s.page_size - 1) / s.page_size; - p.slots = p.pages; - p.pooled_rows = strata::kernels::qsa_dense(s) ? 2 : max_cells / s.idx_block + 2; // dense: as the ring, no indexer - 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; - static const bool main_off = std::getenv("STRATA_KV_MAIN_OFF") != nullptr; - if (ring_cells > 0 ? ring_off : main_off) return p; - if (ring_cells > 0) { - const int64_t r = (ring_cells + s.page_size - 1) / s.page_size; - if (r < p.pages) { p.mode = 2; p.slots = r; p.pooled_rows = 2; } // the drafter has no indexer - } else { - const int64_t r = (std::max(g_kv_resident, qsa_kv_resident_min()) + s.page_size - 1) / s.page_size; - if (r < p.pages) { p.mode = 1; p.slots = r; } - } - return p; -} -uint64_t kv_pool_bytes(const QsaShapes& s, int64_t pages, bool hybrid, bool int8) { - if (hybrid) { // K8V4: the INT8 K half (codes + scales) plus the Q4_0 V half (kv_q4.hpp's rotation) - const uint64_t rows = (uint64_t) pages * s.page_size * s.n_head_kv; - return rows * (uint64_t) s.head_dim + rows * (uint64_t) (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2 + - rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim) + 64; - } - if (g_kv_q4) return (uint64_t) pages * s.page_size * strata::kernels::kv_q4_bytes_per_cell(s) + 64; - return int8 ? (uint64_t) pages * s.page_size * strata::kernels::kv_q8_bytes_per_cell(s) + 64 - : (uint64_t) pages * s.n_head_kv * s.page_size * s.head_dim * 2 * 2; -} -} // 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; } - -uint64_t qsa_state_bytes(const ModelGeometry& g, int64_t max_cells, bool with_rope, int64_t ring_cells) { - const QsaShapes s = qsa_shapes(g); - const KvPlan p = kv_plan(s, max_cells, ring_cells); - uint64_t n = 0; - n += kv_pool_bytes(s, p.slots, g_kv_hybrid && ring_cells <= 0, - g_kv_int8 || g_kv_hybrid) + 4 * 16; // K/V pools (the VRAM slots) - n += (uint64_t) p.pages * 4; // page_table - if (p.mode == 1) n += strata::kernels::kv_stream_map_bytes(p.slots) + 6 * 16; // the residency map - n += (uint64_t) (s.idx_block - 1) * s.idx_dim * 4; // tail - n += (uint64_t) s.idx_dim * 4; // dead - n += (uint64_t) p.pooled_rows * s.idx_dim * 4; // pooled - n += 16; // block_pos - if (with_rope) n += (uint64_t) max_cells * (s.n_rot / 2) * 4 * 2; // cos + sin tables - n += strata::kernels::qsa_step_bytes() + 16; // counts and aligned attention status - n += (uint64_t) s.n_head * 4; // pos_dev - return align_up16(n) + 256; -} - -uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaState& st, - const QsaState* share_rope, int64_t ring_cells) { - const QsaShapes s = qsa_shapes(g); - const KvPlan p = kv_plan(s, max_cells, ring_cells); - const int64_t pages = p.pages; - Cursor c{(uint8_t*) base}; - st.kv_int8 = g_kv_int8 && !g_kv_q4; - 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"); - return 0; - } - st.kv_hybrid = true; - st.kv_int8 = false; - st.kv_q4 = false; - } - st.kv_rot = st.kv_q4 || (st.kv_int8 && g_kv_int8_rot); // K8V4 rotates only V (below) - st.kv_mode = p.mode; - st.n_slots = p.slots; - const uint64_t rows = (uint64_t) p.slots * s.n_head_kv * s.page_size; // VRAM rows: the slots - const uint64_t q4_row = strata::kernels::kv_q4_bytes_per_head((int) s.head_dim); - if (st.kv_hybrid) { - st.k_q = c.take(rows * s.head_dim); - st.k_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); - st.v_q4 = c.take(rows * q4_row); - } else if (st.kv_q4) { - st.k_q4 = c.take(rows * q4_row); - st.v_q4 = c.take(rows * q4_row); - } else if (st.kv_int8) { // st, not the global: the drafter's ring is INT8 under --kv k8v4 too - st.k_q = c.take(rows * s.head_dim); - st.v_q = c.take(rows * s.head_dim); - st.k_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); - st.v_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); - } else { - st.k_pool = c.take(rows * s.head_dim); - st.v_pool = c.take(rows * s.head_dim); - } - st.page_table = c.take((uint64_t) pages); - st.n_pages = pages; - st.max_cells = max_cells; - st.map = strata::kernels::KvStreamMap{}; - st.map.page_table = st.page_table; - st.map.n_blocks = pages; - st.map.n_slots = p.slots; - if (p.mode == 1) { - st.map.slot_block = c.take((uint64_t) p.slots); - st.map.slot_stamp = c.take((uint64_t) p.slots); - st.map.slot_ref = c.take((uint64_t) p.slots); - st.map.miss_block = c.take((uint64_t) p.slots); - st.map.miss_slot = c.take((uint64_t) p.slots); - st.map.ctl = c.take((uint64_t) strata::kernels::kKvCtlInts); - } - st.idx_tail = c.take((uint64_t) (s.idx_block - 1) * s.idx_dim); - st.idx_dead = c.take((uint64_t) s.idx_dim); - st.idx_pooled_rows = p.pooled_rows; - st.idx_pooled = c.take((uint64_t) p.pooled_rows * s.idx_dim); - st.idx_block_pos = c.take(1); - if (share_rope != nullptr) { - st.cos_tab = share_rope->cos_tab; - st.sin_tab = share_rope->sin_tab; - } else { - st.cos_tab = c.take((uint64_t) max_cells * (s.n_rot / 2)); - st.sin_tab = c.take((uint64_t) max_cells * (s.n_rot / 2)); - } - st.step = c.take((uint64_t) strata::kernels::kStepCount); - st.attention_status = c.take(1); - st.pos_dev = c.take((uint64_t) s.n_head); - // the pinned staging the uploads copy FROM - see the note on `host_step` in the header - if (cudaHostAlloc((void**) &st.host_step, strata::kernels::qsa_step_bytes() + sizeof(int32_t), - cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess || - cudaHostAlloc((void**) &st.host_pos, (size_t) s.n_head * 4, cudaHostAllocMapped | cudaHostAllocPortable) != - cudaSuccess) { - return 0; // the caller sees a zero byte count; a half-built state is worse than none - } - st.host_step[strata::kernels::kStepCount] = 0; - // KV streaming: the authoritative K/V of every cell, pinned and device-mapped, in the identity layout - st.host = strata::kernels::KvHostPools{}; - if (p.mode != 0) { - const uint64_t hrows = (uint64_t) pages * s.n_head_kv * s.page_size; - const uint64_t bytes = (uint64_t) pages * strata::kernels::kv_block_bytes(s, qsa_kv_format(st)) + 4 * 256; - uint8_t* h = nullptr; - uint8_t* d = nullptr; - if (cudaHostAlloc((void**) &h, bytes, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess || - cudaHostGetDevicePointer((void**) &d, h, 0) != cudaSuccess) { - // under WSL the NVIDIA driver pins only ~1 GiB in all, which is less than 128K of 8-bit KV needs - if (p.mode == 1) std::fprintf(stderr, "strata: KV streaming: cannot pin %.2f GiB of RAM for a layer's KV copy " - "(%.2f GiB pinned so far) - lower the context, or run without --kv-resident (under " - "WSL the driver pins only about 1 GiB in all)\n", (double) bytes / 1073741824.0, - (double) g_kv_host_bytes / 1073741824.0); - return 0; - } - g_kv_host_bytes += bytes; - Cursor hc{d}; - if (st.kv_q4) { - st.host.k_q4 = hc.take(hrows * q4_row); - st.host.v_q4 = hc.take(hrows * q4_row); - } else if (st.kv_int8) { - st.host.k_q = hc.take(hrows * s.head_dim); - st.host.v_q = hc.take(hrows * s.head_dim); - st.host.k_scale = hc.take(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); - st.host.v_scale = hc.take(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); - } else { - st.host.k_pool = hc.take(hrows * s.head_dim); - st.host.v_pool = hc.take(hrows * s.head_dim); - } - } - // THE ROPE TABLE IS BUILT ON THE HOST IN FLOAT64 and uploaded once, because the reference computes its - // frequencies in float64 and reproducing that on device means double-precision `pow`/`cos` that need not - // agree with the host's libm. A table shorter than the sequence would have the rotation read past it. - // The process's rope scaling (none by default) is INSIDE the table - the rotation kernels cannot tell. - if (share_rope == nullptr) { - std::vector hc((size_t) max_cells * (s.n_rot / 2)), hs((size_t) max_cells * (s.n_rot / 2)); - strata::kernels::build_rope_table((int) s.n_rot, strata::kernels::rope_scaling(), (int) max_cells, - hc.data(), hs.data()); - cudaMemcpy(st.cos_tab, hc.data(), hc.size() * 4, cudaMemcpyHostToDevice); - cudaMemcpy(st.sin_tab, hs.data(), hs.size() * 4, cudaMemcpyHostToDevice); - st.owns_rope = true; - if (s.n_rot == 64) // the native and prompt-path rope kernels read it (mrope.hpp, STRATA_ROPE_TABLE=1) - strata::kernels::rope_table_set(st.cos_tab, st.sin_tab, (int) max_cells, strata::kernels::rope_scaling()); - } - // the page table starts as the IDENTITY, which is the simplest legal mapping and what a caller that does - // not page at all wants; a streamed state starts with nothing resident, a ring at `block % n_slots`. - if (p.mode == 0) { - std::vector tab((size_t) pages); - for (int64_t i = 0; i < pages; ++i) tab[(size_t) i] = (int32_t) i; - cudaMemcpy(st.page_table, tab.data(), tab.size() * 4, cudaMemcpyHostToDevice); - } else if (p.mode == 1) { - strata::kernels::kv_stream_reset(st.map, nullptr); - } else { - strata::kernels::kv_ring_table(st.page_table, pages, p.slots, nullptr); - } - cudaDeviceSynchronize(); - return c.used; -} - -void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream) { - const QsaShapes s = qsa_shapes(g); - cudaStream_t cs = (cudaStream_t) stream; - const size_t rows = (size_t) st.n_slots * s.n_head_kv * s.page_size; - if (st.kv_hybrid) { - cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); - cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); - cudaMemsetAsync(st.v_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); - } else if (st.kv_q4) { - cudaMemsetAsync(st.k_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); - cudaMemsetAsync(st.v_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); - } else if (st.kv_int8) { - cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); - cudaMemsetAsync(st.v_q, 0, rows * s.head_dim, cs); - cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); - cudaMemsetAsync(st.v_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); - } else { - cudaMemsetAsync(st.k_pool, 0, rows * s.head_dim * 2, cs); - cudaMemsetAsync(st.v_pool, 0, rows * s.head_dim * 2, cs); - } - // A streamed state starts over with nothing resident. Its host copy is not cleared (GBs over PCIe per new - // conversation): no reader names a cell before this sequence has written it, and a block copied in whole - // carries the unwritten cells past the end, which nothing reads. - if (st.kv_mode == 1) strata::kernels::kv_stream_reset(st.map, stream); - cudaMemsetAsync(st.idx_tail, 0, (size_t) (s.idx_block - 1) * s.idx_dim * 4, cs); - cudaMemsetAsync(st.idx_dead, 0, (size_t) s.idx_dim * 4, cs); - cudaMemsetAsync(st.idx_pooled, 0, (size_t) st.idx_pooled_rows * s.idx_dim * 4, cs); -} - -strata::kernels::QsaAttnPools qsa_attn_pools(const QsaState& st) { - strata::kernels::QsaAttnPools pools; - pools.page_table = st.page_table; - if (st.kv_hybrid) { pools.k_q = st.k_q; pools.k_scale = st.k_scale; pools.v_q4 = st.v_q4; } - else if (st.kv_q4) { pools.k_q4 = st.k_q4; pools.v_q4 = st.v_q4; } - else if (st.kv_int8) { pools.k_q = st.k_q; pools.v_q = st.v_q; pools.k_scale = st.k_scale; pools.v_scale = st.v_scale; } - else { pools.k_pool = st.k_pool; pools.v_pool = st.v_pool; } - return pools; -} - -void qsa_kv_resolve(const QsaState& st, const ModelGeometry& g, const int32_t* ids, const int32_t* steps, int64_t n_q, - int64_t cap, void* stream) { - if (st.kv_mode != 1) return; - strata::kernels::kv_stream_resolve(st.map, qsa_attn_pools(st), st.host, qsa_kv_format(st), ids, steps, n_q, cap, - qsa_shapes(g), stream); -} - -uint64_t qsa_buffers_bytes(const ModelGeometry& g, int64_t max_cells) { const QsaShapes s = qsa_shapes(g); const int64_t cap = strata::kernels::qsa_selection_cap(max_cells, s); const bool dense = strata::kernels::qsa_dense(s); uint64_t n = 0; n += (uint64_t) q8k_bytes(g.n_embd); n += (uint64_t) (g.n_embd / 32) * 34; -// block_q8_0 -n += (uint64_t) g.n_embd * 2; n += (uint64_t) g.n_head * 2 * g.head_dim * 4; n += (uint64_t) g.n_head * g.head_dim * 4; n += (uint64_t) g.n_head_kv * g.head_dim * 4 * 2; n += (uint64_t) g.idx_key_dim * 4; n += (uint64_t) g.idx_q_heads * g.idx_key_dim * 4; - // dense attention has no cell scores, no ids (a null is the identity) and no gather scratch (the split-K kernel - // reads the pools): at 262,144 cells those three would be 1 + 1 + 512 MiB - if (!dense) { n += (uint64_t) max_cells * 4; n += (uint64_t) cap * 4; n += (uint64_t) cap * g.n_head_kv * g.head_dim * 2 * 2; } - n += (uint64_t) g.n_head * g.head_dim * 4; -// attn -n += (uint64_t) g.n_head * g.head_dim * 2; -// attn16 -n += (uint64_t) g.n_head * g.head_dim * 4; -// attn32 -n += (uint64_t) q8k_bytes(g.n_head * g.head_dim); -// attn_q8k -n += strata::kernels::qsa_decode_attn_scratch_floats(cap, s) * 4 + 16; -// attn_scratch -return align_up16(n) + 256;} -uint64_t qsa_buffers_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaBuffers& b) { const QsaShapes s = qsa_shapes(g); const int64_t cap = strata::kernels::qsa_selection_cap(max_cells, s); const bool dense = strata::kernels::qsa_dense(s); Cursor c{(uint8_t*) base}; b.x_q8k = c.take_bytes(q8k_bytes(g.n_embd)); b.x_q8_0 = c.take_bytes((uint64_t) (g.n_embd / 32) * 34); b.x_bf16 = c.take((uint64_t) g.n_embd); b.q_full = c.take((uint64_t) g.n_head * 2 * g.head_dim); b.qcur = c.take((uint64_t) g.n_head * g.head_dim); b.kcur = c.take((uint64_t) g.n_head_kv * g.head_dim); b.vcur = c.take((uint64_t) g.n_head_kv * g.head_dim); b.idx_raw = c.take((uint64_t) g.idx_key_dim); b.q_idx = c.take((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((uint64_t) max_cells); b.ids = c.take((uint64_t) cap); b.k_scratch = c.take((uint64_t) cap * g.n_head_kv * g.head_dim); b.v_scratch = c.take((uint64_t) cap * g.n_head_kv * g.head_dim); } b.attn = c.take((uint64_t) g.n_head * g.head_dim); b.attn16 = c.take((uint64_t) g.n_head * g.head_dim); b.attn32 = c.take((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(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 -// THAN HALF OF THAT.** `dense_pass.exe` puts all 302 dense GEMVs at 11.64 ms/token and the 1.377 GiB of -// BF16/F32 weights they exclude at another ~5.9, so ~17.5 ms of the 50.25 ms captured no-pool floor is -// accounted for and ~33 ms is not. Arithmetic has already discounted the obvious candidates - the GDN -// recurrence moves 6.2 MB of state per token, the QSA attention at 1,024 tokens is 75M MACs over twelve -// layers, and `gr_norm_kernel`'s 4-block launch moves 40 KB - so the attribution has to come from the engine. -// -// Event pairs are recorded per (layer, stage) and read once at the end, so **NOTHING IS SYNCHRONISED DURING -// THE RUN** and the measurement does not perturb what it measures. That matters here more than usual: a -// per-stage `cudaEventSynchronize` would serialise the pipeline and report the serialised time. -// -// **IT CANNOT BE USED WITH CAPTURED GRAPHS.** An event record inside a stream capture is silently dropped -// (round 199: 2 nodes for two kernels plus an event record, and the event never completed across a 41 ms -// graph), so this is gated on the `--no-capture` path where the layers are ordinary launches. -constexpr int STAGE_SLOTS = 20; - -struct StageTimer { - bool on = false; - cudaEvent_t a[64][STAGE_SLOTS] = {}; - cudaEvent_t b[64][STAGE_SLOTS] = {}; - const char* names[STAGE_SLOTS] = {}; - int nslots = 0; -}; - -static StageTimer g_st; - -bool stage_timing_enable() { - if (g_st.on) return true; - for (int l = 0; l < 64; ++l) { - for (int s = 0; s < STAGE_SLOTS; ++s) { - if (cudaEventCreate(&g_st.a[l][s]) != cudaSuccess) return false; - if (cudaEventCreate(&g_st.b[l][s]) != cudaSuccess) return false; - } - } - g_st.on = true; - return true; -} - -void stage_timing_name(int slot, const char* name) { - if (slot >= 0 && slot < STAGE_SLOTS) { - g_st.names[slot] = name; - if (slot + 1 > g_st.nslots) g_st.nslots = slot + 1; - } -} - -void stage_mark_begin(int64_t layer, int slot, void* stream) { st_begin(layer, slot, stream); } -void stage_mark_end(int64_t layer, int slot, void* stream) { st_end(layer, slot, stream); } - -static void st_begin(int64_t layer, int slot, void* stream) { - if (g_st.on && layer < 64) cudaEventRecord(g_st.a[layer][slot], (cudaStream_t) stream); -} - -static void st_end(int64_t layer, int slot, void* stream) { - if (g_st.on && layer < 64) cudaEventRecord(g_st.b[layer][slot], (cudaStream_t) stream); -} - -void stage_timing_report(int64_t n_layers) { - if (!g_st.on) return; - cudaDeviceSynchronize(); - double tot[STAGE_SLOTS] = {}; - for (int s = 0; s < g_st.nslots; ++s) { - for (int64_t l = 0; l < n_layers && l < 64; ++l) { - float ms = 0.0f; - if (cudaEventElapsedTime(&ms, g_st.a[l][s], g_st.b[l][s]) == cudaSuccess) tot[s] += (double) ms; - } - } - double sum = 0; - for (int s = 0; s < g_st.nslots; ++s) sum += tot[s]; - std::fprintf(stderr, "\nper-stage GPU time, summed over %lld layers (one token):\n", (long long) n_layers); - for (int s = 0; s < g_st.nslots; ++s) { - std::fprintf(stderr, " %-22s %8.3f ms/token %6.3f ms/layer %5.1f%%\n", - g_st.names[s] ? g_st.names[s] : "(unnamed)", tot[s], tot[s] / (double) n_layers, - sum > 0 ? 100.0 * tot[s] / sum : 0.0); - } - std::fprintf(stderr, " %-22s %8.3f ms/token\n", "sum of stages", sum); - // ---- THE PER-LAYER SPLIT, because the attention block is 55% of the token and the engine mixes two - // entirely different attention implementations: GDN on 36 layers and QSA on the twelve where - // `full_attention_interval` divides the index. A single total cannot say which one is expensive, and the - // two have nothing in common to optimise. - std::fprintf(stderr, "\nper-layer, the attention block (ms). A `*` marks a QSA layer:\n"); - double gdn = 0, qsa = 0; - int ng = 0, nq = 0; - for (int64_t l = 0; l < n_layers && l < 64; ++l) { - float ms = 0.0f; - if (cudaEventElapsedTime(&ms, g_st.a[l][1], g_st.b[l][1]) != cudaSuccess) continue; - const bool is_qsa = (l % 4) == 3; - if (is_qsa) { qsa += ms; ++nq; } else { gdn += ms; ++ng; } - std::fprintf(stderr, " %s%2lld %7.3f%s", is_qsa ? "*" : " ", (long long) l, (double) ms, - ((l + 1) % 8 == 0) ? "\n" : ""); - } - std::fprintf(stderr, "\n GDN: %d layers, %.3f ms total, %.4f ms/layer\n", ng, gdn, ng ? gdn / ng : 0.0); - std::fprintf(stderr, " QSA: %d layers, %.3f ms total, %.4f ms/layer\n", nq, qsa, nq ? qsa / nq : 0.0); -} - -// Declared here because `qsa_layer` is defined above `block_layer_pre`, where the body lives. The dump buffer -// is a plain host pointer and the copy is a graph node of whichever layer's capture is running, so the helper -// needs nothing from the layer it is called for beyond its index. -static void dump_slot(float* dump, const ModelGeometry& g, int64_t layer, const float* src, uint64_t off, - uint64_t n, void* stream); -bool qsa_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, const QsaState& st, const QsaBuffers& b, const float* x, float* out, void* stream, std::string& err, float* dump) { using namespace strata::kernels; const QsaShapes s = qsa_shapes(g); const LayerView v(tables, layer); const int64_t n_kv = pos + 1; /* P7 audit: RoPE reads cos/sin row pos_base + pos, and the table holds max_cells rows. */ if ((int64_t) pos_base + pos >= st.max_cells || pos_base < 0) { err = "qsa_layer: position " + std::to_string((long long) pos_base + pos) + " is outside the RoPE table (" + std::to_string((long long) st.max_cells) + " rows)"; return false; } const int64_t n_bid = n_kv / s.idx_block; const int64_t width = qsa_selection_width(n_kv, s); const int64_t cap = qsa_selection_cap(st.max_cells, s); - // Qwen3.6 (3.3): dense attention. No indexer tensors, no raw key, no pooled scores, no top-k: the split-K - // kernel reads every cell (a null `ids` is the identity) with the width n_kv from the step. - const bool has_idx = g.has_indexer(); -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); - else rms_norm_weighted(data, (const float*) norm->data, rows, cols, RMS_EPS, stream); - if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), st.pos_dev, stream); - else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, st.pos_dev, stream); - return true; - } catch (const std::exception& error) { - err = v.name("qsa_norm_rope") + ": " + error.what(); - return false; - } -}; -// ---- resolve every tensor by name, and REFUSE rather than reading a null. `check_layer` has already -// asserted the shapes at load time; a missing name here is a wiring mistake. -struct Req { const char* suf; }; const WeightRef* w_idxk = v.get("indexer.k_proj.weight"); const WeightRef* w_attnq = v.get("attn_q.weight"); const WeightRef* w_attnk = v.get("attn_k.weight"); const WeightRef* w_attnv = v.get("attn_v.weight"); const WeightRef* w_attno = v.get("attn_output.weight"); const WeightRef* w_idxq = v.get("indexer.q_proj.weight"); const WeightRef* w_qn = v.get("attn_q_norm.weight"); const WeightRef* w_kn = v.get("attn_k_norm.weight"); const WeightRef* w_iqn = v.get("indexer.q_norm.weight"); const WeightRef* w_ikn = v.get("indexer.k_norm.weight"); const char* missing = (has_idx && !w_idxk) ? "indexer.k_proj.weight" : !w_attnq ? "attn_q.weight" : !w_attnk ? "attn_k.weight" : !w_attnv ? "attn_v.weight" : !w_attno ? "attn_output.weight" : (has_idx && !w_idxq) ? "indexer.q_proj.weight" : !w_qn ? "attn_q_norm.weight" : !w_kn ? "attn_k_norm.weight" : (has_idx && !w_iqn) ? "indexer.q_norm.weight" : (has_idx && !w_ikn) ? "indexer.k_norm.weight" : nullptr; if (missing) { err = v.name(missing) + " is missing"; return false; } if (pos < 0 || pos >= st.max_cells) { err = "qsa_layer: pos " + std::to_string(pos) + " is outside the state's 0.." + std::to_string(st.max_cells - 1); return false; } -// THE TWO BF16 PROJECTIONS: the arena holds them re-rounded to 2 B/elem, which is what `bf16_gemv` wants. -// Reading one as f32 would walk 2x its length inside the arena without faulting. -if (has_idx && (w_idxk->kind != WeightKind::Bf16InF32 || w_idxq->kind != WeightKind::Bf16InF32)) { err = v.name("indexer.*_proj.weight") + " must be engine form 1 (bf16); they are " + std::to_string((int) w_idxk->kind) + " and " + std::to_string((int) w_idxq->kind); return false; } -// ---- 1. the three activation formats, once each -if (!w_attnk->native_data || !w_attnv->native_data || !w_attnq->native_data) { - quantize_q8_K(x, b.x_q8k, g.n_embd, stream); - quantize_q8_0(x, b.x_q8_0, g.n_embd, stream); - } - if (!native_bf16_projections && has_idx) f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream); -// ---- 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. -// -// THE SOURCES ARE `st.host_step`/`st.host_pos`, WHICH LIVE AS LONG AS THE STATE DOES. A stack array or a -// local vector here would be captured as a dangling POINTER and replayed as garbage - see the note in -// `layer.hpp`. That is a silent failure, not a fault: the copy succeeds, the counts are wrong, and the -// token that comes out is plausible. -{ qsa_step_fill(st.host_step, pos, s); for (int64_t h = 0; h < g.n_head; ++h) st.host_pos[h] = (int32_t) (pos_base + pos); - int32_t* m_step = nullptr; - int32_t* m_pos = nullptr; - if (g_publish_kernel && cudaHostGetDevicePointer((void**) &m_step, st.host_step, 0) == cudaSuccess && - cudaHostGetDevicePointer((void**) &m_pos, st.host_pos, 0) == cudaSuccess) { - strata::kernels::copy_i32_from_mapped(st.step, m_step, strata::kernels::kStepCount, stream); - strata::kernels::copy_i32_from_mapped(st.pos_dev, m_pos, g.n_head, stream); - } else - if (cudaMemcpyAsync(st.step, st.host_step, qsa_step_bytes(), cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess || cudaMemcpyAsync(st.pos_dev, st.host_pos, (size_t) g.n_head * 4, cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess) { err = "qsa_layer: the step-state upload failed"; return false; } } -// ---- 3. the indexer's RAW key: appended before any norm, pooled later once per block -if (has_idx) project_bf16(x, b.x_bf16, (const uint16_t*) w_idxk->data, b.idx_raw, g.n_embd, g.idx_key_dim, false, stream); -// ---- 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 -// artifact, but the dispatch is here for the same reason it is in `gdn_layer`: the pack decides per tensor, -// and "it happens to be uniform here" is the assumption that was wrong for `attn_q`. -if (!gemv_quantized(*w_attnk, p_k, f_k, b.x_q8_0, b.x_q8k, b.kcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_k.weight"), stream, err, x)) return false; if (!gemv_quantized(*w_attnv, p_v, f_v, b.x_q8_0, b.x_q8k, b.vcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_v.weight"), stream, err, x, w_attnk->native_data && w_attnv->native_data)) return false; dump_slot(dump, g, layer, b.vcur, (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim, (uint64_t) g.n_head_kv * g.head_dim, stream); if (!normalize_rotate(b.kcur, w_kn, (int) g.n_head_kv, (int) g.head_dim)) return false; -// ---- 5. into the cache, and the indexer's append (which pools AND rotates on a block completion). -// EVERY ENTRY POINT FROM HERE ON IS THE CAPTURABLE ONE: the per-token counts come from `st.step` and every -// launch is sized from a capacity in `st`/`b`, so this sequence can be captured and replayed. The -// host-scalar wrappers would be correct here today and silently wrong in a graph. -if (st.kv_hybrid) { - // K8V4: only V is rotated (kv_q4.hpp's H); the scores pair unrotated q with unrotated INT8 K, and the - // output - a mix of rotated values - is rotated back after attention. Each append/gather call folds the - // unused half's lanes onto the used pool (a bit-identical duplicate write), so no kernel variants exist. - strata::kernels::fwht256_inplace_cuda(b.vcur, g.n_head_kv, stream); - kv_append_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, st.step, b.kcur, b.kcur, s, stream, nullptr); // mode 0: no host mirror - strata::kernels::kv_append_q4_step(st.v_q4, st.v_q4, st.page_table, st.step, b.vcur, b.vcur, s, stream, nullptr); -} else { -if (st.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1 - strata::kernels::fwht256_inplace_cuda(b.kcur, g.n_head_kv, stream); - strata::kernels::fwht256_inplace_cuda(b.vcur, g.n_head_kv, stream); -} -if (st.kv_q4) { - strata::kernels::kv_append_q4_step(st.k_q4, st.v_q4, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); -} else if (st.kv_int8) kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); else kv_append_step(st.k_pool, st.v_pool, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); } /* not K8V4 */ { const uint64_t nvk = (uint64_t) g.n_head_kv * g.head_dim; const uint64_t base = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + 2 * nvk + 8; if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.k_pool, base, nvk / 2, stream); if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.v_pool, base + nvk / 2, nvk / 2, stream); dump_slot(dump, g, layer, b.vcur, base + nvk, nvk, stream); dump_slot(dump, g, layer, b.kcur, base + 2 * nvk, nvk, stream); } if (has_idx) { const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; if (native_qsa_indexer_enabled()) { - 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); - } catch (const std::exception& error) { err = v.name("native_indexer") + ": " + error.what(); return false; } -} else indexer_key_append(b.idx_raw, st.pos_dev, pos_base, (const float*) w_ikn->data, RMS_EPS, ib, s, - st.cos_tab, st.sin_tab, stream); } -// ---- 6. the query projection, and the HALF-SPLIT into q and gate. -// -// **`attn_q` IS *NOT* ALWAYS Q2_0.** It is Q2_0 on TWO of the twelve QSA layers, Q3_K on six and IQ4_XS on -// four, and this line used to call `s2_gemv_q8` unconditionally - so TEN of the twelve layers decoded an -// S4 code plane with a Q8_0 activation. Both are "a quantized activation", both produce a plausible -// vector, and the difference is 0.6-1.4%. -if (!gemv_quantized(*w_attnq, p_q, f_q, b.x_q8_0, b.x_q8k, b.q_full, g.n_embd, g.n_head * 2 * g.head_dim, v.name("attn_q.weight"), stream, err, x, w_attnv->native_data && w_attnq->native_data)) return false; -// `per_head[:, :head_dim]` - the FIRST half of each head's 2*head_dim block, copied out contiguously so -// the norm and the rotation see whole rows. A 2-D copy is a memcpy node, which captures (`pinned_capture` -// 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); // = - 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); - qsa_block_topk(b.cell_scores, st.step, 1, max_blocks, cap, s, b.ids, stream); - } else { - qsa_index_step(st.idx_pooled, b.q_idx, nullptr, s, st.step, max_blocks, b.cell_scores, stream); topk_512_step(b.cell_scores, s, cap, st.step, b.ids, stream); - } - // KV streaming: every block the selection names is made resident before anything reads it - qsa_kv_resolve(st, g, b.ids, st.step, 1, cap, stream); - if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(b.qcur, g.n_head, stream); // = - if (g_fast_attn && !native_flash_attn_short && dump == nullptr) { - const strata::kernels::QsaAttnPools pools = qsa_attn_pools(st); - strata::kernels::qsa_decode_attn_step(b.qcur, pools, b.ids, st.step, cap, s, b.attn_scratch, b.attn, stream); - } else { - if (st.kv_hybrid) { - kv_gather_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, b.ids, st.step, cap, s, - b.k_scratch, b.k_scratch, stream); - strata::kernels::kv_gather_q4_step(st.v_q4, st.v_q4, st.page_table, b.ids, st.step, cap, s, - b.v_scratch, b.v_scratch, stream); - } - else if (st.kv_q4) strata::kernels::kv_gather_q4_step(st.k_q4, st.v_q4, st.page_table, b.ids, st.step, cap, s, b.k_scratch, b.v_scratch, stream); - else if (st.kv_int8) kv_gather_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, b.ids, st.step, cap, s, b.k_scratch, b.v_scratch, stream); else kv_gather_step(st.k_pool, st.v_pool, st.page_table, b.ids, st.step, cap, s, b.k_scratch, b.v_scratch, stream); if (native_flash_attn_short) { - if (st.max_cells < 1 || st.max_cells > 256 || !st.attention_status || !st.host_step) { - err = v.name("native_flash_attn") + ": short adapter requires context <=256 and persistent status storage"; - return false; - } - try { - native_flash_attn_short_step(b.qcur, b.k_scratch, b.v_scratch, st.step, cap, - (int) st.max_cells, s, b.attn, st.attention_status, nullptr, stream); - } catch (const std::exception& error) { err = v.name("native_flash_attn") + ": " + error.what(); return false; } - if (cudaMemcpyAsync(st.host_step + kStepCount, st.attention_status, sizeof(int32_t), - cudaMemcpyDeviceToHost, (cudaStream_t) stream) != cudaSuccess) { - err = v.name("native_flash_attn") + ": status readback failed"; return false; - } -} 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 -// sigmoid/multiply arithmetic and uses Q8_1 for the native quantized projection. -// The canonical fallback retains its prior FP64 gate and Q8_K projection. -try { - if (native_qsa_enabled()) native_qsa_gate_apply(b.attn, b.q_full, b.attn32, (int) g.n_head, (int) g.head_dim, stream); - else qsa_gate_apply_f32(b.attn, b.q_full, s, b.attn32, stream); -} catch (const std::exception& error) { err = v.name("qsa_gate") + ": " + error.what(); return false; } - if (!w_attno->native_data) quantize_q8_K(b.attn32, b.attn_q8k, g.n_head * g.head_dim, stream); if (w_attno->native_data) { - if (!gemv_quantized(*w_attno, p_o, f_o, nullptr, b.attn_q8k, out, - g.n_head * g.head_dim, g.n_embd, v.name("attn_output.weight"), stream, err, b.attn32)) return false; -} else { - s_gemv_q8k_split(b.attn_q8k, p_o.codes, p_o.scales, p_o.offset, out, - g.n_head * g.head_dim, g.n_embd, f_o, stream); -} return true;} -// ================================ THE DOORBELL ================================ -namespace {} -// namespace -uint64_t doorbell_init(const ModelGeometry& g, int64_t k, Doorbell& db) { db.n_embd = g.n_embd; db.k = k; uint64_t bytes = 0; -// ONE region per field, each MAPPED PINNED, so the device and the host have different pointers to the same -// bytes and no copy is needed to publish them. -auto alloc = [&](size_t n, void** h, void** d, const char* what) { if (cudaHostAlloc(h, n, cudaHostAllocMapped) != cudaSuccess) { std::fprintf(stderr, "doorbell_init: cudaHostAlloc(%s) failed\n", what); return false; } if (cudaHostGetDevicePointer(d, *h, 0) != cudaSuccess) { std::fprintf(stderr, "doorbell_init: cudaHostGetDevicePointer(%s) failed\n", what); return false; } std::memset(*h, 0, n); bytes += n; return true; }; if (!alloc((size_t) g.n_embd * 4, (void**) &db.h_x_f, (void**) &db.d_x_f, "x_f")) return 0; if (!alloc((size_t) k * 4, (void**) &db.h_ids, (void**) &db.d_ids, "ids")) return 0; if (!alloc((size_t) k * 4, (void**) &db.h_weights, (void**) &db.d_weights, "weights")) return 0; if (!alloc(4, (void**) &db.h_seq, (void**) &db.d_seq, "seq")) return 0; if (!alloc(4, (void**) &db.h_flag, (void**) &db.d_flag, "flag")) return 0; return bytes;} -void doorbell_free(Doorbell& db) { if (db.h_x_f) cudaFreeHost(db.h_x_f); if (db.h_ids) cudaFreeHost(db.h_ids); if (db.h_weights) cudaFreeHost(db.h_weights); if (db.h_seq) cudaFreeHost(db.h_seq); if (db.h_flag) cudaFreeHost(db.h_flag); db = Doorbell{};} -void doorbell_reset(const Doorbell& db) { - if (db.h_seq) *db.h_seq = 0; - if (db.h_flag) *(volatile uint32_t*) db.h_flag = 0; -} -// ================================ THE TWO ENDS OF A TOKEN ================================ -bool embed_row(const WeightTable& tables, const ModelGeometry& g, int64_t token, float* out_dev, - void* stream, std::string& err) { - if (const NativeEmbed* ne = native_embed()) { // plan v0.3 P6: the GGUF-form table (IQ model files) - if (token < 0 || out_dev == nullptr) { err = "embed_row: invalid token or output"; return false; } - ne->gather_one(token, out_dev, stream); - return true; - } - const WeightRef* w = tables.find(EMBEDDING_NAME); - if (w == nullptr) { err = "token_embd.weight is missing"; return false; } - if (w->code_bits != 2 && w->code_bits != 4 && w->code_bits != 8) { - err = "embed_row: token_embd.weight is not an S2/S4/S8 tensor"; - return false; - } - if (w->codebook_iq4nl) { - err = "embed_row: an IQ4NL embedding is not supported"; - return false; - } - if (w->data == nullptr || out_dev == nullptr || w->ne0 <= 0 || w->ne1 <= 0 || - w->ne0 != g.n_embd || w->group_elems <= 0 || - w->ne0 % w->group_elems != 0 || w->ne0 % (8 / w->code_bits) != 0) { - err = "embed_row: invalid embedding pointers, dimensions or group size"; - return false; - } - if (token < 0 || token >= w->ne1) { - err = "embed_row: token " + std::to_string(token) + " is outside 0.." + std::to_string(w->ne1 - 1); - return false; - } - - const uint64_t row_codes = (uint64_t) (w->ne0 / (8 / w->code_bits)); - const uint64_t row_groups = (uint64_t) (w->ne0 / w->group_elems); - const uint64_t rows = (uint64_t) w->ne1; - // Division-based checks avoid overflow in rows * row_bytes and reject partial - // code/group rows before any device pointer arithmetic. - if (w->codes_bytes > w->bytes || w->scales_bytes > w->bytes - w->codes_bytes || - w->offset_bytes != w->bytes - w->codes_bytes - w->scales_bytes || - w->codes_bytes % row_codes != 0 || w->codes_bytes / row_codes != rows || - w->codes_bytes % alignof(float) != 0 || w->scales_bytes % sizeof(float) != 0 || - (w->scales_bytes / sizeof(float)) % row_groups != 0 || - (w->scales_bytes / sizeof(float)) / row_groups != rows || - w->has_offset != (w->offset_bytes != 0) || - (w->has_offset && w->offset_bytes != w->scales_bytes)) { - err = "embed_row: embedding planes do not match the loaded tensor shape"; - return false; - } - - const auto* codes = static_cast(w->data); - const auto* scales = reinterpret_cast(codes + w->codes_bytes); - const auto* offsets = w->has_offset ? reinterpret_cast(codes + w->codes_bytes + w->scales_bytes) - : nullptr; - const uint64_t group_offset = (uint64_t) token * row_groups; - strata::kernels::embedding_gather(codes + (uint64_t) token * row_codes, scales + group_offset, - offsets ? offsets + group_offset : nullptr, w->ne0, - w->code_bits, w->code_bias, w->group_elems, out_dev, stream); - return true; -} -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"); - if (!wn || !wd || !wu) { - err = "lm_head: an output_hc_* weight is missing"; - return false; - } - if (wn->kind != WeightKind::F32 || wd->kind != WeightKind::Bf16InF32 || - wu->kind != WeightKind::Bf16InF32) { - err = "lm_head: the output_hc_* weights have the wrong engine forms"; - return false; - } - const strata::kernels::GrShapes gs{g.n_embd, g.hc, g.hc_lr}; - strata::kernels::gr_read(bb.R, (const float*) wn->data, (const uint16_t*) wd->data, - (const uint16_t*) wu->data, nullptr, RMS_EPS, gs, bb.gr, - bb.mixed, bb.inject, stream); - return true; -} - -bool lm_head(const WeightTable& tables, const ModelGeometry& g, const BlockBuffers& bb, - float* logits, void* stream, std::string& err) { - const WeightRef* wo = tables.find("output.weight"); - if (!wo) { err = "output.weight is missing"; return false; } - strata::kernels::SForm form; - Planes planes; - if (!sform_of(*wo, form, "output.weight", err) || - !plane_ptrs(*wo, "output.weight", planes, err)) return false; - if (g.n_embd % Q8K_ELEMS_PER_BLOCK != 0) { - err = "lm_head: n_embd is not a multiple of 256"; - return false; - } - if (!lm_head_mix(tables, g, bb, stream, err)) return false; - strata::kernels::quantize_q8_K(bb.mixed, bb.head_q8k, g.n_embd, stream); - return gemv_quantized(*wo, planes, form, bb.head_q8k, bb.head_q8k, logits, - g.n_embd, wo->ne1, "output.weight", stream, err); -} -// ================================ ONE WHOLE BLOCK ================================ -uint64_t block_buffers_bytes(const ModelGeometry& g) { const strata::kernels::GrShapes s{g.n_embd, g.hc, g.hc_lr}; uint64_t n = 0; n += (uint64_t) g.hc * g.n_embd * 4; -// R -n += (uint64_t) g.n_embd * 4; -// mixed -n += (uint64_t) g.n_embd * 4; -// block_out -n += (uint64_t) g.hc * 4; -// inject -n += (uint64_t) g.hc * 4 * 2 + 32; -// inject2, gr_rs -n += q8k_bytes(g.n_embd); -// head_q8k -n += strata::kernels::gr_workspace_bytes(s); return align_up16(n) + 256;} -uint64_t block_buffers_init(const ModelGeometry& g, void* base, BlockBuffers& b) { const strata::kernels::GrShapes s{g.n_embd, g.hc, g.hc_lr}; Cursor c{(uint8_t*) base}; b.R = c.take((uint64_t) g.hc * g.n_embd); b.mixed = c.take((uint64_t) g.n_embd); b.block_out = c.take((uint64_t) g.n_embd); b.inject = c.take((uint64_t) g.hc); b.inject2 = c.take((uint64_t) g.hc); b.gr_rs = c.take((uint64_t) g.hc); b.head_q8k = c.take_bytes(q8k_bytes(g.n_embd)); uint8_t* grw = c.take_bytes(strata::kernels::gr_workspace_bytes(s)); strata::kernels::gr_workspace_init(s, grw, b.gr); return c.used;} -// ---- THE HALF-LEVEL C1 ORACLE. `dump` is a HOST buffer of `2 * n_embd + 2 * hc + n_head * head_dim` floats -// per layer; this enqueues one slice of it as a device-to-host copy. **IT RUNS INSIDE THE CAPTURE**, which is -// the point: the copy becomes a node of that layer's graph and replays with it, so the layer functions stay one -// function each and no per-layer plumbing reaches `generate.cpp`. A null `dump` is the default and skips the -// enqueue entirely, so the fast path records no extra node. -uint64_t dump_stride_floats(const ModelGeometry& g) { - // Layout per layer, all in floats: - // [0, 2*n_embd) the two halves' block_out - // [2*n_embd, +2*hc) the two halves' inject - // [+NH*HD) the QSA pre-gate attention - // [+2*NKV*HD) the QSA RAW vcur (as floats) - // [+NKV*HD/2) the gathered v_scratch, as fp16 pairs - // [+4) [+4) ids[0..3], then step[0..3] - // [+NKV*HD/2) the v_pool prefix, as fp16 pairs - // [+NKV*HD) the post-norm POST-ROPE kcur - // The last four are what separate a wrong projection from a wrong pool round trip. - const uint64_t nvk = (uint64_t) g.n_head_kv * g.head_dim; - return (uint64_t) 2 * g.n_embd + (uint64_t) 2 * g.hc + (uint64_t) g.n_head * g.head_dim + 5 * nvk + 8; -} -static void dump_slot(float* dump, const ModelGeometry& g, int64_t layer, const float* src, uint64_t off, - uint64_t n, void* stream) { - if (dump == nullptr || src == nullptr || n == 0) return; - cudaMemcpyAsync(dump + (size_t) layer * dump_stride_floats(g) + off, src, n * sizeof(float), - cudaMemcpyDeviceToHost, (cudaStream_t) stream); -} -static void dump_half(const BlockBuffers& bb, const ModelGeometry& g, int64_t layer, const float* src, - 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 - // other layer does; every part of the module was built and parity-tested and none of it was reachable from - // here. The block's output is `hidden + gated + silu(conv)` on the RESIDUAL STACK ITSELF, so it is a - // residual update applied BEFORE layer 1's own `gr_read` - which is what the architecture means by the - // gathered rows arriving "before layer 2". - // - // **THE HASH AND THE GATHER ARE *NOT* HERE, AND THAT IS THE WHOLE REASON `ple_stage_token` EXISTS.** Both - // are HOST operations - the hash is 64-bit multiply/xor that `qwen4exp.cpp` says is host-side because "ggml - // has no int64 and no xor", and the table is a host mapping. This function is CAPTURED, so anything host - // side in it runs ONCE, at capture time, and the graph then replays that result for every token: the engine - // would gather the capture-time token's rows forever and produce a perfectly finite, perfectly stable, - // completely wrong answer. It is the same bug as the doorbell's cloned literal, and it is silent. - // - // So the driver calls `ple_stage_token` once per token, BEFORE the graphs, and what is captured here is only - // the device half: `ple_block` reading `emb_dev`, and the history shift. - const bool fused = g_fused_gr && stage_prefix == 0 && half == 0 && - strata::kernels::fused_gr_supported(g.n_embd, g.hc, g.hc_lr); - // layer-1's FFN write has not been applied to R yet - unless a control vector follows it, which needs R - bool pending_ffn = fused && layer > 0 && !strata::kernels::cvec().covers(layer - 1); - if (ple != nullptr && ple->ready() && layer == 1 && (half == 0 || half == 1)) { - if (pending_ffn) { - const strata::kernels::GrShapes gs0{g.n_embd, g.hc, g.hc_lr}; - gr_write(bb.R, bb.block_out, bb.inject2, gs0, bb.R, stream); - pending_ffn = false; - } - const int64_t hcd = strata::kernels::NG_HC_DIM; - strata::kernels::PleOut po; - // Exports must not alias the block's internal workspace. The previous diagnostic views used a - // different layout inside that workspace: exporting gated values overwrote normalized values - // before the latter were copied to history. Allocate only the one export the recurrence needs. - po.normalized = (float*) ((uint8_t*) ple->scratch + strata::kernels::ple_block_scratch_bytes()); - // `result` IS THE RESIDUAL, in place: the block computes `hidden[i] + gated[i] + conv[i]` elementwise, - // so reading and writing `R` at the same index is well-defined. - po.result = bb.R; - try { - strata::kernels::ple_block(ple->emb_dev, bb.R, ple->hist, ple->w, po, ple->scratch, stream); - } catch (const std::exception& error) { - err = std::string("block_layer_pre PLE: ") + error.what(); - return false; - } - - // ---- AND THE HISTORY ADVANCES, ONCE PER TOKEN, WHICH IS WHAT MAKES IT A CONV HISTORY. - // - // `ple_block` deliberately does NOT write back to the history - "the caller keeps ownership of its - // state and this stays a pure function of its inputs, which is what makes the chunked-versus-single-shot - // property testable" - so the shift is here. The layout is ROW-FASTEST (`hist[row + NG_HIST*channel]`, - // from `ggml_reshape_3d(state, d_conv-1, conv_channels, n_seqs)`), so a row shift is a STRIDED copy of - // NG_HIST-1 elements per channel and an append is a strided copy of one - not a flat memmove, which - // would be the natural reading and would scramble the channels. - strata::kernels::ple_history_advance(ple->hist, po.normalized, stream); - if (cudaPeekAtLastError() != cudaSuccess) { - err = "block_layer_pre: the PLE history shift failed"; - return false; - } - } - const bool qsa = is_qsa_layer(g, layer); const LayerView v(tables, layer); const strata::kernels::GrShapes gs{g.n_embd, g.hc, g.hc_lr}; -// ---- the two halves' GR tensors. Both halves have the same four names with a different prefix, and the -// prefix is the ONLY thing that distinguishes them - so it is built rather than written twice. -const char* pre[2] = {"hc_attn_", "hc_ffn_"}; const WeightRef* w_norm[2]; const WeightRef* w_down[2]; const WeightRef* w_up[2]; const WeightRef* w_inject[2]; for (int h = 0; h < 2; ++h) { const std::string a = std::string(pre[h]) + "norm.weight"; const std::string d = std::string(pre[h]) + "down.weight"; const std::string u = std::string(pre[h]) + "up.weight"; const std::string i = std::string(pre[h]) + "inject.weight"; w_norm[h] = v.get(a.c_str()); w_down[h] = v.get(d.c_str()); w_up[h] = v.get(u.c_str()); w_inject[h] = v.get(i.c_str()); if (!w_norm[h] || !w_down[h] || !w_up[h] || !w_inject[h]) { err = v.name((std::string(pre[h]) + "{norm,down,up,inject}.weight").c_str()) + " is missing"; return false; } -// The GR weights are BF16 and the arena holds them re-rounded to 2 B/elem. `gr_read` wants exactly -// that; handing it f32 bytes would walk 2x the tensor inside the arena without faulting. -if (w_down[h]->kind != WeightKind::Bf16InF32 || w_up[h]->kind != WeightKind::Bf16InF32 || w_inject[h]->kind != WeightKind::Bf16InF32 || w_norm[h]->kind != WeightKind::F32) { err = v.name(pre[h]) + "has the wrong engine forms (norm must be F32, the other three bf16)"; return false; } } -// ---- half 1: the mixer -float* R = bb.R; - // R0.11: WHICH STAGES TO RUN. `stage_prefix == 0` means "as `half` says", so every caller that predates - // this parameter is bit-for-bit unaffected; `stage_prefix == k` runs stages 0..k-1 and ignores `half`. - 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); // R0.9: this is the MIXER half, and `half == 2` skips it entirely. A `half` of 1 or 0 runs it, - // and 0 is what every caller before this used. - if (run0) { -st_begin(layer, 0, stream); - if (fused) { - strata::kernels::FusedGrArgs fa; - fa.R = R; fa.R_out = R; fa.apply = pending_ffn; fa.bo_prev = bb.block_out; fa.inj_prev = bb.inject2; - fa.w_norm = (const float*) w_norm[0]->data; fa.w_down = (const uint16_t*) w_down[0]->data; - fa.w_up = (const uint16_t*) w_up[0]->data; fa.w_inject = (const uint16_t*) w_inject[0]->data; - fa.eps = RMS_EPS; fa.lo = bb.gr.lo; fa.rs = bb.gr_rs; fa.inject_out = bb.inject; fa.mixed = bb.mixed; - strata::kernels::fused_gr_read(fa, stream); - } else { - gr_read(R, (const float*) w_norm[0]->data, (const uint16_t*) w_down[0]->data, (const uint16_t*) w_up[0]->data, (const uint16_t*) w_inject[0]->data, RMS_EPS, gs, bb.gr, bb.mixed, bb.inject, stream); - } - st_end(layer, 0, stream); dump_half(bb, g, layer, bb.inject, 2 * g.n_embd, g.hc, stream); } - if (run1) { - 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); } - if (run2) { - st_begin(layer, 2, stream); if (!fused) gr_write(R, bb.block_out, bb.inject, gs, R, stream); st_end(layer, 2, stream); -// ---- half 2, UP TO AND INCLUDING THE ROUTER. `gr_read` leaves the normed activation in `bb.mixed` and -// the per-stream injection in `bb.inject`, and BOTH must survive until `block_layer_post` runs - which is -// the contract the two functions have with each other and with the host loop's ordering. - } - // R0.9: the FFN front and the ROUTER. It reads `bb.mixed`/`bb.inject`, which the mixer left - - // the same contract `block_layer_post` has, and the reason the two are only meaningful in order. - if (run3) { -st_begin(layer, 3, stream); - if (fused) { - strata::kernels::FusedGrArgs fa; - fa.R = R; fa.R_out = R; fa.apply = true; fa.bo_prev = bb.block_out; fa.inj_prev = bb.inject; - fa.w_norm = (const float*) w_norm[1]->data; fa.w_down = (const uint16_t*) w_down[1]->data; - fa.w_up = (const uint16_t*) w_up[1]->data; fa.w_inject = (const uint16_t*) w_inject[1]->data; - fa.eps = RMS_EPS; fa.lo = bb.gr.lo; fa.rs = bb.gr_rs; fa.inject_out = bb.inject2; fa.mixed = bb.mixed; - strata::kernels::fused_gr_read(fa, stream); - } else { - gr_read(R, (const float*) w_norm[1]->data, (const uint16_t*) w_down[1]->data, (const uint16_t*) w_up[1]->data, (const uint16_t*) w_inject[1]->data, RMS_EPS, gs, bb.gr, bb.mixed, bb.inject, stream); - } - st_end(layer, 3, stream); } - if (run4) { - 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; } - // Plan v0.3 P3: after the ring, so the GPU computes the shared expert while the host runs the pool. - if (g_shared_early && !moe_shared(tables, g, layer, mb, bb.mixed, stream, err)) return false; - } - // Every stage this call was asked to run has run. There is no other way out: the old `return ok;` - // lived inside the stage-4 block and restructuring that left the function with no return at all. - return true; -} -bool ple_issue_token(const PleRun& p, std::string& err) { - if (!p.ready()) { err = "ple_issue_token: the PLE run is not ready"; return false; } - uint32_t rows[strata::kernels::PLE_N_HEADS]; - strata::kernels::ngram_rows(p.token, p.prev, 1, p.consts, rows); - if (!p.table->issue(rows)) { err = "ple_issue_token: the previous token's rows were never collected"; return false; } - return true; -} - -bool ple_finish_token(const PleRun& p, void* stream, std::string& err) { - if (!p.ready()) { err = "ple_finish_token: the PLE run is not ready"; return false; } - if (!p.table->collect(p.emb_host, err)) { err = "ple_finish_token: " + err; return false; } - if (cudaMemcpyAsync(p.emb_dev, p.emb_host, (size_t) strata::kernels::NG_N_EMBD * sizeof(float), - cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess) { - err = "ple_finish_token: the row upload failed"; - return false; - } - return true; -} - -bool ple_stage_token(const PleRun& p, void* stream, std::string& err) { - if (!ple_issue_token(p, err)) return false; - return ple_finish_token(p, stream, err); -} - -uint64_t ple_run_scratch_bytes() { - // Internal workspace followed by a disjoint normalized export used for the next history row. - return strata::kernels::ple_block_scratch_bytes() + strata::kernels::NG_HC_DIM * sizeof(float); -} - -bool block_layer_post(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& mb, const BlockBuffers& bb, const float* parts, void* stream, std::string& err) { - if (g.hc == 1) return plain_block_post(tables, g, layer, k, mb, bb, parts, stream, err); - const strata::kernels::GrShapes gs{g.n_embd, g.hc, g.hc_lr}; -// `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); - 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); dump_half(bb, g, layer, bb.inject, (uint64_t) 2 * g.n_embd + g.hc, g.hc, stream); st_begin(layer, 6, stream); - const bool steer = strata::kernels::cvec().covers(layer); // --control-vector-scaled: after this write - try { - if (!(g_fused_gr && strata::kernels::fused_gr_supported(g.n_embd, g.hc, g.hc_lr))) { - gr_write(bb.R, bb.block_out, bb.inject, gs, bb.R, stream); - if (steer) strata::kernels::cvec_apply(bb.R, layer, 1, g.hc * g.n_embd, nullptr, 0, nullptr, 0, false, stream); - } else if (layer == g.n_layers - 1) { - gr_write(bb.R, bb.block_out, bb.inject2, gs, bb.R, stream); // materialise R for the head - if (steer) strata::kernels::cvec_apply(bb.R, layer, 1, g.hc * g.n_embd, nullptr, 0, nullptr, 0, false, stream); - } else if (steer) { - // the write the next layer's fused read would have folded, then the vector - strata::kernels::cvec_apply(bb.R, layer, 1, g.hc * g.n_embd, bb.block_out, g.n_embd, bb.inject2, g.hc, - true, stream); - } - } catch (const std::exception& e) { - err = std::string("block_layer_post: ") + e.what(); - return false; - } - st_end(layer, 6, stream); return true;} -bool block_layer(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, const float* parts, void* stream, std::string& err, const Doorbell* db, const PleRun* ple) { -// The two halves back to back. `parts` must be THIS layer's experts and must be ready before the call - -// which holds for `session_token`, where the caller supplies them, and does NOT hold for a host loop that -// has only just seen the router. That is why the captured path calls the halves separately. -if (!block_layer_pre(tables, g, layer, pos, pos_base, gb, qst, qb, mb, k, bb, stream, err, db, ple)) return false; return block_layer_post(tables, g, layer, k, mb, bb, parts, stream, err);}} -// namespace strata::core diff --git a/src/core/layout.cpp b/src/core/layout.cpp deleted file mode 100644 index 02fd93f..0000000 --- a/src/core/layout.cpp +++ /dev/null @@ -1,189 +0,0 @@ -// src/core/layout.cpp - the shape checks. See the header for why this exists. -#include "strata/core/layout.hpp" - -#include -#include - -namespace strata::core { -namespace { - -/// A required 2-D shape. `ne0` is the CONTIGUOUS axis, matching the manifest and `s_gemv`'s convention -/// (`y[o] = sum_i x[i]*W[i][o]`, row o contiguous of length ne0). -struct Want2 { - const char* suffix; - int64_t ne0; - int64_t ne1; - bool qsa_only; - bool gdn_only; -}; - -/// A required element count and ENGINE FORM for a 1-D tensor. -/// -/// `kind` is not decoration. The engine form of a 1-D tensor is whatever `WeightKind` the loader applied - -/// `F32` copies 4 B/elem, `Bf16InF32` re-rounds to 2 - and a consumer that casts either one to `const float*` -/// reads 2x its length. **THAT IS NOT HYPOTHETICAL: `ffn_gate_inp_shexp.weight` is BF16, so the arena holds -/// 5120 B for 2560 elements, and `shared_expert` read it as f32. Every one of the 2560 MoE outputs came out -/// non-finite** - a wrong answer loud enough to notice, which is the lucky version. Reading 5120 B past the -/// end of a tensor inside a 4.5 GiB arena does not fault, so the same mistake on a tensor followed by -/// plausible bytes would have produced plausible logits. -struct Want1 { - const char* suffix; - int64_t elements; - WeightKind kind; - bool qsa_only; - bool gdn_only; -}; - -bool fail(std::string& err, const LayerView& v, const char* suffix, const char* what, int64_t got, - int64_t want) { - char buf[512]; - std::snprintf(buf, sizeof buf, "layer %lld: %s %s is %lld, the kernels require %lld", - (long long) v.layer(), v.name(suffix).c_str(), what, (long long) got, (long long) want); - err = buf; - return false; -} - -bool check_one(const WeightTable& t, const ModelGeometry& g, int64_t layer, std::string& err) { - const LayerView v(t, layer); - const bool qsa = is_qsa_layer(g, layer); - - // ---- the 2-D tensor set, per layer family - const Want2 want2[] = { - // gated residual, EVERY layer - `gr_read` takes w_down (hc_lr, hc_dim) and w_up (hc_lr, hc_dim) - // after its own transpose, so the pack's orientation is [hc_dim, hc_lr] and [hc_lr, hc_dim]. - {"hc_attn_down.weight", g.hc_dim(), g.hc_lr, false, false}, - {"hc_attn_up.weight", g.hc_lr, g.hc_dim(), false, false}, - {"hc_attn_inject.weight", g.hc_dim(), g.hc, false, false}, - {"hc_ffn_down.weight", g.hc_dim(), g.hc_lr, false, false}, - {"hc_ffn_up.weight", g.hc_lr, g.hc_dim(), false, false}, - {"hc_ffn_inject.weight", g.hc_dim(), g.hc, false, false}, - // MoE, EVERY layer - {"ffn_gate_inp.weight", g.n_embd, g.n_expert, false, false}, - {"ffn_gate_shexp.weight", g.n_embd, g.n_ff, false, false}, - {"ffn_up_shexp.weight", g.n_embd, g.n_ff, false, false}, - {"ffn_down_shexp.weight", g.n_ff, g.n_embd, false, false}, - // GDN only - {"attn_qkv.weight", g.n_embd, g.ssm_conv_channels, false, true}, - {"attn_gate.weight", g.n_embd, g.ssm_value_dim, false, true}, - {"ssm_out.weight", g.ssm_value_dim, g.n_embd, false, true}, - {"ssm_conv1d.weight", g.ssm_d_conv, g.ssm_conv_channels, false, true}, - {"ssm_alpha.weight", g.n_embd, g.ssm_v_heads, false, true}, - {"ssm_beta.weight", g.n_embd, g.ssm_v_heads, false, true}, - // QSA only - {"attn_q.weight", g.n_embd, 2 * g.n_head * g.head_dim, true, false}, - {"attn_k.weight", g.n_embd, g.n_head_kv * g.head_dim, true, false}, - {"attn_v.weight", g.n_embd, g.n_head_kv * g.head_dim, true, false}, - {"attn_output.weight", g.n_head * g.head_dim, g.n_embd, true, false}, - // THE INDEXER. `q_proj` is the QUERY count and `k_proj` is the KEY width, and they are different - // numbers - conflating them is what made the planner's indexer term 4x too big in round 194. - {"indexer.q_proj.weight", g.n_embd, g.idx_q_heads * g.idx_key_dim, true, false}, - {"indexer.k_proj.weight", g.n_embd, g.idx_key_dim, true, false}, - }; - 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); - return false; - } - if (r->ne0 != w.ne0) return fail(err, v, w.suffix, "ne0", r->ne0, w.ne0); - if (r->ne1 != w.ne1) return fail(err, v, w.suffix, "ne1", r->ne1, w.ne1); - } - - // ---- the 1-D set. EVERY ONE OF THESE IS `F32` EXCEPT the shared expert's scalar gate, which is BF16 - - // and that single exception is the one a reader would not guess, so it is written down rather than - // inferred from the tensor count. - 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}, - {"ssm_norm.weight", g.ssm_state_size, WeightKind::F32, false, true}, - {"attn_q_norm.weight", g.head_dim, WeightKind::F32, true, false}, - {"attn_k_norm.weight", g.head_dim, WeightKind::F32, true, false}, - {"indexer.q_norm.weight", g.idx_key_dim, WeightKind::F32, true, false}, - {"indexer.k_norm.weight", g.idx_key_dim, WeightKind::F32, true, false}, - }; - 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); - return false; - } - if (r->elements != w.elements) return fail(err, v, w.suffix, "elements", r->elements, w.elements); - if (r->kind != w.kind) { - // The byte count is what makes this a REAL check and not a label: a 4 B/elem tensor holds - // `elements * 4`, a 2 B/elem one holds `elements * 2`, and a consumer reading it as the wrong one - // walks off the end. - const uint64_t want_bytes = (uint64_t) w.elements * - (w.kind == WeightKind::Bf16InF32 ? 2u : 4u); - char buf[512]; - std::snprintf(buf, sizeof buf, - "layer %lld: %s is engine form %d (%llu B), the kernels read it as form %d (%llu B)", - (long long) layer, v.name(w.suffix).c_str(), (int) r->kind, - (unsigned long long) r->bytes, (int) w.kind, (unsigned long long) want_bytes); - err = buf; - return false; - } - } - return true; -} - -} // namespace - -std::string LayerView::name(const char* suffix) const { - return "blk." + std::to_string(layer_) + "." + suffix; -} - -bool check_layer(const WeightTable& table, const ModelGeometry& g, int64_t layer, std::string& err) { - if (layer < 0 || layer >= g.n_layers) { - err = "layer " + std::to_string(layer) + " is outside 0.." + std::to_string(g.n_layers - 1); - return false; - } - return check_one(table, g, layer, err); -} - -bool check_all(const WeightTable& table, const ModelGeometry& g, std::string& err) { - int64_t n_qsa = 0, n_gdn = 0; - for (int64_t l = 0; l < g.n_layers; ++l) { - if (!check_one(table, g, l, err)) return false; - if (is_qsa_layer(g, l)) { - ++n_qsa; - } else { - ++n_gdn; - } - } - // The split is derived twice over in `docs/semantics.md` - the interval and an explicit ratio array - - // and both give 36 GDN and 12 QSA. Counting them here is the check that the LAYER TYPE PREDICATE and - // the pack agree, which no per-tensor shape check can see. - if (n_qsa != g.n_qsa_layers() || n_gdn != g.n_gdn_layers()) { - char buf[256]; - std::snprintf(buf, sizeof buf, "layer split is %lld QSA / %lld GDN, the geometry says %lld / %lld", - (long long) n_qsa, (long long) n_gdn, (long long) g.n_qsa_layers(), - (long long) g.n_gdn_layers()); - err = buf; - return false; - } - return true; -} - -} // namespace strata::core diff --git a/src/core/load_main.cpp b/src/core/load_main.cpp deleted file mode 100644 index 0885b76..0000000 --- a/src/core/load_main.cpp +++ /dev/null @@ -1,122 +0,0 @@ -// src/core/load_main.cpp - `strata-load`: the expert arena load, measurable at any scale. -// -// P2.S1 gives this a target (<= 60 s cold, <= 10 s warm for 33.97 GB) and a method (8 threads, 16 MB chunks, -// a checksum per layer). The size is a FLAG rather than hard-coded because the honest way to measure a 34 GB -// load is to measure a smaller one first and project - and because pinning 34 GB evicts every page of page -// cache on the machine, which is not something a test should do while other work is running. -#include "strata/core/pinned.hpp" - -#include -#include -#include -#include - -int main(int argc, char** argv) { - std::string path; - uint64_t layers = 2; - int threads = 8; - uint64_t chunk = 16ull << 20; - uint64_t blob_bytes = 1382400; // architecture §3.2, asserted by tools/pack_layer.py - uint64_t blobs_per_layer = 512; - bool pin = true; - bool stream = false; - - for (int i = 1; i < argc; ++i) { - const std::string a = argv[i]; - auto val = [&]() -> 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 == "--file") path = val(); - else if (a == "--layers") layers = std::strtoull(val(), nullptr, 10); - else if (a == "--threads") threads = std::atoi(val()); - else if (a == "--chunk-mb") chunk = std::strtoull(val(), nullptr, 10) << 20; - else if (a == "--no-pin") pin = false; - else if (a == "--stream") stream = true; - else if (a == "--help" || a == "-h") { - std::printf("usage: strata-load --file experts.bin [--layers N] [--threads N] [--chunk-mb N]\n" - " [--no-pin]\n"); - return 0; - } else { - std::fprintf(stderr, "unknown argument: %s\n", a.c_str()); - return 2; - } - } - if (path.empty()) { std::fprintf(stderr, "--file is required\n"); return 2; } - - const uint64_t bytes = layers * blobs_per_layer * blob_bytes; - std::printf("expert arena: %llu layers x %llu blobs x %llu B = %.3f GiB\n", (unsigned long long) layers, - (unsigned long long) blobs_per_layer, (unsigned long long) blob_bytes, - (double) bytes / (1024.0 * 1024 * 1024)); - - strata::core::PinnedArena arena; - uint8_t* dst = nullptr; - if (pin) { - // constructed in place so the note from the constructor can be printed before the load - new (&arena) strata::core::PinnedArena(bytes); - std::printf("backing: %s\n", arena.note.c_str()); - if (!arena.valid()) { std::fprintf(stderr, "arena allocation failed\n"); return 1; } - dst = arena.data(); - } else { - dst = (uint8_t*) std::malloc((size_t) bytes); - if (!dst) { std::fprintf(stderr, "malloc failed\n"); return 1; } - std::printf("backing: malloc, NOT pinned (--no-pin)\n"); - } - - const strata::core::LoadStats st = - strata::core::load_experts(path, dst, blob_bytes, blobs_per_layer, layers, threads, chunk); - if (!st.ok) { - std::fprintf(stderr, "loading the experts failed: %s\n", st.error.empty() ? "unknown" : st.error.c_str()); - return 1; - } - - std::printf("loaded %.3f GiB in %.3f s with %d threads and %llu MiB chunks -> %.2f GiB/s\n", - (double) st.bytes / (1024.0 * 1024 * 1024), st.seconds, threads, - (unsigned long long) (chunk >> 20), st.gib_per_second()); - std::printf("per-layer checksums (FNV-1a 64):\n"); - for (size_t i = 0; i < st.layer_checksums.size() && i < 4; ++i) { - std::printf(" layer %zu %016llx\n", i, (unsigned long long) st.layer_checksums[i]); - } - if (st.layer_checksums.size() > 4) { - std::printf(" ... %zu more (all layers loaded)\n", st.layer_checksums.size() - 4); - } - if (stream) { - // The bus is the ceiling, so measure it at the granularity the engine actually uses. Printed as a - // sweep rather than one number because "bandwidth" without a transfer size is not a specification. - std::printf("\nexpert stream over the pinned arena (host -> device, one reused destination):\n"); - const uint64_t granularities[] = {blob_bytes, 16 * blob_bytes, 512 * blob_bytes, bytes}; - const char* names[] = {"1 blob (1.38 MB)", "16 blobs (22 MB)", "1 layer (707 MB)", "whole arena"}; - for (int i = 0; i < 4; ++i) { - const uint64_t g = granularities[i]; - if (g > bytes) continue; - const int iters = (int) (g >= bytes ? 3 : (bytes / g >= 8 ? 8 : 3)); - const strata::core::StreamStats ss = - strata::core::stream_bandwidth(dst, (bytes / g) * g, g, iters); - if (ss.seconds < 0) continue; - std::printf(" %-18s chunk %8.2f MB %6.2f GB/s (%.3f GiB in %.3f s)\n", names[i], - (double) g / 1e6, ss.gib_per_second() * 1.073741824, - (double) ss.bytes / (1024.0 * 1024 * 1024), ss.seconds); - } - // And what it means, using the design's own constants, stated with the assumption attached. - const double best = 60.0; // GB/s, replaced below by the measured best if it is larger - (void) best; - std::printf("\nper-token expert stream at E = 663.6 MB and hit rate h (VRAM-resident fraction):\n"); - std::printf(" %-8s %-14s %-14s %s\n", "h", "miss MB/token", "ms at 1 blob", "tok/s ceiling"); - const strata::core::StreamStats one = strata::core::stream_bandwidth(dst, blob_bytes, blob_bytes, 64); - for (double h : {0.0, 0.5, 0.833, 0.9, 0.95}) { - const double miss_mb = (1.0 - h) * 663.6; - const double ms = miss_mb / 1000.0 / (one.gib_per_second() * 1.073741824) * 1000.0; - std::printf(" %-8.3f %-14.1f %-14.2f %.1f\n", h, miss_mb, ms, ms > 0 ? 1000.0 / ms : 0.0); - } - std::printf(" h = 0.167 is the design's constant; h = 0.833 is its complement, shown because the\n" - " plan's E = 663.6 MB is the FULL expert set per token, so which fraction is cached is\n" - " the question the number hinges on.\n"); - } - - // The projection is the number the phase's <= 60 s target is about, and it is printed as a projection - // rather than as the result, because at --layers 2 this program has NOT loaded 33.97 GB. - const double full = 33973862400.0; - std::printf("projection for the full %.2f GiB at this rate: %.1f s\n", full / (1024.0 * 1024 * 1024), - full / (1024.0 * 1024 * 1024) / (st.gib_per_second() > 0 ? st.gib_per_second() : 1e-9)); - return 0; -} diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp deleted file mode 100644 index e711323..0000000 --- a/src/core/mtp.cpp +++ /dev/null @@ -1,1372 +0,0 @@ -// 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" - -#include "strata/core/native_head.hpp" -#include "strata/core/peer_experts.hpp" -#include "strata/kernels/bf16_gemv.hpp" -#include "strata/kernels/cpu/expert.hpp" -#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" -#include "strata/kernels/native_mmvq.hpp" -#include "strata/kernels/native_qsa.hpp" -#include "strata/kernels/native_rope.hpp" -#include "strata/kernels/native_router.hpp" -#include "strata/kernels/qsa.hpp" -#include "strata/kernels/qsa_decode_attn.hpp" -#include "strata/kernels/quantize_act.hpp" -#include "strata/kernels/rope.hpp" -#include "strata/kernels/router_top10.hpp" -#include "strata/kernels/s2_expert_grouped.hpp" -#include "strata/kernels/sampler.hpp" -#include "strata/kernels/shared_expert.hpp" -#include "strata/kernels/verify_kernels.hpp" -#include "strata/kernels/ngram.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if defined(_WIN32) -#include -#elif defined(__x86_64__) -#include -#endif - -namespace strata::core { -namespace { - -constexpr float EPS = 1e-6f; -constexpr int GGML_Q8_0 = 8; -using Clock = std::chrono::steady_clock; -double ms_since(Clock::time_point t) { return std::chrono::duration(Clock::now() - t).count(); } - -struct Bump { - uint8_t* base = nullptr; - uint64_t used = 0; - template T* take(uint64_t n) { - T* p = base ? (T*) (base + used) : nullptr; - used += (n * sizeof(T) + 255) & ~255ull; - return p; - } -}; - -bool mapped(size_t bytes, void** h, void** d) { - if (cudaHostAlloc(h, bytes, cudaHostAllocMapped | (peer_portable() ? cudaHostAllocPortable : 0)) != cudaSuccess) return false; - std::memset(*h, 0, bytes); - return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess; -} - -// the one builder (strata/core/qsa_shapes.hpp): a dense geometry has its three indexer widths zero together -strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { return strata::core::qsa_shapes(g); } - -// 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) -#define STRATA_FILE_SEEK64(f, o, w) _fseeki64((f), (long long) (o), (w)) -#define STRATA_FILE_TELL64(f) _ftelli64(f) -#else -#define STRATA_FILE_SEEK64(f, o, w) fseeko((f), (off_t) (o), (w)) -#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": ` 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& 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 - // start. `fread` passes a request bigger than the stream buffer straight to `ReadFile()`. - FILE* f = std::fopen(path.c_str(), "rb"); - if (f == nullptr) return false; - // A `FILE*` has no destructor and the short-read path below returns early: the guard closes on every path. - struct Closer { - FILE* f; - ~Closer() { if (f != nullptr) std::fclose(f); } - } closer{f}; - if (STRATA_FILE_SEEK64(f, 0, SEEK_END) != 0) return false; - const long long n = (long long) STRATA_FILE_TELL64(f); - if (n < 0 || STRATA_FILE_SEEK64(f, 0, SEEK_SET) != 0) return false; - out.resize((size_t) n); - return n == 0 || std::fread(out.data(), 1, (size_t) n, f) == (size_t) n; -} - -} // namespace - -MtpDrafter::~MtpDrafter() { - if (cs_) cudaStreamSynchronize(cs_); - for (auto& e : prefill_exec_) if (e) cudaGraphExecDestroy(e); - for (auto& e : prefill_dev_exec_) if (e) cudaGraphExecDestroy(e); - if (pf_dev_) cudaFree(pf_dev_); - for (auto& e : round_exec_) if (e) cudaGraphExecDestroy(e); - for (auto& e : step_exec_) if (e) cudaGraphExecDestroy(e); - for (auto& e : round_exec_c_) if (e) cudaGraphExecDestroy(e); - for (auto& e : step_exec_c_) if (e) cudaGraphExecDestroy(e); - if (cparams_) cudaFree(cparams_); - if (cring_) cudaFree(cring_); - if (dinv_) cudaFree(dinv_); - if (cscratch_) cudaFree(cscratch_); - if (h_cparams_) cudaFreeHost(h_cparams_); - if (h_chist_) cudaFreeHost(h_chist_); - if (cs_) cudaStreamDestroy(cs_); - if (dense_) cudaFree(dense_); - if (experts_) cudaFree(experts_); - if (state_arena_) cudaFree(state_arena_); - if (arena_) cudaFree(arena_); - if (head_logits_) cudaFree(head_logits_); - if (dhead_) cudaFree(dhead_); - if (dvocab_) cudaFree(dvocab_); - void* hosts[] = {h_tok_, h_step_, h_pos_, h_row_, h_out_, h_prob_}; - for (void* h : hosts) if (h) cudaFreeHost(h); -} - -const float* MtpDrafter::f32(const char* name) const { - for (const auto& t : tensors_) if (t.name == name && t.kind == "f32") return (const float*) (dense_ + t.off); - return nullptr; -} -const uint16_t* MtpDrafter::bf16(const char* name) const { - for (const auto& t : tensors_) if (t.name == name && t.kind == "bf16") return (const uint16_t*) (dense_ + t.off); - return nullptr; -} -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 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) { - cudaGetDevice(&device_); // a layer split's last stage on another GPU: the drafter lives there - g_ = &g; - ss_ = &ss; - if (ple_ss_ == nullptr) ple_ss_ = &ss; - max_t_ = max_t; - rt_dir_ = rt_dir; - if (max_t < 1 || max_t > strata::kernels::kVerifyMaxT) { err = "mtp: max_t out of range"; return false; } - // Loader fix (0.1.15+loaderfix.2): the two reads below are the whole “drafter files” cost; reporting - // them apart from the rest of the stage is what makes the next regression visible. - const auto t_files = std::chrono::steady_clock::now(); - // ---- the index and the dense weights - { - std::ifstream idx(rt_dir + "/dense.txt"); - if (!idx) { err = "mtp: cannot open " + rt_dir + "/dense.txt (run tools/mtp_rt.py)"; return false; } - std::string line; - while (std::getline(idx, line)) { - if (line.empty()) continue; - std::istringstream is(line); - 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 blob; - if (!read_file(rt_dir + "/dense.bin", blob)) { err = "mtp: cannot read dense.bin"; return false; } - const cudaError_t alloc = cudaMalloc((void**) &dense_, blob.size()); - if (alloc != cudaSuccess) { - size_t free_bytes = 0, total_bytes = 0; - const cudaError_t info = cudaMemGetInfo(&free_bytes, &total_bytes); - err = "mtp: dense weights allocation failed (" + std::string(cudaGetErrorString(alloc)) + - "), requested " + std::to_string(blob.size() >> 20) + " MiB, CUDA0 free " + - (info == cudaSuccess ? std::to_string(free_bytes >> 20) + " MiB" : "unknown"); - return false; - } - cudaMemcpy(dense_, blob.data(), blob.size(), cudaMemcpyHostToDevice); - vram_ += blob.size(); - } - const bool qwen = g.arch == ModelArch::Qwen35Moe; - if (qwen && !check_qwen36_pack(rt_dir, g, err)) return false; - // ---- the routed experts, one blob each: Flash-Next's 512 canonical Q2_0 blobs, or Qwen3.6's 256 native GGUF blobs - uint64_t exp_bytes = (uint64_t) g.n_expert * strata::kernels::cpu::BLOB; - if (qwen && !load_qwen36_experts(rt_dir, g, exp_bytes, err)) return false; - { - 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"); - if (f == nullptr) { err = "mtp: cannot open experts.bin"; return false; } - struct Closer { - FILE* f; - ~Closer() { if (f != nullptr) std::fclose(f); } - } closer{f}; - if (cudaMalloc((void**) &experts_, bytes) != cudaSuccess) { err = "mtp: the " + std::to_string((long long) g.n_expert) + " draft experts (" + std::to_string(bytes >> 20) + " MiB) do not fit in VRAM"; return false; } - std::vector chunk(64u << 20); - for (uint64_t off = 0; off < bytes;) { - const uint64_t n = std::min(chunk.size(), bytes - off); - if (std::fread(chunk.data(), 1, (size_t) n, f) != (size_t) n) { err = "mtp: experts.bin is truncated"; return false; } - cudaMemcpy(experts_ + off, chunk.data(), n, cudaMemcpyHostToDevice); - off += n; - } - vram_ += bytes; - } - if (!qwen) { - const char* required[] = {"fc_embedding.weight", "fc_hidden.weight", "self_attn.q_proj.weight", "self_attn.k_proj.weight", - "self_attn.v_proj.weight", "self_attn.o_proj.weight", "mlp.shared_expert.gate_proj.weight", - "mlp.shared_expert.up_proj.weight", "mlp.shared_expert.down_proj.weight"}; - for (const char* n : required) if (!q8(n)) { err = std::string("mtp: ") + n + " is missing (q8_0)"; return false; } - } - - // ---- the layer's own K/V (dense attention: no indexer state is read) - const strata::kernels::QsaShapes s = shapes_of(g); - const int64_t max_cells = ss.qsa_states[ss.qsa_primary()].max_cells; - // KV streaming: the drafter only reads its last `window` cells, so with streaming on its K/V is a ring of the - // window (plus the cells a round writes ahead of its queries) over a host copy, refilled on a resume. The host copy - // is pinned after the expert arena has pinned what it could: if it does not fit, the K/V stays whole in VRAM. - int64_t ring = (window > 0 && window < max_cells) ? window + 4 * (int64_t) max_t + 64 : 0; - // K8V4 never applies to the drafter: its own attention paths (below, and verify.cpp) handle whole formats - // only, whatever ring shape it takes (0, a window, or the -1 fully-resident fallback). - const bool kv_hybrid_was = qsa_kv_hybrid(); - const bool kv_int8_was = qsa_kv_int8(); - qsa_set_kv_hybrid(false); - if (kv_hybrid_was) qsa_set_kv_int8(true); // the drafter under --kv k8v4: plain INT8 - uint64_t sb = qsa_state_bytes(g, max_cells, false, ring); - if (cudaMalloc(&state_arena_, sb) != cudaSuccess) { err = "mtp: the K/V state does not fit"; return false; } - if (qsa_state_init(g, max_cells, state_arena_, st_, &ss.qsa_states[ss.qsa_primary()], ring) == 0) { - if (st_.kv_mode == 0) { err = "mtp: state init failed"; return false; } - std::fprintf(stderr, "strata mtp: no pinned RAM left for the draft layer's K/V copy; keeping it in VRAM\n"); - cudaGetLastError(); - cudaFree(state_arena_); - st_ = QsaState{}; - ring = -1; // fully resident - sb = qsa_state_bytes(g, max_cells, false, ring); - if (cudaMalloc(&state_arena_, sb) != cudaSuccess) { err = "mtp: the K/V state does not fit"; return false; } - if (qsa_state_init(g, max_cells, state_arena_, st_, &ss.qsa_states[ss.qsa_primary()], ring) == 0) { err = "mtp: state init failed"; return false; } - } - qsa_set_kv_int8(kv_int8_was); - qsa_set_kv_hybrid(kv_hybrid_was); - qsa_state_zero(st_, g, nullptr); - cudaDeviceSynchronize(); - vram_ += sb; - - // ---- buffers - window_ = (window > 0 && window < max_cells) ? window : 0; - cap_ = (((window_ > 0 ? window_ : max_cells) + 63) / 64) * 64; - 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; - const uint64_t NH = (uint64_t) g.n_head, HD = (uint64_t) g.head_dim, NKV = (uint64_t) g.n_head_kv; - const uint64_t R2 = 2 * T; // step/pos rows: T catch-up rows + up to T-2 chain steps - bool ok = mapped(T * 4 + 64, (void**) &h_tok_, (void**) &m_tok_) && - mapped(R2 * 4 * 4 + 64, (void**) &h_step_, (void**) &m_step_) && - mapped(R2 * NH * 4 + 64, (void**) &h_pos_, (void**) &m_pos_) && - mapped(64, (void**) &h_row_, (void**) &m_row_) && - mapped(T * 4 + 64, (void**) &h_out_, (void**) &m_out_) && - mapped(T * 4 + 64, (void**) &h_prob_, (void**) &m_prob_); - if (!ok) { err = "mtp: mapped staging failed"; return false; } - auto carve = [&](Bump& b) { - tok_ = b.take(T); step_ = b.take(R2 * 4); pos_ = b.take(R2 * NH); row_ = b.take(4); - ident_ = b.take(T * (uint64_t) cap_); - Rin_ = b.take(T * HC * N); R_ = b.take(T * HC * N); - emb_ = b.take(T * N); en_ = b.take(T * N); e2_ = b.take(T * N); - hn_ = b.take(T * HC * N); h2_ = b.take(T * HC * N); - mixed_ = b.take(T * N); inj_ = b.take(T * HC); inj2_ = b.take(T * HC); - lo_ = b.take(T * (uint64_t) g.hc_lr); rs_ = b.take(T * HC); bo_ = b.take(T * N); - xn_ = b.take(T * HC * N); - xq_ = b.take(strata::kernels::native_q8_1_bytes((int) std::max(NH * HD, qwen ? 2 * N : 0), 8)); - cat_ = qwen ? b.take(T * 2 * N) : nullptr; // Qwen3.6: concat(enorm, hnorm) - qfull_ = b.take(T * NH * 2 * HD); qcur_ = b.take(T * NH * HD); - kcur_ = b.take(T * NKV * HD); vcur_ = b.take(T * NKV * HD); - attn_ = b.take(T * NH * HD); attn32_ = b.take(T * NH * HD); - attn_scratch_ = b.take((uint64_t) attn_scratch_floats_); // the full layer runs one row at a time - logits_ = b.take(T * (uint64_t) g.n_expert); w_ = b.take(T * K); ids_ = b.take(T * K); - shared_ = b.take(T * N); parts_ = b.take(T * K * N); y_ = b.take(T * N); - sample_ = b.take(T * N); - hit_slot_ = b.take(T * K); hit_dst_ = b.take(T * K); hit_count_ = b.take(4); - grp_ptr_ = b.take(T * K); grp_start_ = b.take(T * K + 1); - grp_counts_ = b.take(4); - hit_xq_ = b.take(T * (N / 32) * 34); hit_xs_ = b.take(T * (N / 32)); - hit_scratch_ = b.take(std::max( - 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(strata::kernels::shared_expert_scratch_bytes(std::max(g.n_ff, g.n_ff_shexp))); - x_bf16_ = b.take(N); - out_ids_ = b.take(T + 4); - probs_ = b.take(T + 4); - dummy_inj_ = b.take(HC); - }; - Bump count; - carve(count); - if (cudaMalloc(&arena_, count.used) != cudaSuccess) { err = "mtp: buffers do not fit"; return false; } - cudaMemset(arena_, 0, count.used); - Bump real; - real.base = (uint8_t*) arena_; - carve(real); - vram_ += count.used; - { - std::vector id((size_t) (T * (uint64_t) cap_)); - for (uint64_t t = 0; t < T; ++t) - for (int64_t i = 0; i < cap_; ++i) id[(size_t) (t * (uint64_t) cap_ + (uint64_t) i)] = (int32_t) i; - cudaMemcpy(ident_, id.data(), id.size() * 4, cudaMemcpyHostToDevice); - } - if (cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess) { err = "mtp: stream"; return false; } - const double files_s = std::chrono::duration(std::chrono::steady_clock::now() - t_files).count(); - std::fprintf(stderr, "strata mtp: draft layer loaded (%s), %.0f MiB of VRAM (experts %.0f, dense %.0f), files read in %.2f s (%.0f MiB/s)\n", - qwen ? "qwen35moe: the nextn block, native experts" : "qwen4exp", (double) vram_ / 1048576.0, - (double) exp_bytes / 1048576.0, (double) tensors_.back().off / 1048576.0, files_s, - files_s > 0 ? ((double) exp_bytes + (double) tensors_.back().off) / 1048576.0 / files_s : 0.0); - return true; -} - -uint64_t MtpDrafter::bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const { - uint64_t bytes = head_logits_ ? 0 : (uint64_t) max_t_ * (uint64_t) n_vocab * sizeof(float); - if (dhead_ == nullptr) { - if (FILE* f = std::fopen((rt_dir_ + "/draft_vocab.bin").c_str(), "rb")) { - std::fseek(f, 0, SEEK_END); - const long size = std::ftell(f); - std::fclose(f); - if (size >= 4 && size % 4 == 0) bytes += (uint64_t) (size / 4) * head_row_bytes + (uint64_t) size; - } - } - // coupled draft sampling (STRATA_SPEC_COUPLED=1 only): an upper bound - the id -> subset map, the penalty ring, - // the split scratch (64 lists of 64 entries at most) and the parameters - if (coupled_draft_env() && cparams_ == nullptr) - bytes += (uint64_t) n_vocab * 4 + (uint64_t) (kCoupledHistCap + max_t_) * 4 + 64ull * 64ull * 8ull + 4096; - return bytes; -} - -bool MtpDrafter::setup_coupled(std::string& err) { - const int64_t nv = dhead_ != nullptr ? n_dvocab_ : n_vocab_; - const size_t scratch = strata::kernels::coupled_draft_scratch_bytes((int) nv); - if (scratch == 0) { - std::fprintf(stderr, "strata mtp: STRATA_SPEC_COUPLED: %lld draft logits are too wide for the coupled sampler; " - "argmax drafts\n", (long long) nv); - return true; - } - const size_t ring = (size_t) (kCoupledHistCap + max_t_) * sizeof(int32_t); - if (cudaMalloc((void**) &cparams_, sizeof(strata::kernels::SamplerParams)) != cudaSuccess || - cudaMalloc((void**) &cring_, ring) != cudaSuccess || cudaMalloc(&cscratch_, scratch) != cudaSuccess || - !mapped(sizeof(strata::kernels::SamplerParams), (void**) &h_cparams_, (void**) &m_cparams_) || - !mapped((size_t) kCoupledHistCap * sizeof(int32_t), (void**) &h_chist_, (void**) &m_chist_)) { - err = "mtp: the coupled draft sampler's buffers do not fit"; - return false; - } - cudaMemset(cring_, 0xff, ring); // -1: no token - std::fill(h_chist_, h_chist_ + kCoupledHistCap, -1); - vram_ += sizeof(strata::kernels::SamplerParams) + ring + scratch; - if (dhead_ != nullptr) { // token id -> subset index (-1: not in the draft head), for the penalties - std::vector sub((size_t) n_dvocab_), inv((size_t) n_vocab_, -1); - cudaMemcpy(sub.data(), dvocab_, sub.size() * sizeof(int32_t), cudaMemcpyDeviceToHost); - for (size_t i = 0; i < sub.size(); ++i) - if (sub[i] >= 0 && sub[i] < n_vocab_ && inv[(size_t) sub[i]] < 0) inv[(size_t) sub[i]] = (int32_t) i; - if (cudaMalloc((void**) &dinv_, inv.size() * sizeof(int32_t)) != cudaSuccess) { - err = "mtp: the coupled draft sampler's token map does not fit"; - return false; - } - cudaMemcpy(dinv_, inv.data(), inv.size() * sizeof(int32_t), cudaMemcpyHostToDevice); - vram_ += inv.size() * sizeof(int32_t); - } - if (cudaDeviceSynchronize() != cudaSuccess) { - err = std::string("mtp: coupled setup: ") + cudaGetErrorString(cudaGetLastError()); - return false; - } - coupled_ok_ = true; - std::fprintf(stderr, "strata mtp: coupled draft sampling on (STRATA_SPEC_COUPLED): sampled requests draft with the " - "target's chain and Philox draw over %lld tokens\n", (long long) nv); - return true; -} - -void MtpDrafter::set_draft_sampling(const strata::kernels::SamplerParams& sp) { - coupled_active_ = coupled_ok_ && !sp.greedy && sp.temperature > 0.0f; - if (!coupled_active_) return; - *h_cparams_ = sp; // read by the next round graph (after the previous one has synced) - std::fill(h_chist_, h_chist_ + kCoupledHistCap, -1); -} - -void MtpDrafter::set_draft_history(const int32_t* tail, int64_t n_tail, int32_t next) { - if (!coupled_active_) return; - const int h = coupled_hist_len(h_cparams_->penalty_last_n, kCoupledHistCap); - coupled_hist_base(tail, n_tail, next, h, h_chist_ + (kCoupledHistCap - h)); -} - -namespace { -// #474: what to change when the draft head's token subset does not fit the VRAM left - a smaller subset that setup -// ships (data/draft_vocab_*.bin; their token counts below), and how to pick it. The start used to stop at "the draft -// head does not fit" with no hint. Text only, after the failure: nothing changes for a start that fits. -void draft_head_hint(int64_t n_tokens, int64_t row_bytes) { - size_t free_b = 0, total_b = 0; - const bool have_free = cudaMemGetInfo(&free_b, &total_b) == cudaSuccess; - auto mib = [&](int64_t n) { return (double) (n * row_bytes) / 1048576.0; }; - std::string free_s; - if (have_free) { - char b[64]; - std::snprintf(b, sizeof(b), " and %.0f MiB is free", (double) free_b / 1048576.0); - free_s = b; - } - std::fprintf(stderr, "strata mtp: the draft head over %lld tokens needs %.0f MiB of VRAM%s.\n", - (long long) n_tokens, mib(n_tokens), free_s.c_str()); - struct Subset { const char* name; int64_t tokens; const char* what; }; - static const Subset smaller[] = {{"cyrillic", 58963, "English, code and the Cyrillic script"}, - {"en", 40525, "English and code"}}; - std::string opts; - for (const Subset& s : smaller) - if (s.tokens < n_tokens) { - char b[160]; - std::snprintf(b, sizeof(b), "%s--draft-vocab %s (%s, ~%.0f MiB)", opts.empty() ? "" : " or ", s.name, - s.what, mib(s.tokens)); - opts += b; - } - if (!opts.empty()) - std::fprintf(stderr, "strata mtp: hint: a smaller draft vocabulary needs less VRAM: %s. Start once with it - " - "START-HERE.bat --draft-vocab en (Windows) or ./setup.sh --draft-vocab en - and the model " - "keeps it (\"draft_vocab\" in its strata-*.json config); or a smaller --context in " - "setup.\n", - opts.c_str()); - else - std::fprintf(stderr, "strata mtp: hint: this is already the smallest shipped draft vocabulary: a smaller " - "--context (or closing what else uses the GPU) leaves it room.\n"); -} -} // namespace - -bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err) { - const OnDevice on_device(device_); - wt_ = &wt; - head_ = head; - window_R_ = window_R; - const WeightRef* wo = wt.find("output.weight"); - if (!wo) { err = "mtp: output.weight is missing"; return false; } - n_vocab_ = wo->ne1; - if (head == nullptr || !head->loaded()) { err = "mtp: the draft layer needs the native head (--native)"; return false; } - if (head_logits_ == nullptr && - cudaMalloc((void**) &head_logits_, (size_t) max_t_ * (size_t) n_vocab_ * sizeof(float)) != cudaSuccess) { - err = "mtp: the draft logits do not fit"; - return false; - } - // the draft head's token subset, when tools/draft_vocab.py wrote one - if (dhead_ == nullptr) { - std::vector raw; - if (read_file(rt_dir_ + "/draft_vocab.bin", raw) && raw.size() >= 4 && raw.size() % 4 == 0) { - n_dvocab_ = (int64_t) (raw.size() / 4); - const int64_t row_bytes = (int64_t) head->row_bytes(); // a vocabulary row of the native head - if (cudaMalloc((void**) &dvocab_, raw.size()) != cudaSuccess || - cudaMalloc((void**) &dhead_, (size_t) (n_dvocab_ * row_bytes)) != cudaSuccess) { - err = "mtp: the draft head does not fit"; - draft_head_hint(n_dvocab_, row_bytes); - return false; - } - cudaMemcpy(dvocab_, raw.data(), raw.size(), cudaMemcpyHostToDevice); - strata::kernels::gather_rows((const uint8_t*) head->weights(), row_bytes, dvocab_, n_dvocab_, dhead_, nullptr); - cudaDeviceSynchronize(); - vram_ += (uint64_t) (n_dvocab_ * row_bytes) + raw.size(); - std::fprintf(stderr, "strata mtp: draft head over %lld tokens (%.1f MiB)\n", (long long) n_dvocab_, - (double) (n_dvocab_ * row_bytes) / 1048576.0); - } - } - if (coupled_draft_env() && cparams_ == nullptr && !setup_coupled(err)) return false; - return true; -} - -// 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_; - // step_row0 >= 0: the full layer on step rows [step_row0, +T); step_row0 < 0: K/V only on rows [-1 - step_row0, +T) - 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, HC = g.hc, K = ss.k, NH = g.n_head, HD = g.head_dim, NKV = g.n_head_kv; - const QsaShapes s = shapes_of(g); - const GrShapes gs{g.n_embd, g.hc, g.hc_lr}; - const int32_t* step = step_ + row0 * 4; - const int32_t* pos = pos_ + row0 * NH; - try { - // ---- the two input branches - 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()) { // plan v0.3 P6: the GGUF-form table - ne->gather_dev(tok_, T, emb_, cs); - } else { - 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); - } - native_qsa_rms_norm_weighted(emb_, f32("pre_fc_norm_embedding.weight"), en_, (int) N, T, EPS, cs); - native_quantize_q8_1(en_, xq_, (int) N, T, cs); - native_mmvq(GGML_Q8_0, q8("fc_embedding.weight"), xq_, e2_, (int) N, (int) N, T, cs); - native_qsa_rms_norm_weighted(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) (HC * N), T, EPS, cs); - for (int c0 = 0; c0 < T * HC; c0 += 8) { - const int nc = (int) std::min(8, T * HC - c0); - native_quantize_q8_1(hn_ + (size_t) c0 * N, xq_, (int) N, nc, cs); - native_mmvq(GGML_Q8_0, q8("fc_hidden.weight"), xq_, h2_ + (size_t) c0 * N, (int) N, (int) N, nc, cs); - } - add_streams_broadcast(h2_, e2_, R_, N, (int) HC, T, cs); - // ---- the attention hyper-connection - { - FusedGrArgs fa[kFusedGrMaxT]; - for (int t = 0; t < T; ++t) { - fa[t].R = R_ + (size_t) t * HC * N; fa[t].R_out = R_ + (size_t) t * HC * N; fa[t].apply = false; - fa[t].w_norm = f32("attn_hyper_connection.hc_norm.weight"); - fa[t].w_down = bf16("attn_hyper_connection.input_mix_weight_down.weight"); - fa[t].w_up = bf16("attn_hyper_connection.input_mix_weight_up.weight"); - fa[t].w_inject = bf16("attn_hyper_connection.block_inject_weight.weight"); - fa[t].eps = EPS; fa[t].lo = lo_ + t * g.hc_lr; fa[t].rs = rs_ + t * HC; - fa[t].inject_out = inj_ + t * HC; fa[t].mixed = mixed_ + t * N; - } - fused_gr_read_multi(fa, T, xn_, cs); - } - // ---- attention: K/V into the layer's own cache, then (full) dense attention over every cell - auto norm_rope = [&](float* data, const float* gamma, int rows, int cols, const int32_t* p) { - native_qsa_rms_norm_weighted(data, gamma, data, cols, rows, EPS, cs); - if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), p, cs); - else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st_.cos_tab, st_.sin_tab, p, cs); - }; - native_quantize_q8_1(mixed_, xq_, (int) N, T, cs); - native_mmvq(GGML_Q8_0, q8("self_attn.k_proj.weight"), xq_, kcur_, (int) N, (int) (NKV * HD), T, cs); - native_mmvq(GGML_Q8_0, q8("self_attn.v_proj.weight"), xq_, vcur_, (int) N, (int) (NKV * HD), T, cs); - for (int t = 0; t < T; ++t) { - norm_rope(kcur_ + t * NKV * HD, f32("self_attn.k_norm.weight"), (int) NKV, (int) HD, pos + t * NH); - if (st_.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1 - fwht256_inplace_cuda(kcur_ + t * NKV * HD, NKV, cs); - fwht256_inplace_cuda(vcur_ + t * NKV * HD, NKV, cs); - } - // stored in the state's own format (#293 appended rotated INT8 K/V as Q4_0, into pools INT8 never has) - 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; - native_mmvq(GGML_Q8_0, q8("self_attn.q_proj.weight"), xq_, qfull_, (int) N, (int) (NH * 2 * HD), T, cs); - 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; - } - norm_rope(qc, f32("self_attn.q_norm.weight"), (int) NH, (int) HD, pos + t * NH); - if (st_.kv_rot) fwht256_inplace_cuda(qc, NH, cs); - } - const QsaAttnPools pools = qsa_attn_pools(st_); - if (window_ > 0) window_ids(const_cast(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); - 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(GGML_Q8_0, q8("self_attn.o_proj.weight"), xq_, bo_, (int) (NH * HD), (int) N, T, cs); - // ---- the MLP hyper-connection (the attention write folded in) - { - FusedGrArgs fa[kFusedGrMaxT]; - for (int t = 0; t < T; ++t) { - fa[t].R = R_ + (size_t) t * HC * N; fa[t].R_out = R_ + (size_t) t * HC * N; fa[t].apply = true; - fa[t].bo_prev = bo_ + t * N; fa[t].inj_prev = inj_ + t * HC; - fa[t].w_norm = f32("mlp_hyper_connection.hc_norm.weight"); - fa[t].w_down = bf16("mlp_hyper_connection.input_mix_weight_down.weight"); - fa[t].w_up = bf16("mlp_hyper_connection.input_mix_weight_up.weight"); - fa[t].w_inject = bf16("mlp_hyper_connection.block_inject_weight.weight"); - fa[t].eps = EPS; fa[t].lo = lo_ + t * g.hc_lr; fa[t].rs = rs_ + t * HC; - fa[t].inject_out = inj2_ + t * HC; fa[t].mixed = mixed_ + t * N; - } - fused_gr_read_multi(fa, T, xn_, cs); - } - // ---- MoE: router, the 512 resident experts, the shared expert, the combine, the write - for (int t = 0; t < T; ++t) { - bf16_gemv_fp32_mmvf(mixed_ + t * N, bf16("mlp.gate.weight"), logits_ + t * g.n_expert, (int) N, (int) g.n_expert, cs); - if (native_router_enabled()) native_router_top10(logits_ + t * g.n_expert, ids_ + t * K, w_ + t * K, cs); - else router_top10(logits_ + t * g.n_expert, 1, (int) g.n_expert, (int) K, ids_ + t * K, w_ + t * K, cs); - } - moe_group_resident(ids_, (int) (T * K), (int) K, experts_, (int64_t) strata::kernels::cpu::BLOB, grp_ptr_, - grp_start_, grp_counts_, hit_dst_, hit_slot_, cs); - quantize_q8_0_scaled(mixed_, hit_xq_, hit_xs_, (int64_t) T * N, cs); - moe_grouped_s2(grp_ptr_, grp_start_, grp_counts_, hit_dst_, hit_slot_, (int64_t) T * K, (int64_t) T * K, hit_xq_, - hit_xs_, hit_scratch_, parts_, cs); - NativeSharedWeights nsw; - nsw.gate_type = GGML_Q8_0; nsw.gate_data = q8("mlp.shared_expert.gate_proj.weight"); - nsw.up_type = GGML_Q8_0; nsw.up_data = q8("mlp.shared_expert.up_proj.weight"); - nsw.down_type = GGML_Q8_0; nsw.down_data = q8("mlp.shared_expert.down_proj.weight"); - nsw.q8_1 = xq_; - const SForm none{}; - const bool need_bf16_x = !shared_expert_native_bf16_enabled(); - static const bool fuse_head_gr = [] { - const char* v = std::getenv("STRATA_FUSE_HEAD_GR"); - return v != nullptr && std::atoi(v) != 0; - }(); - 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, bf16("mlp.shared_expert_gate.weight"), sh_scratch_, shared_ + t * N, - N, g.n_ff, 32, cs, mixed_ + t * N, &nsw); - 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); - if (!fuse_head_gr) - gr_write(R_ + (size_t) t * HC * N, y_ + t * N, inj2_ + t * HC, gs, R_ + (size_t) t * HC * N, cs); - } - // ---- the final mixer and the main model's head - if (fuse_head_gr) { - FusedGrArgs fa[kFusedGrMaxT]; - for (int t = 0; t < T; ++t) { - fa[t].R = R_ + (size_t) t * HC * N; fa[t].R_out = R_ + (size_t) t * HC * N; fa[t].apply = true; - fa[t].bo_prev = y_ + t * N; fa[t].inj_prev = inj2_ + t * HC; - fa[t].w_norm = f32("hyper_connection_mixer.hc_norm.weight"); - fa[t].w_down = bf16("hyper_connection_mixer.input_mix_weight_down.weight"); - fa[t].w_up = bf16("hyper_connection_mixer.input_mix_weight_up.weight"); - fa[t].w_inject = nullptr; - fa[t].eps = EPS; fa[t].lo = lo_ + t * g.hc_lr; fa[t].rs = rs_ + t * HC; - fa[t].inject_out = dummy_inj_; fa[t].mixed = sample_ + t * N; - } - fused_gr_read_multi(fa, T, xn_, cs); - } else { - for (int t = 0; t < T; ++t) - gr_read(R_ + (size_t) t * HC * N, f32("hyper_connection_mixer.hc_norm.weight"), - bf16("hyper_connection_mixer.input_mix_weight_down.weight"), - bf16("hyper_connection_mixer.input_mix_weight_up.weight"), nullptr, EPS, gs, ss.block.gr, - sample_ + t * N, dummy_inj_, cs); - } - 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); - if (coupled_rec_) { - // coupled draft sampling: the target's chain and Philox draw for the row that will verify this draft - // (counter = this cell + 1, from its step record), penalties over the ring; T == 1 (full layer) - coupled_draft_sample(head_logits_, (int) nv, sub ? dvocab_ : nullptr, sub ? dinv_ : nullptr, (int) n_vocab_, - cparams_, cring_, kCoupledHistCap, coupled_j_, step, cscratch_, out_ids_, probs_, cs); - 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; -} - -// ---- 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(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 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; - const cudaError_t ce = cudaStreamEndCapture(cs, &graph); - if (!ok) { - if (graph) cudaGraphDestroy(graph); - return false; - } - if (ce != cudaSuccess || cudaGraphInstantiate(&exec, graph, 0) != cudaSuccess) { - if (graph) cudaGraphDestroy(graph); - err = std::string("mtp: ") + what + " capture: " + cudaGetErrorString(ce); - return false; - } - cudaGraphDestroy(graph); - // an explicit upload: the first launch's implicit one blocked behind a device-side spin (verify.cpp) - cudaGraphUpload(exec, cs); - cudaStreamSynchronize(cs); - return true; -} -} // namespace - -bool MtpDrafter::capture_prefill(int T, std::string& err) { - if (prefill_exec_[T]) return true; - using namespace strata::kernels; - if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "mtp: begin capture"; return false; } - copy_i32_from_mapped(tok_, m_tok_, T, cs_); - copy_i32_from_mapped(step_, m_step_, (int64_t) T * 4, cs_); - copy_i32_from_mapped(pos_, m_pos_, (int64_t) T * g_->n_head, cs_); - const bool ok = record_forward(T, -1, cs_, err); // K/V only, rows [0, T) - return finish_capture(cs_, ok, prefill_exec_[T], "prefill", err); -} - -bool MtpDrafter::capture_prefill_dev(int T, std::string& err) { - if (prefill_dev_exec_[T]) return true; - if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "mtp: begin capture"; return false; } - const bool ok = record_forward(T, -1, cs_, err); // K/V only, rows [0, T); tok_/step_/pos_ filled before launch - return finish_capture(cs_, ok, prefill_dev_exec_[T], "prefill (device inputs)", err); -} - -bool MtpDrafter::capture_round(int T, bool coupled, std::string& err) { - cudaGraphExec_t& exec = coupled ? round_exec_c_[T] : round_exec_[T]; - if (exec) return true; - using namespace strata::kernels; - const int64_t HCN = g_->hc * g_->n_embd; - if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "mtp: begin capture"; return false; } - bool ok = true; - // coupled: the request's chain and the penalty history's base, for this round's drafts - if (coupled) coupled_draft_stage(m_cparams_, m_chist_, cparams_, cring_, kCoupledHistCap, cs_); - copy_i32_from_mapped(tok_, m_tok_, T, cs_); - copy_i32_from_mapped(step_, m_step_, (int64_t) 2 * T * 4, cs_); - copy_i32_from_mapped(pos_, m_pos_, (int64_t) 2 * T * g_->n_head, cs_); - copy_i32_from_mapped(row_, m_row_, 2, cs_); - copy_from_mapped(Rin_, window_R_, (int64_t) T * HCN, cs_); - // the catch-up: K/V for the window's T cells, then the full layer for row a only (its cell's K/V is written - // again, identically), staged by the host in step row 2*max_t - 1; the draft chain is one graph per step - // (`capture_step`) so the host can stop it when a draft is unlikely - const int ra = 2 * max_t_ - 1; - ok = record_forward(T, -1, cs_, err); - if (ok) mtp_select(Rin_, HCN, tok_, row_, Rin_, tok_, nullptr, 0, cs_); - if (ok) { - copy_i32_from_mapped(step_ + ra * 4, m_step_ + ra * 4, 4, cs_); - copy_i32_from_mapped(pos_ + ra * g_->n_head, m_pos_ + ra * g_->n_head, g_->n_head, cs_); - coupled_rec_ = coupled; - coupled_j_ = 0; - ok = record_forward(1, ra, cs_, err); - coupled_rec_ = false; - } - if (ok) mtp_select(R_, HCN, out_ids_, row_ + 1, Rin_, tok_, m_out_, 0, cs_, probs_, m_prob_); - return finish_capture(cs_, ok, exec, coupled ? "round (coupled)" : "round", err); -} - -// Chain step j (1..max_t-2): one row at the cell staged in step row `max_t + j - 1`, from the previous step's -// residual and token (left in Rin_[0] / tok_[0] by mtp_select); draft j and its probability to the mapped outputs. -bool MtpDrafter::capture_step(int j, bool coupled, std::string& err) { - cudaGraphExec_t& exec = coupled ? step_exec_c_[j] : step_exec_[j]; - if (exec) return true; - using namespace strata::kernels; - const int64_t HCN = g_->hc * g_->n_embd; - const int row = max_t_ + j - 1; - if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "mtp: begin capture"; return false; } - copy_i32_from_mapped(step_ + row * 4, m_step_ + row * 4, 4, cs_); - copy_i32_from_mapped(pos_ + row * g_->n_head, m_pos_ + row * g_->n_head, g_->n_head, cs_); - coupled_rec_ = coupled; - coupled_j_ = j; - bool ok = record_forward(1, row, cs_, err); - coupled_rec_ = false; - if (ok) mtp_select(R_, HCN, out_ids_, row_ + 1, Rin_, tok_, m_out_, j, cs_, probs_, m_prob_); - return finish_capture(cs_, ok, exec, coupled ? "step (coupled)" : "step", err); -} - -void MtpDrafter::kv_restore(int64_t upto) { - const OnDevice on_device(device_); - if (st_.kv_mode != 2 || upto <= 0) return; - // the ring's blocks below `upto`, from the host copy: a checkpoint resume may have left later cells in them - const strata::kernels::QsaShapes s = shapes_of(*g_); - const int64_t b1 = (upto + s.page_size - 1) / s.page_size, b0 = std::max(0, b1 - st_.n_slots); - strata::kernels::kv_ring_restore(qsa_attn_pools(st_), st_.host, qsa_kv_format(st_), b0, b1, st_.n_slots, s, cs_); - cudaStreamSynchronize(cs_); -} - -bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err) { - const OnDevice on_device(device_); - const Clock::time_point t0 = Clock::now(); - const int64_t HCN = g_->hc * g_->n_embd; - // cells the window can never reach again need no K/V - const int64_t first_needed = (window_ > 0 && prompt_len_ > 0) ? prompt_len_ - window_ - 64 : 0; - // E-4: every group's token / step / position records uploaded at once; each group is then device copies and a - // graph on the one stream, with a single sync at the end (a group of <= max_t rows used to be staged in mapped - // memory and synced before the next: ~5,500 host round trips on a 32K prompt). The same work in the same - // order. STRATA_MTP_PREFILL_SYNC=1 keeps the old loop, =0 forces E-4. - // HIP defaults to the old loop. This pass runs whenever E-9 (Prefill::draft_kv) declines, which it does for the - // drafter's ring (KV streaming, --kv-resident), and on gfx1201 / ROCm 7.2.4 the E-4 queue (a graph launch and four - // device copies per group, ~2,000 groups per 8192-token chunk, no sync) sometimes never completes: the prompt hangs - // in hipGraphLaunch or the final sync until the watchdog ends the engine. R9700, full IQ3_XXS, --kv-resident - // 32768, mixed load (chats, 32K and 7K prompts, deep follow-ups): E-4 hung in the first round on 2 of 2 tries, - // the old loop ran 30 of 30 rounds clean, prompt speed unchanged. - static const bool per_group_sync = [] { - if (const char* v = std::getenv("STRATA_MTP_PREFILL_SYNC")) return std::atoi(v) != 0; -#if defined(STRATA_USE_HIP) - return true; -#else - return false; -#endif - }(); - const int64_t NHp = g_->n_head, per_row = 1 + 4 + NHp; - if (!per_group_sync && n > 0) { - if (pf_cap_ < n * per_row) { - if (pf_dev_) cudaFree(pf_dev_); - pf_dev_ = nullptr; - pf_cap_ = 0; - if (cudaMalloc((void**) &pf_dev_, (size_t) (n * per_row) * sizeof(int32_t)) != cudaSuccess) { - err = "mtp prefill: the input records do not fit"; - return false; - } - pf_cap_ = n * per_row; - } - std::vector rec((size_t) (n * per_row)); - int32_t* tk = rec.data(); - int32_t* stp = tk + n; - int32_t* ps = stp + 4 * n; - for (int64_t i = 0; i < n; ++i) { - const int64_t cell = cell0 + i; - tk[i] = next_tokens[i]; - stp[i * 4 + 0] = (int32_t) cell; - stp[i * 4 + 1] = (int32_t) (cell + 1); - stp[i * 4 + 2] = (int32_t) ((cell + 1) / 4); - stp[i * 4 + 3] = (int32_t) (cell + 1); - for (int64_t h = 0; h < NHp; ++h) ps[i * NHp + h] = (int32_t) cell; - } - if (cudaMemcpyAsync(pf_dev_, rec.data(), rec.size() * sizeof(int32_t), cudaMemcpyHostToDevice, cs_) != cudaSuccess) { - err = "mtp prefill: the input records upload failed"; - return false; - } - const int32_t* d_tk = pf_dev_; - const int32_t* d_stp = d_tk + n; - const int32_t* d_ps = d_stp + 4 * n; - for (int64_t c = 0; c < n; c += max_t_) { - const int T = (int) std::min(max_t_, n - c); - if (cell0 + c + T <= first_needed) continue; - if (!capture_prefill_dev(T, err)) return false; - if (cudaMemcpyAsync(tok_, d_tk + c, (size_t) T * 4, cudaMemcpyDeviceToDevice, cs_) != cudaSuccess || - cudaMemcpyAsync(step_, d_stp + c * 4, (size_t) T * 16, cudaMemcpyDeviceToDevice, cs_) != cudaSuccess || - cudaMemcpyAsync(pos_, d_ps + c * NHp, (size_t) (T * NHp) * 4, cudaMemcpyDeviceToDevice, cs_) != cudaSuccess || - cudaMemcpyAsync(Rin_, R_rows + (size_t) c * HCN, (size_t) T * HCN * sizeof(float), cudaMemcpyDeviceToDevice, - cs_) != cudaSuccess || - cudaGraphLaunch(prefill_dev_exec_[T], cs_) != cudaSuccess) { - err = std::string("mtp prefill: ") + cudaGetErrorString(cudaGetLastError()); - return false; - } - } - if (cudaStreamSynchronize(cs_) != cudaSuccess) { - err = std::string("mtp prefill: ") + cudaGetErrorString(cudaGetLastError()); - return false; - } - ms_prefill += ms_since(t0); - return true; - } - for (int64_t c = 0; c < n; c += max_t_) { - const int T = (int) std::min(max_t_, n - c); - if (cell0 + c + T <= first_needed) continue; - if (!capture_prefill(T, err)) return false; - for (int t = 0; t < T; ++t) { - const int64_t cell = cell0 + c + t; - h_tok_[t] = next_tokens[c + t]; - h_step_[t * 4 + 0] = (int32_t) cell; - h_step_[t * 4 + 1] = (int32_t) (cell + 1); - h_step_[t * 4 + 2] = (int32_t) ((cell + 1) / 4); - h_step_[t * 4 + 3] = (int32_t) (cell + 1); - for (int64_t h = 0; h < g_->n_head; ++h) h_pos_[t * g_->n_head + h] = (int32_t) cell; - } - if (cudaMemcpyAsync(Rin_, R_rows + (size_t) c * HCN, (size_t) T * HCN * sizeof(float), cudaMemcpyDeviceToDevice, - cs_) != cudaSuccess || - cudaGraphLaunch(prefill_exec_[T], cs_) != cudaSuccess || - cudaStreamSynchronize(cs_) != cudaSuccess) { - err = std::string("mtp prefill: ") + cudaGetErrorString(cudaGetLastError()); - return false; - } - } - ms_prefill += ms_since(t0); - return true; -} - -bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* drafts, std::string& err, - float* probs, float min_p, int* n_drafts) { - const OnDevice on_device(device_); - if (T < 1 || T > max_t_ || a < 0 || a >= T) { err = "mtp: draft arguments out of range"; return false; } - const bool cp = coupled_active_; // coupled draft sampling for this request: its own graphs - if (!capture_round(T, cp, err)) return false; - const int max_steps = std::min(max_t_ - 1, max_drafts_); - for (int j = 1; j < max_steps; ++j) - if (!capture_step(j, cp, err)) return false; - const Clock::time_point t0 = Clock::now(); - const int64_t NH = g_->n_head; - auto put = [&](int row, int64_t cell) { - h_step_[row * 4 + 0] = (int32_t) cell; - h_step_[row * 4 + 1] = (int32_t) (cell + 1); - h_step_[row * 4 + 2] = (int32_t) ((cell + 1) / 4); - h_step_[row * 4 + 3] = (int32_t) (cell + 1); - for (int64_t h = 0; h < NH; ++h) h_pos_[row * NH + h] = (int32_t) cell; - }; - for (int t = 0; t < T; ++t) { - h_tok_[t] = tokens[t]; - put(t, p + t); - } - put(2 * max_t_ - 1, coupled_draft_cell(p, a, 0)); // p + a: draft 0's cell - for (int j = 1; j < max_steps; ++j) - put(max_t_ + j - 1, coupled_draft_cell(p, a, j)); - for (int j = 0; j < max_steps; ++j) ((volatile int32_t*) h_out_)[j] = -1; - h_row_[0] = a; - h_row_[1] = 0; - std::atomic_thread_fence(std::memory_order_seq_cst); - - SessionState* const pss = ple_ss_ ? ple_ss_ : ss_; - const bool do_ple = pss != nullptr && pss->ple.ready() && pss->ple.table != nullptr; - int32_t ple_prev[2] = {do_ple ? pss->ple_prev[0] : 0, do_ple ? pss->ple_prev[1] : 0}; - auto prefetch_ple = [&](int32_t tok) { - if (!do_ple || tok < 0) return; - uint32_t rows16[strata::kernels::PLE_N_HEADS]; - strata::kernels::ngram_rows(&tok, ple_prev, 1, pss->ple.consts, rows16); - ple_prev[0] = ple_prev[1]; - ple_prev[1] = tok; - pss->ple.table->prefetch_rows(rows16); - }; - - int n = 0; - if (min_p <= 0.0f && max_steps > 0) { - if (cudaGraphLaunch(cp ? round_exec_c_[T] : round_exec_[T], cs_) != cudaSuccess) { - err = std::string("mtp draft: ") + cudaGetErrorString(cudaGetLastError()); - return false; - } - for (int j = 1; j < max_steps; ++j) { - if (cudaGraphLaunch(cp ? step_exec_c_[j] : step_exec_[j], cs_) != cudaSuccess) { - err = std::string("mtp draft step: ") + cudaGetErrorString(cudaGetLastError()); - return false; - } - } - (void) cudaStreamQuery(cs_); - prefetch_ple(tokens[a]); - for (int j = 0; j + 1 < max_steps; ++j) { - uint32_t spins = 0; - while (((volatile int32_t*) h_out_)[j] < 0) { -#if defined(_WIN32) || defined(__x86_64__) - _mm_pause(); -#endif - if ((++spins & 1023u) == 0 && cudaStreamQuery(cs_) != cudaErrorNotReady) break; - } - drafts[j] = ((volatile int32_t*) h_out_)[j]; - if (probs) probs[j] = ((volatile float*) h_prob_)[j]; - prefetch_ple(drafts[j]); - } - if (cudaStreamSynchronize(cs_) != cudaSuccess) { - err = std::string("mtp draft: ") + cudaGetErrorString(cudaGetLastError()); - return false; - } - const int last = max_steps - 1; - drafts[last] = ((volatile int32_t*) h_out_)[last]; - if (probs) probs[last] = ((volatile float*) h_prob_)[last]; - prefetch_ple(drafts[last]); - n = max_steps; - } else if (max_steps > 0) { - if (cudaGraphLaunch(cp ? round_exec_c_[T] : round_exec_[T], cs_) != cudaSuccess) { - err = std::string("mtp draft: ") + cudaGetErrorString(cudaGetLastError()); - return false; - } - (void) cudaStreamQuery(cs_); - prefetch_ple(tokens[a]); - auto wait_step = [&](int j) { - uint32_t spins = 0; - while (((volatile int32_t*) h_out_)[j] < 0) { -#if defined(_WIN32) || defined(__x86_64__) - _mm_pause(); -#endif - if ((++spins & 1023u) == 0 && cudaStreamQuery(cs_) != cudaErrorNotReady) break; - } - }; - wait_step(0); - drafts[0] = ((volatile int32_t*) h_out_)[0]; - float pj = ((volatile float*) h_prob_)[0]; - if (probs) probs[0] = pj; - n = 1; - for (int j = 1; j < max_steps && pj >= min_p; ++j) { - if (cudaGraphLaunch(cp ? step_exec_c_[j] : step_exec_[j], cs_) != cudaSuccess) { - err = std::string("mtp draft step: ") + cudaGetErrorString(cudaGetLastError()); - return false; - } - (void) cudaStreamQuery(cs_); - prefetch_ple(drafts[j - 1]); - wait_step(j); - drafts[j] = ((volatile int32_t*) h_out_)[j]; - pj = ((volatile float*) h_prob_)[j]; - if (probs) probs[j] = pj; - ++n; - } - prefetch_ple(drafts[n - 1]); - if (cudaStreamSynchronize(cs_) != cudaSuccess) { - err = std::string("mtp draft: ") + cudaGetErrorString(cudaGetLastError()); - return false; - } - } - for (int j = n; j < max_t_ - 1; ++j) { drafts[j] = 0; if (probs) probs[j] = 0.0f; } - if (n_drafts) *n_drafts = n; - ms_draft += ms_since(t0); - ++rounds; - return true; -} - -bool MtpDrafter::draft_first(int T, const float* R_row, int32_t token, int64_t cell, int32_t* drafts, std::string& err, - float* probs, float min_p, int* n_drafts) { - const OnDevice on_device(device_); - // row 0 is the real pair; rows 1.. repeat it and only write cells the next round overwrites - const int64_t HCN = g_->hc * g_->n_embd; - for (int t = 0; t < T; ++t) - if (cudaMemcpy((void*) (window_R_ + (size_t) t * HCN), R_row, (size_t) HCN * sizeof(float), - cudaMemcpyDeviceToDevice) != cudaSuccess) { - err = "mtp: staging the first residual failed"; - return false; - } - std::vector toks((size_t) T, token); - return draft(T, toks.data(), cell, 0, drafts, err, probs, min_p, n_drafts); -} - -} // namespace strata::core diff --git a/src/core/native_dense.cpp b/src/core/native_dense.cpp deleted file mode 100644 index e0609fd..0000000 --- a/src/core/native_dense.cpp +++ /dev/null @@ -1,210 +0,0 @@ -#include "strata/core/native_dense.hpp" -#include -#include "strata/core/weights.hpp" -#include "strata/artifact/gguf_reader.hpp" -#include "strata/kernels/native_mmvq.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace strata::core { -namespace { -int g_layer_lb = -1, g_layer_le = -1; // set_layer_range; -1: every layer -bool in_range(const std::string& name) { - if (g_layer_lb < 0 || name.rfind("blk.", 0) != 0) return true; - const int l = std::atoi(name.c_str() + 4); - return l >= g_layer_lb && l < g_layer_le; -} -bool eligible(const strata::TensorInfo& tensor, bool include_ple_key) { - const auto& name = tensor.name; - if (name.rfind("blk.", 0) != 0) return false; - // Match the native PLE kernel: Q2_0, IQ3_XXS, IQ4_XS and Q8_0 (UD-Q4_K_XL). Other keys retain the packed BF16 - // fallback. - if (name == "blk.1.ple_key.weight") - return include_ple_key && (tensor.type == 42 || tensor.type == 18 || tensor.type == 23 || tensor.type == 8); - static const char* suffixes[] = {".attn_qkv.weight", ".attn_gate.weight", ".ssm_out.weight", - ".attn_q.weight", ".attn_k.weight", ".attn_v.weight", ".attn_output.weight", - ".ffn_gate_shexp.weight", ".ffn_up_shexp.weight", ".ffn_down_shexp.weight"}; - for (const char* suffix : suffixes) if (name.ends_with(suffix)) return true; - return false; -} -struct DeviceFree { void operator()(void* p) const { if (p) cudaFree(p); } }; -using DevicePtr = std::unique_ptr; -struct Pending { - WeightRef* ref; - int type; - uint64_t bytes; - DevicePtr data; -}; -} - -bool NativeDense::served_names(const std::vector& shards, bool include_ple_key, - std::set& out, std::string& err) { - try { - for (const auto& path : shards) { - strata::GgufFile gguf(path); - for (const auto& tensor : gguf.tensors()) - if (eligible(tensor, include_ple_key) && strata::kernels::native_mmvq_supported(tensor.type) && - tensor.shape.size() == 2) - out.insert(tensor.name); - } - return true; - } catch (const std::exception& error) { - err = std::string("native dense: ") + error.what(); - return false; - } -} - -void NativeDense::set_layer_range(int lb, int le) { g_layer_lb = lb; g_layer_le = le; } -bool NativeDense::keep_unquantized_ple_key(const std::string& pack_dir, std::set& skip, - std::string& err) { - const std::string key = "blk.1.ple_key.weight"; - if (!skip.count(key)) return true; - int code_bits = -1; - if (!WeightTable::index_code_bits(pack_dir, key, code_bits, err)) return false; - if (code_bits == 0) skip.erase(key); - return true; -} - -NativeDense::~NativeDense() { - if (scratch_) cudaFree(scratch_); - for (void* p : weights_) cudaFree(p); -} - -bool NativeDense::load(const std::vector& shards, WeightTable& table, std::string& err, - bool include_ple_key, int64_t layer_lo, int64_t layer_hi) { - auto outside = [&](const std::string& name) { // a blk.. tensor of another stage's layers - if (layer_hi < 0 || name.rfind("blk.", 0) != 0) return false; - const long l = std::strtol(name.c_str() + 4, nullptr, 10); - return l < layer_lo || l >= layer_hi; - }; - if (scratch_ || !weights_.empty()) { err = "native dense: already loaded"; return false; } - if (shards.empty()) { err = "native dense: at least one GGUF shard is required"; return false; } - try { - std::vector pending; - std::set seen; - int max_in = 0; - uint64_t total = 0; - uint64_t split_count = 0, split_tensors = 0; - std::set split_numbers; - bool have_architecture = false; - for (const auto& path : shards) { - strata::GgufFile gguf(path); - const auto* count = gguf.get("split.count"); - const auto* number = gguf.get("split.no"); - const auto* tensors = gguf.get("split.tensors.count"); - if (gguf.get("general.architecture")) { - err = strata::check_architecture(gguf); - if (!err.empty()) return false; - have_architecture = true; - if (count && number && tensors && number->u == 0 && count->u > 1) { - split_count = count->u; - split_tensors = tensors->u; - } - } else if (!have_architecture || !split_count || !count || !number || !tensors || - count->u != split_count || number->u == 0 || number->u >= split_count || - tensors->u != split_tensors) { - err = "native dense: additional shard must match the architecture-validated first shard's split metadata"; - return false; - } - if (number && !split_numbers.insert(number->u).second) { - err = "native dense: duplicate split shard number"; return false; - } - std::vector offsets; - for (const auto& tensor : gguf.tensors()) offsets.push_back(tensor.offset); - std::sort(offsets.begin(), offsets.end()); - if (std::adjacent_find(offsets.begin(), offsets.end()) != offsets.end()) { - err = "native dense: tensor payload offsets overlap"; return false; - } - // Validate every directory span, including tensors we do not upload: - // an ignored tensor must not overlap the native matrix that follows it. - const uint64_t payload = gguf.file_size() - gguf.data_start(); - for (const auto& tensor : gguf.tensors()) { - int block_elements = 0, block_bytes = 0; - uint64_t elements = 1; - if (tensor.shape.empty() || !strata::block_geometry(tensor.type, block_elements, block_bytes) || - tensor.shape[0] % (uint64_t) block_elements != 0) { - err = "native dense: invalid block geometry " + tensor.name; return false; - } - for (uint64_t dimension : tensor.shape) { - if (!dimension || elements > (std::numeric_limits::max)() / dimension) { - err = "native dense: invalid tensor extent " + tensor.name; return false; - } - elements *= dimension; - } - const uint64_t blocks = elements / (uint64_t) block_elements; - if (blocks > (std::numeric_limits::max)() / (uint64_t) block_bytes) { - err = "native dense: tensor byte count overflow " + tensor.name; return false; - } - const uint64_t bytes = blocks * (uint64_t) block_bytes; - if (tensor.offset > payload || bytes > payload - tensor.offset) { - err = "native dense: truncated payload " + tensor.name; return false; - } - const auto next = std::upper_bound(offsets.begin(), offsets.end(), tensor.offset); - if (next != offsets.end() && bytes > *next - tensor.offset) { - err = "native dense: overlapping payload " + tensor.name; return false; - } - } - for (const auto& tensor : gguf.tensors()) { - if (!eligible(tensor, include_ple_key) || outside(tensor.name)) continue; - if (!in_range(tensor.name) && tensor.name.find("ple") == std::string::npos) continue; - if (!seen.insert(tensor.name).second) { - err = "native dense: duplicate tensor " + tensor.name; return false; - } - auto found = table.table_.find(tensor.name); - if (found == table.table_.end()) { - err = "native dense: tensor absent from canonical table: " + tensor.name; return false; - } - auto& ref = found->second; - if (ref.native_data) { err = "native dense: override already attached"; return false; } - if (!strata::kernels::native_mmvq_supported(tensor.type)) continue; - // #326: the pack keeps an unquantized (--compat-bf16) key, which the PLE reads from the arena - if (tensor.name == "blk.1.ple_key.weight" && !ref.quantized()) continue; - if (!ref.quantized() || tensor.shape.size() != 2 || - ref.ne0 <= 0 || ref.ne0 > INT_MAX || ref.ne1 <= 0 || ref.ne1 > INT_MAX || - tensor.shape[0] != (uint64_t) ref.ne0 || tensor.shape[1] != (uint64_t) ref.ne1) { - err = "native dense: incompatible matrix " + tensor.name; return false; - } - const auto bytes = strata::kernels::native_mmvq_weight_bytes( - tensor.type, (int) ref.ne0, (int) ref.ne1); - void* allocation = nullptr; - auto status = cudaMalloc(&allocation, bytes); - DevicePtr data(allocation); - if (status == cudaSuccess) - status = cudaMemcpy(data.get(), gguf.tensor_data(tensor), bytes, cudaMemcpyHostToDevice); - if (status != cudaSuccess) { - err = "native dense upload " + tensor.name + ": " + cudaGetErrorString(status); return false; - } - max_in = (std::max)(max_in, (int) ref.ne0); - total += bytes; - pending.push_back(Pending{&ref, (int) tensor.type, bytes, std::move(data)}); - } - } - if (pending.empty()) { err = "native dense: no supported GDN/QSA matrices in supplied shards"; return false; } - void* allocation = nullptr; - const auto status = cudaMalloc(&allocation, strata::kernels::native_q8_1_bytes(max_in)); - DevicePtr scratch(allocation); - if (status != cudaSuccess) { err = std::string("native dense scratch: ") + cudaGetErrorString(status); return false; } - // All checks and allocations finish before publishing any reference. - weights_.reserve(pending.size()); - for (auto& item : pending) { - item.ref->native_data = item.data.get(); - item.ref->native_type = item.type; - item.ref->native_q8_1 = scratch.get(); - weights_.push_back(item.data.release()); - } - scratch_ = scratch.release(); - bytes_ = total; - return true; - } catch (const std::exception& error) { - err = std::string("native dense: ") + error.what(); - return false; - } -} -} // namespace strata::core diff --git a/src/core/native_head.cpp b/src/core/native_head.cpp deleted file mode 100644 index acb4f81..0000000 --- a/src/core/native_head.cpp +++ /dev/null @@ -1,198 +0,0 @@ -#include "strata/core/native_head.hpp" -#include "strata/artifact/gguf_reader.hpp" -#include "strata/kernels/iq_kernels.hpp" -#include "strata/kernels/native_mmvq.hpp" - -#include -#include -#include -#include -#include - -namespace strata::core { - -NativeHead::~NativeHead() { - if (scratch_) cudaFree(scratch_); - if (weights_) cudaFree(weights_); -} - -bool NativeHead::load(const std::vector& shards, int64_t n_in, int64_t n_out, std::string& err) { - if (loaded()) { err = "native head is already loaded"; return false; } - if (n_in <= 0 || n_out <= 0 || n_in > INT_MAX || n_out > INT_MAX || n_in % 256) { - err = "native head requires positive int32 dimensions and whole 256-value rows"; - return false; - } - try { - // The architecture is the metadata shard's; output.weight comes from whichever shard holds it (shard 2 - // of Unsloth's UD-Q4_K_XL, whose shard 1 holds no tensor). GgufModel refuses a duplicate across shards. - const strata::GgufModel model(shards); - err = strata::check_architecture(model.meta()); - if (!err.empty()) return false; - size_t at = 0; - const strata::TensorInfo* tensor = model.find("output.weight", &at); - const strata::GgufFile& gguf = model.shard(at); - if (!tensor || !strata::kernels::native_mmvq_supported((int) tensor->type) || tensor->shape.size() != 2 || - tensor->shape[0] != (uint64_t) n_in || tensor->shape[1] != (uint64_t) n_out) { - err = "native head: expected a natively supported output.weight with the canonical head dimensions"; - return false; - } - const uint64_t bytes = strata::kernels::native_mmvq_weight_bytes((int) tensor->type, (int) n_in, (int) n_out); - const uint64_t payload = gguf.file_size() - gguf.data_start(); - if (tensor->offset > payload || bytes > payload - tensor->offset) { - err = "native head: truncated output.weight payload"; - return false; - } - void* weights = nullptr; - void* scratch = nullptr; - cudaError_t status = cudaMalloc(&weights, bytes); - if (status == cudaSuccess) - status = cudaMalloc(&scratch, strata::kernels::native_q8_1_bytes((int) n_in, 1)); - if (status == cudaSuccess) - status = cudaMemcpy(weights, gguf.tensor_data(*tensor), bytes, cudaMemcpyHostToDevice); - if (status != cudaSuccess) { - if (scratch) cudaFree(scratch); - if (weights) cudaFree(weights); - err = std::string("native head upload: ") + cudaGetErrorString(status); - return false; - } - weights_ = weights; - scratch_ = scratch; - bytes_ = bytes; - n_in_ = (int) n_in; - n_out_ = (int) n_out; - type_ = (int) tensor->type; - return true; - } catch (const std::exception& error) { - err = std::string("native head: ") + error.what(); - return false; - } -} - -bool NativeHead::run(const float* mixed, float* logits, void* stream, std::string& err) const { - if (!loaded() || !mixed || !logits || !stream) { - err = "native head requires loaded weights, device buffers and an explicit stream"; - return false; - } - try { - if (type_ == 13) { - strata::kernels::native_q5_k_f32(weights_, mixed, scratch_, logits, n_in_, n_out_, 1, stream); - } else { - strata::kernels::native_quantize_q8_1(mixed, scratch_, n_in_, 1, stream); - strata::kernels::native_mmvq(type_, weights_, scratch_, logits, n_in_, n_out_, 1, stream); - } - } catch (const std::exception& error) { - err = std::string("native head launch: ") + error.what(); - return false; - } - const cudaError_t status = cudaPeekAtLastError(); - if (status != cudaSuccess) { - err = std::string("native head launch: ") + cudaGetErrorString(status); - return false; - } - return true; -} - -// ================================ plan v0.3 P6: THE NATIVE EMBEDDING ================================ - -namespace { -const NativeEmbed* g_embed = nullptr; -} -void set_native_embed(const NativeEmbed* e) { g_embed = e; } -const NativeEmbed* native_embed() { return g_embed; } - -NativeEmbed::~NativeEmbed() { - if (host_) cudaFreeHost(host_); - else if (dev_) cudaFree(const_cast(dev_)); // the VRAM fallback below -} - -bool NativeEmbed::load(const std::vector& shards, int64_t n_embd, int64_t n_vocab, std::string& err) { - try { - const strata::GgufModel model(shards); - // --embd-gguf's one-tensor file (tools/embd_bf16_pack.py) says "strata-embd": only its tensor is checked - const strata::MetaValue* arch = model.meta().get("general.architecture"); - err = arch != nullptr && arch->s == "strata-embd" ? std::string() : strata::check_architecture(model.meta()); - if (!err.empty()) { err = "native embedding: " + err; return false; } - size_t at = 0; - const strata::TensorInfo* t = model.find("token_embd.weight", &at); - const strata::GgufFile& gguf = model.shard(at); - if (!t || t->shape.size() != 2 || t->shape[0] != (uint64_t) n_embd || t->shape[1] != (uint64_t) n_vocab || - !strata::kernels::embed_type_supported((int) t->type) || n_embd % 256) { - err = "native embedding: token_embd.weight is absent, of another shape, or of a type without a GPU " - "dequantizer"; - return false; - } - row_ = strata::kernels::iq_row_bytes((int) t->type, n_embd); - bytes_ = (uint64_t) row_ * (uint64_t) n_vocab; - // the table is copied out of the mapping below: a truncated shard must be an error, not a read past EOF - if (!model.in_bounds(*t, at) || strata::tensor_payload_bytes(*t) != bytes_) { - err = "native embedding: token_embd.weight's payload is truncated or not " + std::to_string(bytes_) + - " B (" + gguf.path() + ")"; - bytes_ = 0; - return false; - } - if (cudaHostAlloc(&host_, bytes_, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess) { - // Under WSL2 the driver's pinned/mapped host budget (~1 GiB) can be spent by the GPU contexts - // themselves (three cards). The table is only gathered from, so keep it in the current device's VRAM - // instead: it costs its size there and reads faster than over PCIe. - cudaGetLastError(); - host_ = nullptr; - void* d = nullptr; - if (cudaMalloc(&d, bytes_) != cudaSuccess || - cudaMemcpy(d, gguf.tensor_data(*t), bytes_, cudaMemcpyHostToDevice) != cudaSuccess) { - if (d) cudaFree(d); - cudaGetLastError(); - err = "native embedding: cannot pin " + std::to_string(bytes_ >> 20) + " MiB, nor place it in VRAM"; - return false; - } - std::fprintf(stderr, "strata: native embedding: cannot pin %llu MiB, kept in VRAM instead\n", - (unsigned long long) (bytes_ >> 20)); - dev_ = d; - } else { - std::memcpy(host_, gguf.tensor_data(*t), bytes_); - void* d = nullptr; -#if defined(STRATA_USE_HIP) - // #325: the Windows HIP stack can refuse the device alias of a mapped allocation (and, when it gives - // one, it is the host address itself - unified addressing; kernels read it correctly there, a - // device-to-device copy into it does not land: tests/hip/mapped_alias). The table is only gathered from, - // so without an alias it goes into VRAM like the unpinnable case above, instead of failing the start. - if (cudaHostGetDevicePointer(&d, host_, 0) != cudaSuccess || d == nullptr) { - cudaGetLastError(); - d = nullptr; - if (cudaMalloc(&d, bytes_) != cudaSuccess || - cudaMemcpy(d, gguf.tensor_data(*t), bytes_, cudaMemcpyHostToDevice) != cudaSuccess) { - if (d) cudaFree(d); - cudaGetLastError(); - err = "native embedding: no device alias for the mapped table, and no VRAM to copy it into"; - return false; - } - cudaFreeHost(host_); // the destructor frees dev_ when host_ is null - host_ = nullptr; - std::fprintf(stderr, "strata: native embedding: no device alias for the mapped table, kept in VRAM\n"); - } -#else - if (cudaHostGetDevicePointer(&d, host_, 0) != cudaSuccess) { - err = "native embedding: no device alias for the mapped table"; - return false; - } -#endif - dev_ = d; - } - type_ = (int) t->type; - n_embd_ = n_embd; - n_vocab_ = n_vocab; - return true; - } catch (const std::exception& e) { - err = std::string("native embedding: ") + e.what(); - return false; - } -} - -void NativeEmbed::gather_dev(const int32_t* tokens, int64_t n_tok, float* out, void* stream) const { - strata::kernels::iq_embed_rows(type_, dev_, row_, tokens, n_tok, n_embd_, out, stream); -} - -void NativeEmbed::gather_one(int64_t token, float* out, void* stream) const { - strata::kernels::iq_dequant_f32(type_, (const uint8_t*) dev_ + (size_t) token * row_, n_embd_, out, stream); -} - -} // namespace strata::core diff --git a/src/core/overlap_main.cpp b/src/core/overlap_main.cpp deleted file mode 100644 index f5981c1..0000000 --- a/src/core/overlap_main.cpp +++ /dev/null @@ -1,169 +0,0 @@ -// src/core/overlap_main.cpp - `strata-overlap`: does streaming an expert overlap with computing on it? -// -// THE ARCHITECTURE'S CENTRAL PREMISE. Only (1 - h) of a token's expert weights are in VRAM, so the rest must -// cross the bus while the GPU is working. If the copy and the compute do not overlap, the per-token cost is -// their SUM; if they do, it is their MAXIMUM. L3 measured the stream at 4.07 ms/token (design h) and L5 the -// matvec at 27.9 ms/token, so serial would be ~32 ms and overlapped ~28 - but those are the STEADY-STATE -// numbers for a whole token; at one expert's granularity the ratio is completely different and that is what -// decides how the loop must be built. -// -// Measured against a SERIAL baseline in the same process, because the interesting quantity is the ratio and -// not the absolute figure - and L6 established that absolute figures on this machine move by 20%. -#include "strata/core/pinned.hpp" -#include "strata/kernels/s_gemv.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace { - -void check(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -struct Timing { - double seconds = 0; - const char* name = ""; -}; - -} // namespace - -int main(int argc, char** argv) { - std::string path; - int experts = 64; - int threads_per_row = 32; - for (int i = 1; i < argc; ++i) { - const std::string a = argv[i]; - auto val = [&]() -> 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 == "--file") path = val(); - else if (a == "--experts") experts = std::atoi(val()); - else if (a == "--tpr") threads_per_row = std::atoi(val()); - else { - std::fprintf(stderr, "usage: strata-overlap --file experts.bin [--experts N] [--tpr N]\n"); - return 2; - } - } - if (path.empty()) { std::fprintf(stderr, "--file is required\n"); return 2; } - - // One ROLE's worth of S2 weights: gate is [n_embd 2560] x [ff 640] = 1,638,400 weights = 460,800 B of - // codes at 4 codes per byte, plus 40 scales per row. - const long long n_in = 2560, n_out = 640; - const uint64_t role_codes = (uint64_t) n_out * n_in / 4; - const uint64_t role_bytes = role_codes + (uint64_t) n_out * (n_in / 64) * 4; - std::printf("per role: %lld x %lld S2 weights, %.1f KB of planes\n", n_in, n_out, role_bytes / 1024.0); - - // host side: `experts` blobs read into a pinned arena, and the S2 planes the GEMV will read - strata::core::PinnedArena arena((uint64_t) experts * role_codes); - if (!arena.valid()) { std::fprintf(stderr, "arena allocation failed\n"); return 1; } - { - std::ifstream f(path, std::ios::binary); - if (!f) { std::fprintf(stderr, "cannot open %s\n", path.c_str()); return 1; } - // take the first `experts` blobs' worth of CODE bytes, pretending each is a role's plane: the bytes - // are real Q2_0 codes, so the kernel decodes real data and no cache-friendly pattern is invented - for (int i = 0; i < experts; ++i) { - f.seekg((std::streamoff) i * 1382400); - f.read((char*) arena.data() + (uint64_t) i * role_codes, (std::streamsize) role_codes); - if ((uint64_t) f.gcount() != role_codes) { - std::fprintf(stderr, "short read on expert %d\n", i); - return 1; - } - } - } - std::printf("loaded %d role-sized planes into a %s arena\n", experts, arena.note.c_str()); - - // device side: double buffered codes, plus x / scales / y - uint8_t* d_codes[2] = {nullptr, nullptr}; - for (int b = 0; b < 2; ++b) check(cudaMalloc(&d_codes[b], role_codes), "cudaMalloc codes"); - uint16_t* d_x = nullptr; - float *d_scales = nullptr, *d_y = nullptr; - check(cudaMalloc(&d_x, n_in * sizeof(uint16_t)), "cudaMalloc x"); - check(cudaMalloc(&d_scales, (size_t) n_out * (n_in / 64) * sizeof(float)), "cudaMalloc scales"); - check(cudaMalloc(&d_y, n_out * sizeof(float)), "cudaMalloc y"); - std::vector hx((size_t) n_in, 0x3C00); - std::vector hs((size_t) n_out * (size_t) (n_in / 64), 0.001f); - check(cudaMemcpy(d_x, hx.data(), hx.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "copy x"); - check(cudaMemcpy(d_scales, hs.data(), hs.size() * sizeof(float), cudaMemcpyHostToDevice), "copy scales"); - - cudaStream_t s_copy{}, s_comp{}; - check(cudaStreamCreate(&s_copy), "stream copy"); - check(cudaStreamCreate(&s_comp), "stream compute"); - const strata::kernels::SForm form{2, -1, 64, strata::kernels::Codebook::Affine, false}; - - // ---- SERIAL: the same operations on the SAME stream, so the GPU runs them one after another ---- - // - // NOT a sync-per-iteration loop. The first version waited with `cudaStreamSynchronize` after every copy and - // measured 234.8 us/expert where a copy plus a GEMV is ~43 us: the baseline was dominated by the CPU - // round-trip, so the ratio of 0.095 mostly measured "with syncs" against "without syncs". Putting both - // operations on one stream expresses the same dependency with NO CPU involvement and ONE sync at the end, - // which is what makes the comparison about overlap rather than about synchronisation. - check(cudaStreamSynchronize(0), "pre sync"); - auto t0 = std::chrono::steady_clock::now(); - for (int i = 0; i < experts; ++i) { - check(cudaMemcpyAsync(d_codes[0], arena.data() + (uint64_t) i * role_codes, role_codes, - cudaMemcpyHostToDevice, 0), - "serial copy"); - strata::kernels::s_gemv_split_async(d_x, d_codes[0], d_scales, nullptr, d_y, n_in, n_out, form, - threads_per_row, (void*) (cudaStream_t) 0); - } - check(cudaStreamSynchronize(0), "serial final sync"); - const double serial = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - - // ---- OVERLAPPED: copy the next one while computing on the current one ---- - check(cudaStreamSynchronize(0), "pre sync 2"); - cudaEvent_t ev[2]; - for (int b = 0; b < 2; ++b) check(cudaEventCreateWithFlags(&ev[b], cudaEventDisableTiming), "event"); - t0 = std::chrono::steady_clock::now(); - check(cudaMemcpyAsync(d_codes[0], arena.data(), role_codes, cudaMemcpyHostToDevice, s_copy), "prologue"); - check(cudaEventRecord(ev[0], s_copy), "prologue event"); - for (int i = 0; i < experts; ++i) { - const int cur = i & 1, nxt = (i + 1) & 1; - if (i + 1 < experts) { - check(cudaMemcpyAsync(d_codes[nxt], arena.data() + (uint64_t) (i + 1) * role_codes, role_codes, - cudaMemcpyHostToDevice, s_copy), - "overlap copy"); - check(cudaEventRecord(ev[nxt], s_copy), "overlap event"); - } - // the compute stream must not start row i until its codes have landed - check(cudaStreamWaitEvent(s_comp, ev[cur], 0), "wait"); - // a hand-written launch so it goes on s_comp; `s_gemv` synchronises on the default stream - strata::kernels::s_gemv_split_async(d_x, d_codes[cur], d_scales, nullptr, d_y, n_in, n_out, form, - threads_per_row, (void*) s_comp); - } - check(cudaStreamSynchronize(s_comp), "final sync"); - check(cudaStreamSynchronize(s_copy), "final sync 2"); - const double overlap = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - - std::printf("\n serial %8.3f ms for %d experts (%.1f us/expert)\n", serial * 1000, experts, - serial * 1e6 / experts); - std::printf(" overlapped %8.3f ms for %d experts (%.1f us/expert)\n", overlap * 1000, experts, - overlap * 1e6 / experts); - std::printf(" ratio %.3f (1.00 = no overlap at all, <1.00 = overlap)\n", overlap / serial); - std::printf("\nNOTE: the OVERLAPPED loop launches on `s_comp` without synchronising, so the copy and the\n" - " compute really are concurrent; the serial loop waits after each step. What this does NOT\n" - " model is the CPU expert path, the router, or the fact that a real token has 1440 roles to\n" - " stream rather than %d.\n", experts); - - for (int b = 0; b < 2; ++b) { - cudaFree(d_codes[b]); - cudaEventDestroy(ev[b]); - } - cudaFree(d_x); - cudaFree(d_scales); - cudaFree(d_y); - cudaStreamDestroy(s_copy); - cudaStreamDestroy(s_comp); - return 0; -} diff --git a/src/core/peer_experts.cpp b/src/core/peer_experts.cpp deleted file mode 100644 index bf6284a..0000000 --- a/src/core/peer_experts.cpp +++ /dev/null @@ -1,325 +0,0 @@ -// src/core/peer_experts.cpp - see include/strata/core/peer_experts.hpp. -#include "strata/core/peer_experts.hpp" - -#include "strata/kernels/cpu/expert_layout.hpp" -#include "strata/kernels/elementwise.hpp" -#include "strata/kernels/iq_kernels.hpp" -#include "strata/kernels/quantize_act.hpp" -#include "strata/kernels/s2_expert_grouped.hpp" - -#include -#include -#include -#include -#include -#include - -namespace strata::core { - -static bool g_peer_portable = false; -void set_peer_portable(bool on) { g_peer_portable = on; } -bool peer_portable() { return g_peer_portable; } - -namespace { - -constexpr int64_t H = strata::kernels::cpu::H; -constexpr int64_t CAP = strata::kernels::cpu::MAXT * 10; // entries per layer: MAXT tokens x top-10 - -struct Meta { // one block, uploaded with one copy per layer - unsigned long long ptr[CAP]; - int32_t start[CAP + 1]; - int32_t dst[CAP]; - int32_t tok[CAP]; - int32_t count[4]; // [0] groups, [1] entries - int32_t out_row[CAP]; // multi-GPU: compact row -> entry row in the host `out` -}; - -/// Switches the calling thread to `dev` and back. The engine's own thread lives on device 0. -struct On { - int prev = 0; - explicit On(int dev) { cudaGetDevice(&prev); if (prev != dev) cudaSetDevice(dev); } - ~On() { int cur = 0; cudaGetDevice(&cur); if (cur != prev) cudaSetDevice(prev); } -}; - -bool ck(cudaError_t e, const char* what, std::string& err) { - if (e == cudaSuccess) return true; - err = std::string("peer experts: ") + what + ": " + cudaGetErrorString(e); - return false; -} - -} // namespace - -PeerExperts::~PeerExperts() { close(); } - -void PeerExperts::close() { - if (device_ < 0) return; - { - On on(device_); - if (stream_) cudaStreamSynchronize(stream_); - if (refill_) cudaStreamSynchronize(refill_); - cache_.close(); - if (d_x_) cudaFree(d_x_); - if (d_out_) cudaFree(d_out_); - if (d_meta_) cudaFree(d_meta_); - if (d_q8_) cudaFree(d_q8_); - if (d_scratch_) cudaFree(d_scratch_); - if (h_x_) cudaFreeHost(h_x_); - if (h_out_) cudaFreeHost(h_out_); - if (h_meta_) cudaFreeHost(h_meta_); - if (refill_ev_) cudaEventDestroy(refill_ev_); - if (stream_) cudaStreamDestroy(stream_); - if (refill_) cudaStreamDestroy(refill_); - } - d_x_ = d_out_ = h_x_ = h_out_ = nullptr; - d_meta_ = h_meta_ = d_scratch_ = nullptr; - d_q8_ = nullptr; - stream_ = refill_ = nullptr; - refill_ev_ = nullptr; - device_ = -1; -} - -bool PeerExperts::open(int device, const std::vector>& ranked, const ExpertCache& primary, - ExpertSource& src, int64_t n_layers, int64_t n_expert, int reserve_mib, int64_t max_slots, - std::string& err) { - close(); - int count = 0; - if (!ck(cudaGetDeviceCount(&count), "cudaGetDeviceCount", err)) return false; - if (device < 1 || device >= count) { - err = "peer experts: CUDA device " + std::to_string(device) + " is not visible (" + std::to_string(count) + - " devices; set CUDA_VISIBLE_DEVICES)"; - return false; - } - const auto& lay = strata::kernels::cpu::expert_layout(); - n_layers_ = n_layers; - n_expert_ = n_expert; - src_ = &src; - res_.assign((size_t) (n_layers * n_expert), kNotResident); - { // direct access both ways (NVLink or another P2P path): the prompt path copies activations and results over it - int a = 0, b = 0; - cudaDeviceCanAccessPeer(&a, 0, device); - cudaDeviceCanAccessPeer(&b, device, 0); - p2p_ = a && b; - if (p2p_) { - On on0(0); - cudaError_t e0 = cudaDeviceEnablePeerAccess(device, 0); - if (e0 == cudaErrorPeerAccessAlreadyEnabled) { cudaGetLastError(); e0 = cudaSuccess; } - On on1(device); - cudaError_t e1 = cudaDeviceEnablePeerAccess(0, 0); - if (e1 == cudaErrorPeerAccessAlreadyEnabled) { cudaGetLastError(); e1 = cudaSuccess; } - p2p_ = e0 == cudaSuccess && e1 == cudaSuccess; - } - } - On on(device); - device_ = device; - // scratch first, so the slots take what is really left - int64_t ff = strata::kernels::cpu::FF; - if (lay.native) - for (const auto& f : lay.fmt) ff = std::max(ff, f.n_ff); - const size_t scratch = std::max((size_t) strata::kernels::moe_hit_grouped_scratch_bytes(CAP, H, ff), - strata::kernels::native_expert_scratch_bytes(CAP, ff)); - const bool alloc_ok = - ck(cudaStreamCreateWithFlags(&stream_, cudaStreamNonBlocking), "stream", err) && - ck(cudaStreamCreateWithFlags(&refill_, cudaStreamNonBlocking), "refill stream", err) && - ck(cudaEventCreateWithFlags(&refill_ev_, cudaEventDisableTiming), "event", err) && - ck(cudaHostAlloc((void**) &h_x_, (size_t) CAP * H * sizeof(float), cudaHostAllocPortable | cudaHostAllocMapped), "input staging", err) && - ck(cudaHostAlloc((void**) &h_out_, (size_t) CAP * H * sizeof(float), cudaHostAllocPortable | cudaHostAllocMapped), "result staging", err) && - ck(cudaHostAlloc(&h_meta_, sizeof(Meta), cudaHostAllocPortable | cudaHostAllocMapped), "plan staging", err) && - ck(cudaMalloc((void**) &d_x_, (size_t) CAP * H * sizeof(float)), "input", err) && - ck(cudaMalloc((void**) &d_out_, (size_t) CAP * H * sizeof(float)), "result", err) && - ck(cudaMalloc(&d_meta_, sizeof(Meta)), "plan", err) && - ck(cudaMalloc((void**) &d_q8_, (size_t) CAP * (H / 32) * 36), "activations", err) && - ck(cudaMalloc(&d_scratch_, scratch), "scratch", err); - if (!alloc_ok) { close(); return false; } - - // the pairs the primary does not hold, in rank order, as many as fit - size_t free_b = 0, total_b = 0; - if (!ck(cudaMemGetInfo(&free_b, &total_b), "cudaMemGetInfo", err)) { close(); return false; } - const uint64_t reserve = (uint64_t) std::max(reserve_mib, 128) << 20; - const uint64_t budget = free_b > reserve ? free_b - reserve : 0; - std::vector> pick; - std::vector sizes; - uint64_t used = 0; - for (const auto& pr : ranked) { - if (primary.slot_of(pr.first, pr.second) >= 0) continue; - const uint64_t b = lay.blob_bytes(pr.first); - const uint64_t b256 = lay.native ? (b + 255) / 256 * 256 : lay.max_blob; - if (used + b256 > budget) break; - if (max_slots > 0 && (int64_t) pick.size() >= max_slots) break; - used += b256; - pick.push_back(pr); - sizes.push_back((int64_t) b); - } - if (pick.empty()) { err = "peer experts: no room or no expert left for the peer"; close(); return false; } - const bool opened = lay.native ? cache_.open_sized(sizes, n_layers, n_expert, err) - : cache_.open((int64_t) pick.size(), n_layers, n_expert, (int64_t) lay.max_blob, err); - if (!opened) { err = "peer experts: " + err; close(); return false; } - // open() zeroes the arena with cudaMemset on the legacy stream, which is not ordered against the non-blocking - // refill stream: wait for it, or the zeroing can land on top of the fills - if (!ck(cudaDeviceSynchronize(), "arena zeroing", err)) { close(); return false; } - for (const auto& pr : pick) { - const int32_t slot = cache_.admit(pr.first, pr.second); - const uint8_t* b = src.blob(pr.first, pr.second); - if (slot < 0 || b == nullptr || !cache_.fill_slot(slot, b, refill_, err, (int64_t) lay.blob_bytes(pr.first))) { - err = "peer experts: fill failed: " + err; - close(); - return false; - } - res_[(size_t) (pr.first * n_expert + pr.second)] = slot; - } - if (!ck(cudaStreamSynchronize(refill_), "fill", err)) { close(); return false; } - const auto& f0 = pick.front(); - if (!cache_.verify_slot(res_[(size_t) (f0.first * n_expert + f0.second)], src.blob(f0.first, f0.second), err, - (int64_t) lay.blob_bytes(f0.first))) { - err = "peer experts: " + err; - close(); - return false; - } - resident_ = (int64_t) pick.size(); - return true; -} - -bool PeerExperts::launch(int64_t layer, const float* x, const int32_t* ids, int64_t n_tok, int64_t k, - const int32_t* kind, std::string& err, float* out) { - static const bool direct_env = [] { const char* v = std::getenv("STRATA_PEER_DIRECT"); return v == nullptr || std::atoi(v) != 0; }(); - const bool direct = direct_env && out != nullptr; - launched_direct_ = false; - launched_rows_ = 0; - row_of_.clear(); - const int64_t n = n_tok * k; - if (n > CAP) { err = "peer experts: window too large"; return false; } - Meta& m = *(Meta*) h_meta_; - int groups = 0, rows = 0; - // distinct experts in routing order; each one's entries become compact rows - for (int64_t i = 0; i < n; ++i) { - if (kind[i] != 2) continue; - bool seen = false; - for (int64_t j = 0; j < i; ++j) - if (kind[j] == 2 && ids[j] == ids[i]) { seen = true; break; } - if (seen) continue; - const int32_t slot = res_[(size_t) (layer * n_expert_ + ids[i])]; - if (slot < 0) { err = "peer experts: an entry was planned for the peer but is not resident"; return false; } - m.ptr[groups] = (unsigned long long) cache_.device_slot(slot); - m.start[groups] = rows; - for (int64_t j = i; j < n; ++j) - if (kind[j] == 2 && ids[j] == ids[i]) { - m.dst[rows] = rows; - m.tok[rows] = (int32_t) (j / k); - m.out_row[rows] = (int32_t) j; - row_of_.push_back((int32_t) j); - ++rows; - } - ++groups; - ++experts_; - } - if (groups == 0) return true; - m.start[groups] = rows; - m.count[0] = groups; - m.count[1] = rows; - entries_ += rows; - launched_rows_ = rows; - // direct: x is the verifier's pinned (portable) doorbell row block - copied from where it is - if (!direct) std::memcpy(h_x_, x, (size_t) (n_tok * H) * sizeof(float)); - On on(device_); - const cudaStream_t s = stream_; - if (!ck(cudaMemcpyAsync(d_x_, direct ? x : h_x_, (size_t) (n_tok * H) * sizeof(float), cudaMemcpyHostToDevice, s), "input", err) || - !ck(cudaMemcpyAsync(d_meta_, h_meta_, sizeof(Meta), cudaMemcpyHostToDevice, s), "plan", err)) - return false; - Meta* dm = (Meta*) d_meta_; - const auto& lay = strata::kernels::cpu::expert_layout(); - if (lay.native) { - strata::kernels::quantize_q8_1_rows(d_x_, n_tok, H, d_q8_, s); - const auto& f = lay.fmt[(size_t) layer]; - const auto L = strata::kernels::native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff); - strata::kernels::native_expert_grouped(L, dm->ptr, dm->start, dm->count, dm->dst, dm->tok, groups, rows, d_q8_, - d_scratch_, d_out_, s); - } else { - err = "peer experts: only native packs are supported"; - return false; - } - if (direct) { // the rows straight into the host `out` (zero-copy, coalesced float4 writes) - try { - strata::kernels::scatter_rows_f32(d_out_, out, dm->out_row, rows, H, s); - } catch (const std::exception& e) { err = std::string("peer experts: scatter: ") + e.what(); return false; } - launched_direct_ = true; - return true; - } - return ck(cudaMemcpyAsync(h_out_, d_out_, (size_t) rows * H * sizeof(float), cudaMemcpyDeviceToHost, s), - "results", err); -} - -bool PeerExperts::finish(float* out, std::string& err) { - if (launched_rows_ == 0) return true; - const auto t0 = std::chrono::steady_clock::now(); - { - On on(device_); - // spin on the stream (a blocking sync would sleep the pool thread and wake it late) - cudaError_t e; - while ((e = cudaStreamQuery(stream_)) == cudaErrorNotReady) { - } - if (!ck(e, "finish", err)) return false; - } - ms_wait += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - if (launched_direct_) { launched_rows_ = 0; return true; } - for (size_t r = 0; r < row_of_.size(); ++r) - std::memcpy(out + (size_t) row_of_[r] * H, h_out_ + r * H, (size_t) H * sizeof(float)); - launched_rows_ = 0; - return true; -} - -bool PeerExperts::adapt(const float* usage, const int32_t* res0, int max_swaps, std::string& err) { - if (!pending_.empty() || max_swaps <= 0) return true; - const auto& lay = strata::kernels::cpu::expert_layout(); - struct Swap { float gain; int32_t layer, in, out; }; - std::vector swaps; - std::vector> cand, vict; - for (int64_t l = 0; l < n_layers_; ++l) { - cand.clear(); - vict.clear(); - const float* u = usage + l * n_expert_; - const int32_t* r0 = res0 + l * n_expert_; - const int32_t* r1 = res_.data() + l * n_expert_; - for (int32_t e = 0; e < (int32_t) n_expert_; ++e) { - if (r1[e] >= 0) vict.emplace_back(u[e], e); - else if (r0[e] < 0 && u[e] >= 2.0f) cand.emplace_back(u[e], e); - } - if (cand.empty() || vict.empty()) continue; - std::sort(cand.begin(), cand.end(), [](auto& a, auto& b) { return a.first > b.first; }); - const size_t nc = std::min(cand.size(), vict.size()); - std::partial_sort(vict.begin(), vict.begin() + (ptrdiff_t) nc, vict.end(), - [](auto& a, auto& b) { return a.first < b.first; }); - for (size_t i = 0; i < nc; ++i) { - if (cand[i].first < vict[i].first + 1.5f) break; - swaps.push_back({cand[i].first - vict[i].first, (int32_t) l, cand[i].second, vict[i].second}); - } - } - if (swaps.empty()) return true; - std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; }); - if ((int) swaps.size() > max_swaps) swaps.resize((size_t) max_swaps); - On on(device_); - for (const Swap& s : swaps) { - const size_t in = (size_t) (s.layer * n_expert_ + s.in), out = (size_t) (s.layer * n_expert_ + s.out); - const int32_t slot = res_[out]; - const uint8_t* b = src_->blob(s.layer, s.in); - if (slot < 0 || b == nullptr) continue; - if (!ck(cudaMemcpyAsync(cache_.device_slot(slot), b, (size_t) lay.blob_bytes(s.layer), cudaMemcpyHostToDevice, - refill_), "refill", err)) - return false; - res_[out] = kNotResident; // evicted now: the CPU computes it meanwhile - pending_.emplace_back((int32_t) in, slot); - ++swaps_; - } - return ck(cudaEventRecord(refill_ev_, refill_), "refill event", err); -} - -void PeerExperts::apply_pending(bool wait) { - if (pending_.empty()) return; - { - On on(device_); - if (wait) cudaEventSynchronize(refill_ev_); - else if (cudaEventQuery(refill_ev_) != cudaSuccess) return; - } - for (const auto& [i, slot] : pending_) res_[(size_t) i] = slot; - pending_.clear(); -} - -} // namespace strata::core diff --git a/src/core/pinned.cu b/src/core/pinned.cu deleted file mode 100644 index fbc3b3c..0000000 --- a/src/core/pinned.cu +++ /dev/null @@ -1,725 +0,0 @@ -// src/core/pinned.cu - P2.S1: the pinned host arena and the parallel expert load. -#include "strata/core/pinned.hpp" -#include "strata/platform/memory.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -// Loader fix: `fseek`/`ftell` are 32-bit on Windows by default (and the pack is 42.9 GB), and the 64-bit -// spelling is not the same on the two platforms the engine builds for. -#ifdef _WIN32 -#define STRATA_FSEEK64(f, o) _fseeki64((f), (long long) (o), SEEK_SET) -#else -#define STRATA_FSEEK64(f, o) fseeko((f), (off_t) (o), SEEK_SET) -#endif - -#ifdef _WIN32 -#include -#else -#include -#include -#include -#include -#include -#ifndef MAP_HUGE_2MB -#define MAP_HUGE_2MB (21 << 26) -#endif -#endif - -namespace strata::core { - -namespace { - -constexpr uint64_t kSharedArenaHeaderBytes = 4096; -constexpr char kSharedArenaMagic[16] = "STRATA-ARENA-V1"; - -struct SharedArenaHeader { - char magic[16]; - uint32_t version; - uint32_t header_bytes; - uint64_t arena_bytes; - uint64_t pack_hash; - uint64_t reserved[4]; -}; -static_assert(sizeof(SharedArenaHeader) <= kSharedArenaHeaderBytes); - -// A 2 MB-aligned reservation. Large pages first, then the largest alignment the OS will give us for free. -// A non-empty shared_file instead maps one file whose first 4 KiB identify the pack and whose remaining bytes -// are the resident arena. This shared-file layout is intended for tmpfs (/dev/shm); hugetlbfs would need -// hugepage-aligned file size and arena offset rather than the 4 KiB header layout used here. -void* reserve(uint64_t bytes, PageBacking& got, std::string& note, const std::string& shared_file, - uint64_t shared_pack_hash, void*& mapping_base, uint64_t& mapping_bytes) { - mapping_base = nullptr; - mapping_bytes = 0; -#ifdef _WIN32 - if (!shared_file.empty()) { - note = "shared-file arena backing is not implemented on Windows"; - return nullptr; - } - // MEM_LARGE_PAGES needs SeLockMemoryPrivilege. Having it assigned to the account is not enough: the - // PROCESS must enable it in its own token (AdjustTokenPrivileges) before VirtualAlloc, or the call fails. - // An account without the assignment, or a failure to enable, leaves the process as it was: VirtualAlloc - // then refuses and the 4 KB fallback below runs - that is the EXPECTED outcome on a desktop. - { - HANDLE tok = nullptr; - if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &tok)) { - TOKEN_PRIVILEGES tp{}; - tp.PrivilegeCount = 1; - if (LookupPrivilegeValueW(nullptr, L"SeLockMemoryPrivilege", &tp.Privileges[0].Luid)) { - tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; - if (!AdjustTokenPrivileges(tok, FALSE, &tp, 0, nullptr, nullptr) && GetLastError() != ERROR_NOT_ALL_ASSIGNED) - (void) 0; // nothing actionable: the large-page attempt below reports the outcome - } - CloseHandle(tok); - } - } - // MEM_LARGE_PAGES needs SeLockMemoryPrivilege; a normal account does not have it and VirtualAlloc then - // fails with ERROR_PRIVILEGE_NOT_HELD. That is the EXPECTED outcome on a desktop, not an error. - SIZE_T large = GetLargePageMinimum(); - // A/B switch: STRATA_NO_LARGEPAGES=1 skips the large-page attempt, same run, same boot. - if (large > 0 && std::getenv("STRATA_NO_LARGEPAGES") == nullptr) { - // MEM_LARGE_PAGES requires the allocation size to be an exact multiple of the large page size - - // anything else is ERROR_INVALID_PARAMETER (87), which reads like a privilege problem but is not. - // Round up: the slack is under 2 MB and the tail stays unused. - const SIZE_T lbytes = (SIZE_T) (((SIZE_T) bytes + large - 1) / large * large); - void* p = VirtualAlloc(nullptr, lbytes, MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES, - PAGE_READWRITE); - if (p) { - got = PageBacking::LargePages; - note = "large pages (" + std::to_string((unsigned long long) large) + " B)"; - return p; - } - // 1450 (ERROR_NO_SYSTEM_RESOURCES) is the large-page pool saying no, 87 is a size that is not a - // multiple of the minimum, 1314 is the privilege: without the byte count the three read as one bug. - note = "large pages refused for " + std::to_string((unsigned long long) lbytes) + " B (GetLargePageMinimum=" + - std::to_string((unsigned long long) large) + ", VirtualAlloc error " + - std::to_string((unsigned long long) GetLastError()) + "); using 4 KB pages"; - } else if (std::getenv("STRATA_NO_LARGEPAGES") != nullptr) { - note = "large pages skipped (STRATA_NO_LARGEPAGES); using 4 KB pages"; - } else { - note = "this system has no large-page minimum; using 4 KB pages"; - } - void* p = VirtualAlloc(nullptr, (SIZE_T) bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); - got = PageBacking::NormalPages; - return p; -#else - if (!shared_file.empty()) { - if (shared_pack_hash == 0) { - note = "shared arena requires a nonzero pack hash"; - return nullptr; - } - if (bytes > UINT64_MAX - kSharedArenaHeaderBytes) { - note = "shared arena size overflows its header"; - return nullptr; - } - const uint64_t file_bytes = kSharedArenaHeaderBytes + bytes; - const int fd = open(shared_file.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600); - if (fd < 0) { - note = "cannot open shared arena " + shared_file + ": " + std::strerror(errno); - return nullptr; - } - struct stat st{}; - if (fstat(fd, &st) != 0) { - const int e = errno; - close(fd); - note = "cannot stat shared arena " + shared_file + ": " + std::strerror(e); - return nullptr; - } - - const bool fresh = st.st_size == 0; - if (fresh) { - if (ftruncate(fd, (off_t) file_bytes) != 0) { - const int e = errno; - close(fd); - note = "cannot size shared arena " + shared_file + ": " + std::strerror(e); - return nullptr; - } - SharedArenaHeader hdr{}; - std::memcpy(hdr.magic, kSharedArenaMagic, sizeof hdr.magic); - hdr.version = 1; - hdr.header_bytes = (uint32_t) kSharedArenaHeaderBytes; - hdr.arena_bytes = bytes; - hdr.pack_hash = shared_pack_hash; - const ssize_t written = pwrite(fd, &hdr, sizeof hdr, 0); - if (written != (ssize_t) sizeof hdr) { - const int e = errno; - close(fd); - note = "cannot write shared arena header " + shared_file + ": " + - (written < 0 ? std::string(std::strerror(e)) : std::string("short write")); - return nullptr; - } - } else { - if (st.st_size < 0 || (uint64_t) st.st_size != file_bytes) { - close(fd); - note = "shared arena " + shared_file + " is " + - std::to_string((unsigned long long) st.st_size) + " B, expected " + - std::to_string((unsigned long long) file_bytes) + " B including its header"; - return nullptr; - } - SharedArenaHeader hdr{}; - const ssize_t got_header = pread(fd, &hdr, sizeof hdr, 0); - if (got_header != (ssize_t) sizeof hdr || - std::memcmp(hdr.magic, kSharedArenaMagic, sizeof hdr.magic) != 0 || - hdr.version != 1 || hdr.header_bytes != kSharedArenaHeaderBytes || hdr.arena_bytes != bytes) { - close(fd); - note = "shared arena " + shared_file + " has an incompatible or missing header"; - return nullptr; - } - if (hdr.pack_hash != shared_pack_hash) { - close(fd); - char b[256]; - std::snprintf(b, sizeof b, - "shared arena %s was written for pack hash %016llx, expected %016llx", - shared_file.c_str(), (unsigned long long) hdr.pack_hash, - (unsigned long long) shared_pack_hash); - note = b; - return nullptr; - } - } - - void* map = mmap(nullptr, (size_t) file_bytes, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); - const int e = errno; - close(fd); - if (map == MAP_FAILED) { - note = "cannot map shared arena " + shared_file + ": " + std::strerror(e); - return nullptr; - } - mapping_base = map; - mapping_bytes = file_bytes; - got = PageBacking::NormalPages; - note = "MAP_SHARED file " + shared_file + " (pack hash checked)"; - return (uint8_t*) map + kSharedArenaHeaderBytes; - } - - // STRATA_NO_LARGEPAGES=1 is the same-run A/B switch the Windows branch documents; honor it - // here too, so the large-page path can be compared without changing the pool or rebooting. - if (std::getenv("STRATA_NO_LARGEPAGES") != nullptr) { - note = "large pages skipped (STRATA_NO_LARGEPAGES); using 4 KB pages"; - } else { - void* p = mmap(nullptr, bytes, PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_HUGE_2MB, -1, 0); - if (p != MAP_FAILED) { - got = PageBacking::LargePages; - note = "hugetlb 2 MB pages"; - return p; - } - // MAP_HUGETLB is all-or-nothing: a pool smaller than the mapping fails exactly like an absent - // one, and the old message guessed "no hugetlb pool configured" either way. Name the shortfall: - // how many 2 MiB pages the mapping needs against what vm.nr_hugepages actually holds. - const unsigned long long need = ((unsigned long long) bytes + (1ull << 21) - 1) / (1ull << 21); - unsigned long long pool = 0; - bool have_pool = false; - if (std::FILE* f = std::fopen("/proc/sys/vm/nr_hugepages", "r")) { - have_pool = std::fscanf(f, "%llu", &pool) == 1; - std::fclose(f); - } - note = "MAP_HUGETLB unavailable (needed " + std::to_string(need) + " 2 MiB pages, vm.nr_hugepages=" + - (have_pool ? std::to_string(pool) : std::string("?")) + "); using 4 KB pages"; - } - // No hugetlb mapping: a 2 MiB-aligned anonymous mapping with MADV_HUGEPAGE, so transparent huge pages back - // it where THP is "madvise" (the common distro default). The CPU expert pool streams whole experts out of - // this arena; with 4 KB pages every 3 MB expert costs ~750 TLB misses. - constexpr uint64_t kAlign = 2ull << 20; - const uint64_t padded = bytes + kAlign; - void* raw = mmap(nullptr, padded, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - got = PageBacking::NormalPages; - if (raw == MAP_FAILED) return nullptr; - const uintptr_t start = (uintptr_t) raw; - const uintptr_t aligned = (start + kAlign - 1) & ~(uintptr_t) (kAlign - 1); - if (aligned > start) munmap(raw, aligned - start); - const uintptr_t end = aligned + bytes, raw_end = start + padded; - if (raw_end > end) munmap((void*) end, raw_end - end); - void* p = (void*) aligned; - if (std::getenv("STRATA_NO_LARGEPAGES") == nullptr && madvise(p, bytes, MADV_HUGEPAGE) == 0) { - const std::string four_k = "; using 4 KB pages"; - if (note.size() >= four_k.size() && note.compare(note.size() - four_k.size(), four_k.size(), four_k) == 0) - note.resize(note.size() - four_k.size()); - note += "; transparent huge pages requested (MADV_HUGEPAGE)"; - } - return p; -#endif -} - -void release(void* p, uint64_t bytes) { - if (!p) return; -#ifdef _WIN32 - (void) bytes; - VirtualFree(p, 0, MEM_RELEASE); -#else - munmap(p, bytes); -#endif -} - -} // namespace - -uint64_t fnv1a64(const uint8_t* p, uint64_t n, uint64_t seed) { - uint64_t h = seed; - for (uint64_t i = 0; i < n; ++i) { - h ^= p[i]; - h *= 1099511628211ull; - } - return h; -} - -namespace { -bool clear_error() { (void) cudaGetLastError(); return true; } -} // namespace - -int arena_pin_cap_gib() { - const char* e = std::getenv("STRATA_ARENA_PIN_GIB"); - if (e == nullptr || *e == '\0') return -1; - if (std::string(e) == "auto") return -2; // #243: the Windows shared-memory budget sets the sliced pin's cap - const int v = std::atoi(e); - return v < 0 ? -1 : v; -} - -namespace { -#ifdef _WIN32 -// #243: how much of the arena the sliced registration may pin on Windows when the whole arena was refused. -// Page-locked memory the GPU maps is charged to its shared (non-local) WDDM segment; pinned slice by slice until -// the driver refused one (28 GiB of a 63 GB PC), that segment was left full and every later cudaMalloc failed -// "out of memory". 4 GiB of the budget stay free for what the engine allocates after the arena; without the DXGI -// numbers, RAM/2 - 8 GiB (the budget is about half the RAM). False: no limit could be worked out. -bool sliced_pin_limit(uint64_t& limit, std::string& why) { - constexpr uint64_t GiB = 1ull << 30; - char buf[256]; - int dev = 0; - cudaDeviceProp p{}; - uint64_t budget = 0, usage = 0; - std::string err = "no CUDA device properties"; - if (cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess && - strata::platform::gpu_shared_memory_budget(p.luid, budget, usage, err)) { - limit = budget > usage + 4 * GiB ? budget - usage - 4 * GiB : 0; - std::snprintf(buf, sizeof buf, "the GPU's shared-memory budget %.1f GiB - %.1f GiB in use - 4 GiB", - (double) budget / GiB, (double) usage / GiB); - why = buf; - return true; - } - (void) cudaGetLastError(); - const uint64_t ram = strata::platform::total_physical_memory(); - if (ram == 0) return false; - limit = ram / 2 > 8 * GiB ? ram / 2 - 8 * GiB : 0; - std::snprintf(buf, sizeof buf, "%s: RAM/2 - 8 GiB of %.1f GiB", err.c_str(), (double) ram / GiB); - why = buf; - return true; -} -#endif -} // namespace - -namespace { -std::vector uniform_bounds(uint64_t bytes, uint64_t slice) { - std::vector b; - if (slice == 0) return b; - for (uint64_t off = 0; off + slice <= bytes; off += slice) b.push_back(off); - if (!b.empty()) b.push_back(b.back() + slice); - return b; -} -} // namespace - -PinnedArena::PinnedArena(uint64_t bytes, uint64_t slice) : PinnedArena(bytes, uniform_bounds(bytes, slice)) { - if (slice_bytes) slice_bytes = slice; // sliced registration: record the uniform size -} - -PinnedArena::PinnedArena(uint64_t bytes, const std::vector& bounds, - uint64_t max_pinned_bytes, const std::string& shared_file, - uint64_t shared_pack_hash) : capacity(bytes) { - if (bytes == 0) return; - base = reserve(bytes, backing, note, shared_file, shared_pack_hash, mapping_base, mapping_bytes); - if (base != nullptr && mapping_base == nullptr) { - mapping_base = base; - mapping_bytes = bytes; - } - - // Register with CUDA BEFORE any page is touched: cudaHostRegister pins what is resident now, and a region - // that has already been faulted in page by page is far more expensive to register and may fail outright. - if (base) { - // #243: STRATA_ARENA_PIN_GIB=N caps the registration from the start where the caller set no cap - const int env_gib = arena_pin_cap_gib(); - uint64_t cap = max_pinned_bytes; - std::string cap_why = "by the engine (multi-GPU under WDDM, or remote experts)"; - if (cap == 0 && env_gib > 0) { - cap = (uint64_t) env_gib << 30; - cap_why = "by STRATA_ARENA_PIN_GIB"; - } - const bool capped = cap > 0 && cap < bytes && bounds.size() >= 2; - const cudaError_t e = capped ? cudaSuccess : - cudaHostRegister(base, (size_t) bytes, cudaHostRegisterPortable | cudaHostRegisterMapped); - if (!capped && e == cudaSuccess) { - note = "cudaHostRegister PORTABLE ok; " + note; - registered_bytes = bytes; - } else if (bounds.size() >= 2 && (capped || clear_error())) { - // Plan v0.3 P5: the whole range is refused, so pin it slice by slice from the start. The rest stays - // resident through the working-set lock below. (P6: slices may differ in size, one per layer.) - slice_bytes = 1; // sliced; the uniform constructor records the size - bool limited = capped; - uint64_t limit = cap; - std::string limit_why; -#ifdef _WIN32 - // #243 (opt-in, STRATA_ARENA_PIN_GIB=auto): not up to the driver's refusal but below the shared-memory - // budget, for a PC where the full sliced pin leaves WDDM refusing later allocations. Not the default: a - // 64 GB PC pins 30 GiB past that budget without trouble, and capping it at 26 cost ~20% prompt speed. - if (!capped && env_gib == -2) limited = sliced_pin_limit(limit, limit_why); -#endif - for (size_t i = 0; i + 1 < bounds.size(); ++i) { - const uint64_t off = bounds[i], n = bounds[i + 1] - bounds[i]; - if (limited && (off > limit || n > limit - off)) break; - if (cudaHostRegister((uint8_t*) base + off, (size_t) n, cudaHostRegisterPortable | cudaHostRegisterMapped) != cudaSuccess) { - (void) cudaGetLastError(); - break; - } - slice_starts.push_back(off); - registered_bytes = off + n; - ++registered_slices; - } - char gib[32]; - std::snprintf(gib, sizeof gib, "%.1f", (double) limit / (double) (1ull << 30)); - note = (capped ? "cudaHostRegister limited to " + std::to_string(cap >> 30) + " GiB " + cap_why + "; " : - "cudaHostRegister of the whole arena FAILED (" + std::string(cudaGetErrorString(e)) + "); " + - (limited ? "slices capped at " + std::string(gib) + " GiB (" + limit_why + - "; STRATA_ARENA_PIN_GIB=auto; N sets a cap; #243); " : std::string())) + - std::to_string(registered_slices) + " slices pinned (" + std::to_string(registered_bytes >> 30) + - " GiB); " + note; - if (registered_bytes < bytes) { - const char* env = std::getenv("STRATA_ARENA_LOCK"); - if (env == nullptr || std::string(env) != "0") { - const strata::platform::LockResult lr = - strata::platform::lock_resident((uint8_t*) base + registered_bytes, bytes - registered_bytes); - locked_bytes = lr.locked_bytes; - note = lr.note + "; " + note; - } - } - } else { - note = std::string("cudaHostRegister FAILED (") + cudaGetErrorString(e) + - ") - the arena is NOT pinned, so copies will be slow; " + note; - // **CONSUME THE ERROR, OR IT LIES ABOUT SOMETHING ELSE LATER.** - // - // `cudaGetLastError()` returns the last error and CLEARS it; until something reads it, the error - // state is sticky. This failure is caught and handled right here - the arena is simply not pinned - - // but leaving it set meant the next `cudaGetLastError()` in the engine, which is `gr_read`'s launch - // check, reported "out of memory" for kernels that allocate nothing. That cost a round: the arena - // was written off as not fitting the machine when in fact the only thing wrong was a stale error - // from this line. - // - // It is the same trap `gr.cu` warns about for ASYNC faults, in the other direction: a synchronous - // failure is sticky too, and it lies about where it happened just as convincingly. - (void) cudaGetLastError(); - // Plan v0.3 P0.1: keep it RESIDENT instead. Unpinned, Windows trims the arena under memory pressure - // and the CPU pool's rate then depends on the OS; locking it through the working set needs no - // special privilege. STRATA_ARENA_LOCK=0 is the A/B arm. - const char* env = std::getenv("STRATA_ARENA_LOCK"); - if (env == nullptr || std::string(env) != "0") { - const strata::platform::LockResult lr = strata::platform::lock_resident(base, bytes); - locked_bytes = lr.locked_bytes; - note = lr.note + "; " + note; - } else { - note = "arena lock disabled (STRATA_ARENA_LOCK=0); " + note; - } - } - } -} - -PinnedArena::~PinnedArena() { - if (base) { - if (locked_bytes) strata::platform::unlock_resident((uint8_t*) base + (slice_bytes ? registered_bytes : 0), locked_bytes); - if (slice_bytes) { - for (uint64_t off : slice_starts) cudaHostUnregister((uint8_t*) base + off); - } else { - cudaHostUnregister(base); - } - release(mapping_base ? mapping_base : base, mapping_bytes ? mapping_bytes : capacity); - base = nullptr; - mapping_base = nullptr; - mapping_bytes = 0; - } -} - -LoadStats load_experts(const std::string& path, uint8_t* dst, uint64_t blob_bytes, uint64_t blobs_per_layer, - uint64_t layers, int threads, uint64_t chunk) { - std::vector off((size_t) layers), n((size_t) layers, blobs_per_layer * blob_bytes); - for (uint64_t L = 0; L < layers; ++L) off[(size_t) L] = L * blobs_per_layer * blob_bytes; - return load_experts_ranges(path, dst, off, n, threads, chunk); -} - -LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std::vector& layer_off, - const std::vector& layer_bytes, int threads, uint64_t chunk) { - LoadStats st; - st.ok = false; -#ifdef _WIN32 - constexpr uint64_t kAlign = 4096; - if (((uintptr_t) dst % kAlign) != 0 || chunk == 0 || chunk % kAlign != 0) return st; - struct Piece { uint64_t off, n; }; - std::vector pieces; - uint64_t bytes = 0; - for (size_t L = 0; L < layer_off.size(); ++L) { - if (layer_off[L] % kAlign != 0 || layer_bytes[L] % kAlign != 0) return st; - for (uint64_t p = 0; p < layer_bytes[L]; p += chunk) - pieces.push_back({layer_off[L] + p, std::min(chunk, layer_bytes[L] - p)}); - bytes += layer_bytes[L]; - } - if (threads < 1) threads = 1; - const auto t0 = std::chrono::steady_clock::now(); - std::atomic next{0}; - std::mutex err_mu; - std::string err; - const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0); - std::vector wpath((size_t) (std::max)(wide, 1), L'\0'); - if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide); - auto worker = [&]() { - HANDLE h = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, - FILE_FLAG_NO_BUFFERING | FILE_FLAG_SEQUENTIAL_SCAN, nullptr); - if (h == INVALID_HANDLE_VALUE) { - std::lock_guard g(err_mu); - if (err.empty()) - err = "cannot open " + path + " unbuffered (error " + std::to_string((unsigned long long) GetLastError()) + ")"; - next = pieces.size(); - return; - } - for (;;) { - const size_t i = next.fetch_add(1); - if (i >= pieces.size()) break; - OVERLAPPED ov{}; - ov.Offset = (DWORD) pieces[i].off; - ov.OffsetHigh = (DWORD) (pieces[i].off >> 32); - DWORD got = 0; - if (!ReadFile(h, dst + pieces[i].off, (DWORD) pieces[i].n, &got, &ov) || got != pieces[i].n) { - std::lock_guard g(err_mu); - if (err.empty()) - err = "short unbuffered read at offset " + std::to_string(pieces[i].off) + ": got " + std::to_string(got) + - " of " + std::to_string(pieces[i].n) + " B (error " + - std::to_string((unsigned long long) GetLastError()) + ")"; - next = pieces.size(); - break; - } - } - CloseHandle(h); - }; - std::vector pool; - for (int i = 1; i < threads; ++i) pool.emplace_back(worker); - worker(); - for (auto& t : pool) t.join(); - st.layers = layer_off.size(); - if (!err.empty()) { - st.seconds = -1.0; - st.error = err; - return st; - } - st.ok = true; - st.bytes = bytes; - st.seconds = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); -#else - (void) path; (void) dst; (void) layer_off; (void) layer_bytes; (void) threads; (void) chunk; -#endif - return st; -} - -bool experts_unbuffered(const std::vector& files, uint64_t arena_bytes, std::string& why, - bool cache_counts, uint64_t read_bytes) { - const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); - if (env != nullptr && env[0] != '\0') { - why = std::string("STRATA_UNBUFFERED_LOAD=") + env; - return env[0] != '0'; - } -#ifdef _WIN32 - LARGE_INTEGER freq{}, a{}, b{}; - QueryPerformanceFrequency(&freq); - constexpr DWORD kRead = 64 << 10; - constexpr int kSamples = 16; - std::vector buf(kRead); - uint64_t total_bytes = 0; - int fast = 0, n = 0; - uint64_t seed = (uint64_t) GetTickCount64() * 6364136223846793005ull + 1442695040888963407ull; - for (const std::string& f : files) { - const int wide = MultiByteToWideChar(CP_UTF8, 0, f.c_str(), -1, nullptr, 0); - std::vector w((size_t) (std::max)(wide, 1), L'\0'); - if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, f.c_str(), -1, w.data(), wide); - HANDLE h = CreateFileW(w.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, - nullptr); - if (h == INVALID_HANDLE_VALUE) continue; - LARGE_INTEGER size{}; - GetFileSizeEx(h, &size); - total_bytes += (uint64_t) size.QuadPart; - // random offsets: a probe must not find the blocks an earlier probe put into the cache - for (int i = 0; i < kSamples && (uint64_t) size.QuadPart > 2ull * kRead; ++i) { - seed = seed * 6364136223846793005ull + 1442695040888963407ull; - const uint64_t off = ((seed >> 17) % ((uint64_t) size.QuadPart - kRead)) / kRead * kRead; - OVERLAPPED ov{}; - ov.Offset = (DWORD) off; - ov.OffsetHigh = (DWORD) (off >> 32); - DWORD got = 0; - QueryPerformanceCounter(&a); - const BOOL ok = ReadFile(h, buf.data(), kRead, &got, &ov); - QueryPerformanceCounter(&b); - if (!ok) continue; - ++n; - fast += (double) (b.QuadPart - a.QuadPart) * 1e6 / (double) freq.QuadPart < 30.0; - } - CloseHandle(h); - } - const bool cached = n > 0 && fast * 4 >= n * 3; - MEMORYSTATUSEX ms{}; - ms.dwLength = sizeof ms; - GlobalMemoryStatusEx(&ms); - const uint64_t avail = ms.ullAvailPhys; - // what the cache could keep beside the arena (~4 GiB for everything else) - const uint64_t need = read_bytes == kAllFileBytes ? total_bytes : read_bytes; - const bool keepable = strata::platform::file_cache_keeps(avail, arena_bytes, need); - char msg[256]; - if (read_bytes == kAllFileBytes) - std::snprintf(msg, sizeof msg, "%d of %d probe reads from the file cache; %.1f GiB available, %.1f GiB of files", - fast, n, (double) avail / (1ull << 30), (double) total_bytes / (1ull << 30)); - else - std::snprintf(msg, sizeof msg, "%.1f GiB available, %.1f GiB of it still to be taken by the RAM copy, %.1f GiB " - "of experts read from the files: the file cache %s keep them", - (double) avail / (1ull << 30), (double) arena_bytes / (1ull << 30), (double) need / (1ull << 30), - keepable ? "can" : "cannot"); - why = msg; - return (!cached || !cache_counts) && !keepable; -#else - (void) files; (void) arena_bytes; (void) cache_counts; (void) read_bytes; - why = "buffered (not Windows)"; - return false; -#endif -} - -LoadStats load_experts_ranges(const std::string& path, uint8_t* dst, const std::vector& layer_off, - const std::vector& layer_bytes, int threads, uint64_t chunk) { - LoadStats st; - const uint64_t layers = (uint64_t) layer_off.size(); - st.layers = layers; - st.bytes = 0; - for (uint64_t b : layer_bytes) st.bytes += b; - if (threads < 1) threads = 1; - - const auto t0 = std::chrono::steady_clock::now(); - std::vector layer_hash((size_t) layers, 1469598103934665603ull); - std::atomic next_layer{0}; - std::atomic read_ns_sum{0}; // summed over the threads: see LoadStats::read_seconds - std::atomic copy_ns_sum{0}; - std::mutex err_mu; - std::string err; - - auto worker = [&]() { - std::vector buf((size_t) chunk); - // One handle per thread, seeked once per layer: a shared handle would need a lock around the seek and - // would serialise the very thing the threads are here to parallelise. `fread` on a `FILE*` rather than - // `std::ifstream`: see the header - MSVC's `basic_filebuf::xsgetn` splits any request larger than - // `_INTERNAL_BUFSIZ - 1` into 4095-byte freads, which turned one 8 MiB chunk into ~2048 4 KiB reads. - // `fread` sees a request bigger than the stream buffer and passes it to `_read()`/ - // `ReadFile()` unchanged, so the chunk size reaches the disk. Buffered, not `FILE_FLAG_NO_BUFFERING`: - // the cache should still hold what it can. - FILE* f = std::fopen(path.c_str(), "rb"); - if (f == nullptr) { - std::lock_guard g(err_mu); - err = "cannot open " + path; - return; - } - // A `FILE*` has no destructor that closes it, and this function has early returns below (open, seek and - // short-read failures), so the guard is what keeps the closing correct on every path. - struct Closer { - FILE* f; - ~Closer() { if (f != nullptr) std::fclose(f); } - } closer{f}; - uint64_t read_ns = 0, copy_ns = 0; - for (;;) { - const uint64_t L = next_layer.fetch_add(1); - if (L >= layers) break; - const uint64_t off = layer_off[(size_t) L]; - uint64_t remaining = layer_bytes[(size_t) L]; - uint64_t pos = 0; - uint64_t h = 1469598103934665603ull; - // 64-bit seek: the pack is 42.9 GB, so the 32-bit `fseek` would wrap past 4 GiB - if (STRATA_FSEEK64(f, off) != 0) { - std::lock_guard g(err_mu); - err = "seek to " + std::to_string(off) + " B failed in layer " + std::to_string(L); - return; - } - while (remaining > 0) { - const uint64_t n = remaining < chunk ? remaining : chunk; - const auto t_read = std::chrono::steady_clock::now(); - const size_t got = std::fread(buf.data(), 1, (size_t) n, f); - read_ns += (uint64_t) std::chrono::duration_cast( - std::chrono::steady_clock::now() - t_read).count(); - // A short read is EOF or an I/O error, never a silent zero fill: say WHERE and HOW SHORT, and - // keep going no further - the caller turns this into a refused load, not a wrong answer. - if (got != (size_t) n) { - std::lock_guard g(err_mu); - err = "short read in layer " + std::to_string(L) + ": got " + std::to_string(got) + " of " - + std::to_string(n) + " B at offset " + std::to_string(off + pos) - + (std::ferror(f) != 0 ? " (ferror set)" : ""); - return; - } - const auto t_copy = std::chrono::steady_clock::now(); - std::memcpy(dst + off + pos, buf.data(), (size_t) n); - h = fnv1a64(buf.data(), n, h); - copy_ns += (uint64_t) std::chrono::duration_cast( - std::chrono::steady_clock::now() - t_copy).count(); - pos += n; - remaining -= n; - } - layer_hash[(size_t) L] = h; - } - read_ns_sum.fetch_add(read_ns); - copy_ns_sum.fetch_add(copy_ns); - }; - - std::vector pool; - for (int i = 1; i < threads; ++i) pool.emplace_back(worker); - worker(); - for (auto& t : pool) t.join(); - - if (!err.empty()) { - std::fprintf(stderr, "load_experts: %s\n", err.c_str()); - st.seconds = -1.0; - st.ok = false; - st.error = err; - return st; - } - st.read_seconds = (double) read_ns_sum.load() / 1e9; - st.copy_seconds = (double) copy_ns_sum.load() / 1e9; - st.layer_checksums = std::move(layer_hash); - st.seconds = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - return st; -} - -StreamStats stream_bandwidth(const uint8_t* src, uint64_t bytes, uint64_t chunk, int iters) { - StreamStats st; - st.bytes = bytes * (uint64_t) iters; - st.chunk = chunk; - uint8_t* dst = nullptr; - cudaStream_t s{}; - if (cudaMalloc(&dst, (size_t) chunk) != cudaSuccess) { - std::fprintf(stderr, "stream_bandwidth: cudaMalloc failed for %llu B\n", (unsigned long long) chunk); - st.seconds = -1.0; - return st; - } - cudaStreamCreate(&s); - - // one untimed pass so the first transfer's page-fault and setup cost is not in the measurement - for (uint64_t off = 0; off + chunk <= bytes; off += chunk) { - cudaMemcpyAsync(dst, src + off, (size_t) chunk, cudaMemcpyHostToDevice, s); - } - cudaStreamSynchronize(s); - - const auto t0 = std::chrono::steady_clock::now(); - for (int it = 0; it < iters; ++it) { - for (uint64_t off = 0; off + chunk <= bytes; off += chunk) { - cudaMemcpyAsync(dst, src + off, (size_t) chunk, cudaMemcpyHostToDevice, s); - } - } - cudaStreamSynchronize(s); - st.seconds = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - - cudaStreamDestroy(s); - cudaFree(dst); - return st; -} - -} // namespace strata::core diff --git a/src/core/pinned_shared_test.cpp b/src/core/pinned_shared_test.cpp deleted file mode 100644 index c663f1a..0000000 --- a/src/core/pinned_shared_test.cpp +++ /dev/null @@ -1,61 +0,0 @@ -// Linux selftest for the optional MAP_SHARED backing of PinnedArena. -#include "strata/core/pinned.hpp" - -#include -#include -#include -#include - -#include - -int main() { - char path[] = "/tmp/strata-shared-arena-XXXXXX"; - const int fd = mkstemp(path); - if (fd < 0) { - std::perror("mkstemp"); - return 2; - } - close(fd); - - int fail = 0; - const uint64_t bytes = 64u << 10; - const uint64_t pack_hash = 0x0123456789abcdefull; - const std::vector no_bounds; - { - strata::core::PinnedArena first(bytes, no_bounds, 0, path, pack_hash); - if (!first.valid()) { - std::fprintf(stderr, "first shared arena failed: %s\n", first.note.c_str()); - fail = 1; - } else { - first.data()[123] = 0x5a; - - strata::core::PinnedArena second(bytes, no_bounds, 0, path, pack_hash); - if (!second.valid()) { - std::fprintf(stderr, "second shared arena failed: %s\n", second.note.c_str()); - fail = 1; - } else if (second.data()[123] != 0x5a) { - std::fprintf(stderr, "shared mapping did not expose the same bytes\n"); - fail = 1; - } - - strata::core::PinnedArena wrong_pack(bytes, no_bounds, 0, path, pack_hash + 1); - if (wrong_pack.valid() || wrong_pack.note.find("pack hash") == std::string::npos) { - std::fprintf(stderr, "pack mismatch was not refused: %s\n", wrong_pack.note.c_str()); - fail = 1; - } - - strata::core::PinnedArena wrong_size(bytes * 2, no_bounds, 0, path, pack_hash); - if (wrong_size.valid() || wrong_size.note.find("expected") == std::string::npos) { - std::fprintf(stderr, "size mismatch was not refused: %s\n", wrong_size.note.c_str()); - fail = 1; - } - } - } - - if (unlink(path) != 0) { - std::perror("unlink"); - fail = 1; - } - std::printf("pinned_shared_test: %s\n", fail ? "FAILED" : "OK"); - return fail; -} diff --git a/src/core/remote_expert_opt.cu b/src/core/remote_expert_opt.cu deleted file mode 100644 index 229781c..0000000 --- a/src/core/remote_expert_opt.cu +++ /dev/null @@ -1,194 +0,0 @@ -#include "strata/core/remote_expert_opt.hpp" -#include "strata/core/remote_experts.hpp" -#include "strata/core/on_device.hpp" -#include "strata/kernels/cpu/expert_layout.hpp" -#include "strata/kernels/elementwise.hpp" -#include "strata/kernels/verify_kernels.hpp" - -#include -#include - -namespace strata::core { -namespace { -constexpr int64_t H = strata::kernels::cpu::H; -constexpr int K = 10, MAXT = strata::kernels::cpu::MAXT, CAP = MAXT * K; -struct ReduceMeta { int32_t row[CAP]; float weight[CAP]; }; - -bool check(cudaError_t status, std::string& err) { - if (status == cudaSuccess) return true; - err = std::string("remote expert decode optimization: ") + cudaGetErrorString(status); - return false; -} - -__global__ void reduce_experts(const float* parts, const ReduceMeta* meta, float* sum) { - const int t = blockIdx.y, c = blockIdx.x * blockDim.x + threadIdx.x; - if (c >= H) return; - float v = 0.0f; - for (int j = 0; j < K; ++j) { - const int i = t * K + j, r = meta->row[i]; - if (r >= 0) v += parts[(int64_t) r * H + c] * meta->weight[i]; - } - sum[(int64_t) t * H + c] = v; -} - -// Like the upstream mapped-row copy, also skip rows returned in the remote sum. -__global__ void copy_cpu_rows(float4* dst, const volatile float4* src, const int32_t* mask, - const int32_t* hit_rows, const int32_t* count) { - const int row = blockIdx.x; - __shared__ int skip; - if (threadIdx.x == 0) { - int s = mask[row]; - for (int i = 0; i < *count; ++i) s |= hit_rows[i] == row; - skip = s; - } - __syncthreads(); - const int64_t start = (int64_t) row * (H / 4); - for (int i = threadIdx.x; i < H / 4; i += blockDim.x) - dst[start + i] = skip ? make_float4(0, 0, 0, 0) : const_cast(src)[start + i]; -} -} // namespace - -void RemoteExpertOpt::attach(RemoteExperts& remote) { - remote.remote_opt_ = this; - peers_.push_back({&remote}); -} - -bool RemoteExpertOpt::init(std::string& err) { - void* mapped = nullptr; - if (!check(cudaHostAlloc((void**) &h_sum_, MAXT * (H + K) * sizeof(float), - cudaHostAllocPortable | cudaHostAllocMapped), err) || - !check(cudaHostGetDevicePointer(&mapped, h_sum_, 0), err)) return false; - m_sum_ = (float*) mapped; - h_mask_ = reinterpret_cast(h_sum_ + MAXT * H); - m_mask_ = reinterpret_cast(m_sum_ + MAXT * H); - for (auto& p : peers_) { - const OnDevice on(p.remote->device_); - if (!check(cudaMalloc((void**) &p.sum, MAXT * H * sizeof(float)), err)) return false; - } - return true; -} - -RemoteExpertOpt::~RemoteExpertOpt() { - for (auto& p : peers_) { - const OnDevice on(p.remote->device_); - if (p.remote->stream_) cudaStreamSynchronize(p.remote->stream_); - if (p.sum) cudaFree(p.sum); - p.remote->remote_opt_ = nullptr; - } - if (h_sum_) cudaFreeHost(h_sum_); -} - -size_t RemoteExpertOpt::metadata_bytes() { return sizeof(ReduceMeta); } - -void RemoteExpertOpt::begin(const float* weights, int token_begin, int tokens) { - weights_ = weights; - token_begin_ = token_begin; - tokens_ = tokens; - std::memset(h_sum_ + token_begin * H, 0, tokens * H * sizeof(float)); - std::memset(h_mask_ + token_begin * K, 0, tokens * K * sizeof(int32_t)); -} - -void RemoteExpertOpt::prepare(const RemoteExperts& remote, void* metadata) const { - auto* m = (ReduceMeta*) metadata; - std::fill(m->row, m->row + tokens_ * K, -1); - for (size_t i = 0; i < remote.original_row_.size(); ++i) - m->row[remote.original_row_[i]] = (int32_t) i; - std::memcpy(m->weight, weights_, tokens_ * K * sizeof(float)); -} - -bool RemoteExpertOpt::reduce(RemoteExperts& remote, const void* metadata, std::string& err) { - const auto& p = *std::find_if(peers_.begin(), peers_.end(), [&](const Peer& p) { return p.remote == &remote; }); - reduce_experts<<>>( - remote.d_out_, (const ReduceMeta*) metadata, p.sum); - return check(cudaMemcpyAsync(remote.h_out_, p.sum, tokens_ * H * sizeof(float), - cudaMemcpyDeviceToHost, remote.stream_), err); -} - -void RemoteExpertOpt::accumulate(const RemoteExperts& remote) { - for (int64_t i = 0; i < tokens_ * H; ++i) h_sum_[token_begin_ * H + i] += remote.h_out_[i]; - for (int i = 0; i < tokens_ * K; ++i) - h_mask_[token_begin_ * K + i] |= remote.owned_[(size_t) i] != 0; -} - -void RemoteExpertOpt::copy_rows(float* dst, const float* src, int token_begin, int tokens, - const int32_t* hit_rows, const int32_t* count, void* stream) const { - copy_cpu_rows<<>>( - (float4*) dst, (const volatile float4*) src, m_mask_ + token_begin * K, hit_rows, count); -} - -void RemoteExpertOpt::combine(float* dst, float* scratch, int token_begin, int tokens, - const uint32_t* skip, uint32_t ring, void* stream) const { - const float* sum = m_sum_ + token_begin * H; - if (skip) { - // An all-primary device-planned group bypasses the host: ignore its stale sum. - strata::kernels::copy_or_zero_from_mapped(scratch, sum, tokens * H, skip, ring, stream); - sum = scratch; - } - strata::kernels::add_inplace(dst, sum, tokens * H, stream); -} - -bool RemoteExpertOpt::owns(int64_t layer, int32_t expert) const { - for (const auto& p : peers_) - if (p.remote->cache_.slot_of(layer, expert) >= 0) return true; - return false; -} - -bool RemoteExpertOpt::adapt(const std::vector& usage, const std::vector& primary, - const std::vector>& pending, int max_swaps, - ExpertSource& source) { - if (max_swaps <= 0) return true; - const auto& lay = strata::kernels::cpu::expert_layout(); - std::vector resident(primary.size(), 0); - for (size_t i = 0; i < primary.size(); ++i) resident[i] = primary[i] >= 0; - for (const auto& [i, slot] : pending) resident[(size_t) i] = 1; - for (const auto& p : peers_) { - const auto& r = *p.remote; - for (int32_t l = 0; l < (int32_t) r.layers_present_.size(); ++l) - for (int32_t e = 0; e < r.n_expert_; ++e) - if (r.cache_.slot_of(l, e) >= 0) resident[(size_t) l * r.n_expert_ + e] = 1; - } - struct Swap { float gain; int32_t layer, in, out; }; - std::string err; - for (auto& p : peers_) { - auto& r = *p.remote; - std::vector swaps; - std::vector> candidates, victims; - for (int32_t l = 0; l < (int32_t) r.layers_present_.size(); ++l) { - candidates.clear(); victims.clear(); - const size_t base = (size_t) l * r.n_expert_; - float primary_cold = 1.0e30f; - for (int32_t e = 0; e < r.n_expert_; ++e) { - const float u = usage[base + e]; - if (primary[base + e] >= 0) primary_cold = std::min(primary_cold, u); - if (r.cache_.slot_of(l, e) >= 0) victims.emplace_back(u, e); - else if (!resident[base + e] && u >= 2.0f) candidates.emplace_back(u, e); - } - const size_t n = std::min(candidates.size(), victims.size()); - if (!n) continue; - std::sort(candidates.begin(), candidates.end(), [](auto& a, auto& b) { return a.first > b.first; }); - std::partial_sort(victims.begin(), victims.begin() + n, victims.end(), - [](auto& a, auto& b) { return a.first < b.first; }); - for (size_t i = 0; i < n; ++i) { - if (victims[i].first > primary_cold) break; - if (candidates[i].first < victims[i].first + 1.5f) break; - swaps.push_back({candidates[i].first - victims[i].first, l, candidates[i].second, victims[i].second}); - } - } - std::sort(swaps.begin(), swaps.end(), [](auto& a, auto& b) { return a.gain > b.gain; }); - if ((int) swaps.size() > max_swaps) swaps.resize((size_t) max_swaps); - if (swaps.empty()) continue; - const OnDevice on(r.device_); - for (const auto& s : swaps) - if (!r.cache_.fill_slot(r.cache_.slot_of(s.layer, s.out), source.blob(s.layer, s.in), - r.stream_, err, (int64_t) lay.blob_bytes(s.layer))) return false; - if (!check(cudaStreamSynchronize(r.stream_), err)) return false; - for (const auto& s : swaps) { - r.cache_.replace(s.layer, s.out, s.in); - const size_t base = (size_t) s.layer * r.n_expert_; - resident[base + s.out] = 0; - resident[base + s.in] = 1; - } - } - return true; -} -} // namespace strata::core diff --git a/src/core/remote_experts.cpp b/src/core/remote_experts.cpp deleted file mode 100644 index 1b6969e..0000000 --- a/src/core/remote_experts.cpp +++ /dev/null @@ -1,341 +0,0 @@ -#include "strata/core/remote_experts.hpp" -#include "strata/core/remote_expert_opt.hpp" - -#include "strata/kernels/cpu/expert_layout.hpp" -#include "strata/kernels/iq_kernels.hpp" -#include "strata/kernels/quantize_act.hpp" -#include "strata/kernels/s2_expert_grouped.hpp" - -#include -#include -#include -#include - -namespace strata::core { -namespace { -constexpr int64_t H = strata::kernels::cpu::H; -constexpr int64_t FF = strata::kernels::cpu::FF; -constexpr int64_t CAP = strata::kernels::cpu::MAXT * 10; - -// Small enough to copy as one pinned buffer per layer. The kernels read the -// individual arrays through pointers into the same device allocation. -struct RemoteMeta { - unsigned long long ptr[CAP]; - int32_t start[CAP + 1]; - int32_t dst[CAP]; - int32_t tok[CAP]; - int32_t count; -}; - -struct DeviceScope { - int previous = -1; - bool ok = false; - cudaError_t status = cudaSuccess; - const char* failed_step = nullptr; - explicit DeviceScope(int device) { - status = cudaGetDevice(&previous); - if (status != cudaSuccess) { - previous = -1; - failed_step = "cudaGetDevice"; - return; - } - status = cudaSetDevice(device); - if (status != cudaSuccess) { - failed_step = "cudaSetDevice"; - return; - } - ok = true; - } - ~DeviceScope() { if (previous >= 0) cudaSetDevice(previous); } - std::string error(int device) const { - return std::string("CUDA") + std::to_string(device) + " experts: " + - (failed_step ? failed_step : "device switch") + - "(" + std::to_string(device) + ") failed: " + cudaGetErrorString(status) + - " (CUDA error " + std::to_string((int) status) + ")"; - } -}; - -bool check(cudaError_t result, const char* what, std::string& err, int device) { - if (result == cudaSuccess) return true; - err = "CUDA" + std::to_string(device) + " experts: " + what + ": " + cudaGetErrorString(result); - return false; -} -} // namespace - -RemoteExperts::~RemoteExperts() { close(); } - -bool RemoteExperts::preflight(int device, double& free_gib, std::string& err) { - int count = 0; - if (!check(cudaGetDeviceCount(&count), "cudaGetDeviceCount", err, device)) return false; - if (device < 1 || device >= count) { - err = "CUDA" + std::to_string(device) + " experts: CUDA device is not visible"; - return false; - } - // The layer waits for this GPU on the CPU pool's critical path: spin instead of sleeping, whose wake-up - // costs more than a small expert batch takes (measured: ~0.3 ms per round trip on Windows). Only possible - // before the device's context exists, so first thing; STRATA_REMOTE_SPIN=0 keeps the driver's default. -#if !defined(STRATA_USE_HIP) - const char* spin = std::getenv("STRATA_REMOTE_SPIN"); - if (!(spin && spin[0] == '0')) cudaInitDevice(device, cudaDeviceScheduleSpin | cudaDeviceMapHost, 0); - cudaGetLastError(); -#endif - // HIP has no cudaInitDevice equivalent; retain its default scheduling policy. - DeviceScope scope(device); - if (!scope.ok) { err = scope.error(device); return false; } - size_t free_bytes = 0, total_bytes = 0; - if (!check(cudaMemGetInfo(&free_bytes, &total_bytes), "preflight free memory", err, device)) return false; - free_gib = (double) free_bytes / 1073741824.0; - return true; -} - -void RemoteExperts::close() { - if (device_ < 0) return; - DeviceScope scope(device_); - if (scope.ok) { - if (stream_) cudaStreamSynchronize(stream_); - cache_.close(); - if (d_x_) cudaFree(d_x_); - if (d_out_) cudaFree(d_out_); - if (d_q8_) cudaFree(d_q8_); - if (d_scales_) cudaFree(d_scales_); - if (d_scratch_) cudaFree(d_scratch_); - if (d_meta_) cudaFree(d_meta_); - if (h_x_) cudaFreeHost(h_x_); - if (h_out_) cudaFreeHost(h_out_); - if (h_meta_) cudaFreeHost(h_meta_); - if (stream_) cudaStreamDestroy(stream_); - } - device_ = -1; - stream_ = nullptr; - h_x_ = h_out_ = d_x_ = d_out_ = nullptr; - h_meta_ = d_meta_ = nullptr; - d_q8_ = nullptr; - d_scales_ = nullptr; - d_scratch_ = nullptr; - d_start_ = d_dst_ = d_tok_ = d_count_ = nullptr; - d_ptr_ = nullptr; - original_row_.clear(); - layers_present_.clear(); -} - -bool RemoteExperts::open(int device, int slots, int64_t layers, int64_t experts, - const std::vector>& ranked, - const ExpertCache& primary, ExpertSource& source, - std::vector& claimed, std::string& err, bool auto_size) { - close(); - int count = 0; - if (!check(cudaGetDeviceCount(&count), "cudaGetDeviceCount", err, device)) return false; - if (device < 1 || device >= count || slots <= 0 || ranked.empty() || - layers <= 0 || experts <= 0 || claimed.size() != (size_t) layers * (size_t) experts) { - err = "CUDA" + std::to_string(device) + " experts: need the device, ranked experts and positive slot count"; - return false; - } - DeviceScope scope(device); - if (!scope.ok) { err = scope.error(device); return false; } - device_ = device; - n_expert_ = experts; - const auto& lay = strata::kernels::cpu::expert_layout(); - size_t free_bytes = 0, total_bytes = 0; - if (!check(cudaMemGetInfo(&free_bytes, &total_bytes), "free memory", err, device)) { close(); return false; } - uint64_t needed = 0; - std::vector> selected; - selected.reserve((size_t) std::min(slots, layers * experts)); - std::vector picked(claimed.size(), 0); - for (const auto& pair : ranked) { - if (pair.first < 0 || pair.first >= layers || pair.second < 0 || pair.second >= experts) continue; - const size_t index = (size_t) pair.first * (size_t) experts + (size_t) pair.second; - if (primary.slot_of(pair.first, pair.second) < 0 && !claimed[index] && !picked[index]) { - const uint64_t bytes = lay.native ? (lay.blob_bytes(pair.first) + 255) / 256 * 256 : lay.max_blob; - if (auto_size && needed + bytes + (512ull << 20) > free_bytes) break; - selected.push_back(pair); - needed += bytes; - picked[index] = 1; - if ((int) selected.size() >= slots) break; - } - } - if (selected.empty()) { - err = "CUDA" + std::to_string(device) + (auto_size ? " experts: no unclaimed expert fits with 512 MiB free" - : " experts: no unclaimed experts remain"); - close(); return false; - } - std::vector sizes; - if (lay.native) { - sizes.reserve(selected.size()); - for (const auto& pair : selected) sizes.push_back((int64_t) lay.blob_bytes(pair.first)); - } - // Leave room for the CUDA context, staging and later driver allocations, especially under WDDM. - if (needed + (512ull << 20) > free_bytes) { - err = "CUDA" + std::to_string(device) + " experts: slots leave less than 512 MiB free; reduce --expert-cache-device" + std::to_string(device); - close(); return false; - } - const bool cache_ok = lay.native ? cache_.open_sized(sizes, layers, experts, err) - : cache_.open((int64_t) selected.size(), layers, experts, - (int64_t) lay.max_blob, err); - if (!cache_ok) { err = "CUDA" + std::to_string(device) + " experts: " + err; close(); return false; } - for (const auto& pair : selected) { - const int32_t slot = cache_.admit(pair.first, pair.second); - const uint8_t* blob = source.blob(pair.first, pair.second); - if (slot < 0 || !blob || !cache_.fill_slot_blocking(slot, blob, err, (int64_t) lay.blob_bytes(pair.first))) { - err = "CUDA" + std::to_string(device) + " experts: " + - (err.empty() ? "cache fill failed" : err); - close(); return false; - } - } - const auto& first = selected.front(); - if (!cache_.verify_slot(cache_.slot_of(first.first, first.second), source.blob(first.first, first.second), - err, (int64_t) lay.blob_bytes(first.first))) { - err = "CUDA" + std::to_string(device) + " experts: " + err; - close(); return false; - } - - const size_t scratch = std::max( - (size_t) strata::kernels::moe_hit_grouped_scratch_bytes(CAP, H, FF), - strata::kernels::native_expert_scratch_bytes(CAP, FF)); - const size_t meta_bytes = sizeof(RemoteMeta) + (remote_opt_ ? remote_opt_->metadata_bytes() : 0); - const bool allocated = - check(cudaStreamCreateWithFlags(&stream_, cudaStreamNonBlocking), "stream", err, device) && - check(cudaHostAlloc((void**) &h_x_, (size_t) CAP * H * sizeof(float), cudaHostAllocPortable | cudaHostAllocMapped), "input staging", err, device) && - check(cudaHostAlloc((void**) &h_out_, (size_t) CAP * H * sizeof(float), cudaHostAllocPortable | cudaHostAllocMapped), "result staging", err, device) && - check(cudaHostAlloc(&h_meta_, meta_bytes, cudaHostAllocPortable), "metadata staging", err, device) && - check(cudaMalloc((void**) &d_x_, (size_t) CAP * H * sizeof(float)), "input", err, device) && - check(cudaMalloc((void**) &d_out_, (size_t) CAP * H * sizeof(float)), "result", err, device) && - check(cudaMalloc((void**) &d_q8_, (size_t) CAP * (H / 32) * 36), "activation", err, device) && - check(cudaMalloc((void**) &d_scales_, (size_t) CAP * (H / 32) * sizeof(float)), "activation scales", err, device) && - check(cudaMalloc(&d_scratch_, scratch), "scratch", err, device) && - check(cudaMalloc(&d_meta_, meta_bytes), "group metadata", err, device); - if (!allocated) { close(); return false; } - // Zero-copy: the helper reads its input from, and writes its compact rows into, the pinned host buffers - // directly - two copies fewer per layer, each of which is a PCIe round trip. STRATA_REMOTE_ZEROCOPY=0 copies. - const char* zc = std::getenv("STRATA_REMOTE_ZEROCOPY"); - zero_copy_ = !(zc && zc[0] == '0') && - cudaHostGetDevicePointer((void**) &z_x_, h_x_, 0) == cudaSuccess && - cudaHostGetDevicePointer((void**) &z_out_, h_out_, 0) == cudaSuccess; - cudaGetLastError(); - auto* meta = (RemoteMeta*) d_meta_; - d_ptr_ = meta->ptr; - d_start_ = meta->start; - d_dst_ = meta->dst; - d_tok_ = meta->tok; - d_count_ = &meta->count; - owned_.resize(CAP); - layers_present_.assign((size_t) layers, 0); - group_of_.resize(CAP); - group_id_.reserve(CAP); - ptr_.reserve(CAP); - start_.reserve(CAP + 1); - dst_.reserve(CAP); - tok_.reserve(CAP); - original_row_.reserve(CAP); - computed_ = 0; - launched_layers_ = 0; - returned_bytes_ = full_row_bytes_ = 0; - for (const auto& pair : selected) { - layers_present_[(size_t) pair.first] = 1; - claimed[(size_t) pair.first * (size_t) experts + (size_t) pair.second] = 1; - } - return true; -} - -bool RemoteExperts::begin(int64_t layer, const float* x, const int32_t* ids, int64_t n_tok, - int64_t k, const int32_t* kind, const int32_t* primary_res, - std::string& err) { - // cumulative host time in here (staging and launches), reported per request by the driver - struct Timer { double& acc; std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now(); - ~Timer() { acc += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); } } timer{ms_begin_}; - const int64_t n = n_tok * k; - if (n <= 0 || n > CAP || n_tok > strata::kernels::cpu::MAXT || k != 10 || layer < 0 || - (size_t) layer >= layers_present_.size() || device_ < 0) { - err = "CUDA" + std::to_string(device_) + " experts: invalid layer, routing width or window size"; - return false; - } - std::fill(owned_.begin(), owned_.begin() + n, 0); - group_id_.clear(); ptr_.clear(); start_.clear(); dst_.clear(); tok_.clear(); original_row_.clear(); - if (!layers_present_[(size_t) layer]) return true; - std::fill(group_of_.begin(), group_of_.begin() + n, -1); - for (int64_t i = 0; i < n; ++i) { - const int32_t e = ids[i]; - if ((kind && kind[i] != -1) || e < 0 || e >= n_expert_ || - (primary_res && primary_res[(size_t) layer * (size_t) n_expert_ + (size_t) e] >= 0)) continue; - const int32_t slot = cache_.slot_of(layer, e); - if (slot < 0) continue; - owned_[(size_t) i] = 1; - int32_t group = -1; - for (size_t g = 0; g < group_id_.size(); ++g) - if (group_id_[g] == e) { group = (int32_t) g; break; } - if (group < 0) { - group = (int32_t) group_id_.size(); - group_id_.push_back(e); - ptr_.push_back((unsigned long long) cache_.device_slot(slot)); - } - group_of_[(size_t) i] = group; - ++computed_; - } - if (group_id_.empty()) return true; - for (size_t g = 0; g < group_id_.size(); ++g) { - start_.push_back((int32_t) dst_.size()); - for (int64_t i = 0; i < n; ++i) if (group_of_[(size_t) i] == (int32_t) g) { - // The grouped kernels read the activation from `tok`, so their - // output row can instead be packed densely for the USB4 return. - original_row_.push_back((int32_t) i); - dst_.push_back((int32_t) dst_.size()); - tok_.push_back((int32_t) (i / k)); - } - } - start_.push_back((int32_t) dst_.size()); - // Private pinned buffers survive until this GPU has consumed them. The CPU - // pool can write other output rows without a cross-device race. - std::memcpy(h_x_, x, (size_t) n_tok * H * sizeof(float)); - auto* meta = (RemoteMeta*) h_meta_; - std::memcpy(meta->ptr, ptr_.data(), ptr_.size() * sizeof(ptr_[0])); - std::memcpy(meta->start, start_.data(), start_.size() * sizeof(start_[0])); - std::memcpy(meta->dst, dst_.data(), dst_.size() * sizeof(dst_[0])); - std::memcpy(meta->tok, tok_.data(), tok_.size() * sizeof(tok_[0])); - meta->count = (int32_t) group_id_.size(); - const bool reduce = remote_opt_ && remote_opt_->active(); - if (reduce) remote_opt_->prepare(*this, meta + 1); - DeviceScope scope(device_); - if (!scope.ok) { err = scope.error(device_); return false; } - groups_ = (int32_t) group_id_.size(); - const cudaStream_t s = stream_; - const bool staged = - (zero_copy_ || check(cudaMemcpyAsync(d_x_, h_x_, (size_t) n_tok * H * sizeof(float), cudaMemcpyHostToDevice, s), "copy input", err, device_)) && - check(cudaMemcpyAsync(d_meta_, h_meta_, sizeof(RemoteMeta) + (reduce ? remote_opt_->metadata_bytes() : 0), - cudaMemcpyHostToDevice, s), "copy group metadata", err, device_); - if (!staged) return false; - const auto& lay = strata::kernels::cpu::expert_layout(); - if (lay.native) { - strata::kernels::quantize_q8_1_rows(zero_copy_ ? z_x_ : d_x_, n_tok, H, d_q8_, s); - const auto& fmt = lay.fmt[(size_t) layer]; - auto L = strata::kernels::native_expert_layout(fmt.gu_type, fmt.d_type, fmt.n_embd, fmt.n_ff); - strata::kernels::native_expert_grouped(L, d_ptr_, d_start_, d_count_, d_dst_, d_tok_, - groups_, (int64_t) dst_.size(), d_q8_, d_scratch_, zero_copy_ && !reduce ? z_out_ : d_out_, s); - } else { - strata::kernels::quantize_q8_0_scaled(zero_copy_ ? z_x_ : d_x_, d_q8_, d_scales_, n_tok * H, s); - strata::kernels::moe_grouped_s2(d_ptr_, d_start_, d_count_, d_dst_, d_tok_, - groups_, (int64_t) dst_.size(), d_q8_, d_scales_, d_scratch_, zero_copy_ && !reduce ? z_out_ : d_out_, s); - } - const uint64_t compact_bytes = (uint64_t) (reduce ? n_tok : dst_.size()) * H * sizeof(float); - if (reduce) { - if (!remote_opt_->reduce(*this, (RemoteMeta*) d_meta_ + 1, err)) return false; - } else if (!zero_copy_ && !check(cudaMemcpyAsync(h_out_, d_out_, (size_t) compact_bytes, cudaMemcpyDeviceToHost, s), - "copy results", err, device_)) return false; - ++launched_layers_; - returned_bytes_ += compact_bytes; - full_row_bytes_ += (uint64_t) n * H * sizeof(float); - return true; -} - -bool RemoteExperts::finish(float* out, std::string& err) { - if (group_id_.empty()) return true; - DeviceScope scope(device_); - if (!scope.ok) { err = scope.error(device_); return false; } - const auto w0 = std::chrono::steady_clock::now(); - if (!check(cudaStreamSynchronize(stream_), "finish", err, device_)) return false; - ms_wait_ += std::chrono::duration(std::chrono::steady_clock::now() - w0).count(); - if (remote_opt_ && remote_opt_->active()) { remote_opt_->accumulate(*this); return true; } - for (size_t i = 0; i < original_row_.size(); ++i) - std::memcpy(out + (size_t) original_row_[i] * H, h_out_ + i * H, (size_t) H * sizeof(float)); - return true; -} - -} // namespace strata::core diff --git a/src/core/session.cpp b/src/core/session.cpp deleted file mode 100644 index eba30f9..0000000 --- a/src/core/session.cpp +++ /dev/null @@ -1,967 +0,0 @@ -// 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" - -#include "strata/kernels/qsa.hpp" -#include "strata/kernels/elementwise.hpp" -#include "strata/kernels/quantize_act.hpp" -#include "strata/kernels/s2_expert_grouped.hpp" -#include "strata/kernels/cpu/pool.hpp" -#include "strata/kernels/ngram.hpp" - -#include - -#include -#include -#include -#include -#include -#include - -// `_mm_pause` for the doorbell spin. Guarded because it is x86-only; a target without it still builds, the -// spin is just less polite to the pipeline. -#if defined(_MSC_VER) || defined(__x86_64__) || defined(__i386__) -#include -#define STRATA_SPIN_PAUSE() _mm_pause() -#else -#define STRATA_SPIN_PAUSE() ((void) 0) -#endif - -namespace strata::core { -namespace { - -constexpr uint64_t SESSION_STATE_ALIGN = 256; - -uint64_t align_up(uint64_t n, uint64_t a) { return (n + a - 1) / a * a; } - -/// The floats one GDN layer's recurrent + conv state needs. `gdn_buffers_bytes` carves them for ONE layer and -/// `GdnBuffers::state`/`conv_state` point INTO that carve, so a session with 36 GDN layers has to give each one -/// its own - they cannot share, because the recurrence is the whole point. -uint64_t gdn_state_floats(const ModelGeometry& g) { - return (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); -} - -} // namespace - -/// `NG_HIST` rows of `hc_dim` floats: the PLE conv's history, which is the ONLY PLE state that lives in the -/// session arena. The table and the weights are model-level and the caller owns them. -static uint64_t ple_hist_bytes(const ModelGeometry& g) { - // a model without a PLE (Qwen3.6, `has_ple` false) carves none of it (Qwen3.6 port, step 2; inventory row 29) - return g.has_ple ? (uint64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM * sizeof(float) : 0; -} - -uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k, int64_t layer_lo, int64_t layer_hi) { - if (layer_hi < 0 || layer_hi > g.n_layers) layer_hi = g.n_layers; - if (layer_lo < 0) layer_lo = 0; - // QSA layers are `l % interval == interval-1`, so exactly `bound / interval` of them live below `bound` - const int64_t I = std::max(g.qsa_interval, 1); - const int64_t q_lo = layer_lo / I, q_hi = layer_hi / I; - const int64_t q_n = std::max(q_hi - q_lo, g.n_qsa_layers() > 0 ? 1 : 0); - const int64_t gdn_n = std::max((layer_hi - layer_lo) - std::max(q_hi - q_lo, 0), 0); - uint64_t n = 0; - n += gdn_buffers_bytes(g); - n += (uint64_t) gdn_n * gdn_state_floats(g) * 4; - // One QSA state carries the RoPE table; the others borrow it (P7: 64 MiB per layer at 262K). - if (g.n_qsa_layers() > 0) - n += qsa_state_bytes(g, max_cells, true) + (uint64_t) (q_n - 1) * qsa_state_bytes(g, max_cells, false); - n += qsa_buffers_bytes(g, max_cells); - n += moe_buffers_bytes(g, k); - n += block_buffers_bytes(g); - n += ple_hist_bytes(g); // the PLE's NG_HIST normalized history rows (0 without a PLE) - return align_up(n, SESSION_STATE_ALIGN) + 4096; -} - -uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void* base, SessionState& s, - int64_t layer_lo, int64_t layer_hi) { - if (layer_hi < 0 || layer_hi > g.n_layers) layer_hi = g.n_layers; - if (layer_lo < 0) layer_lo = 0; - uint8_t* p = (uint8_t*) base; - uint64_t used = 0; - auto take = [&](uint64_t bytes) { - uint8_t* r = p + used; - used = align_up(used + bytes, SESSION_STATE_ALIGN); - return r; - }; - - s.max_cells = max_cells; - s.k = k; - s.layer_lo = layer_lo; - s.layer_hi = layer_hi; - const int64_t I = std::max(g.qsa_interval, 1); - const int64_t q_n_range = layer_hi / I - layer_lo / I; - s.qsa_ord0 = layer_lo / I; - s.qsa_alloc = std::max(q_n_range, g.n_qsa_layers() > 0 ? 1 : 0); - s.gdn_ord0 = layer_lo - layer_lo / I; - s.gdn_alloc = std::max((layer_hi - layer_lo) - q_n_range, 0); - - gdn_buffers_init(g, take(gdn_buffers_bytes(g)), s.gdn); - s.gdn_state = (float*) take((uint64_t) s.gdn_alloc * gdn_state_floats(g) * 4); - - // the QSA states are separate allocations carved from one arena, because `QsaState` is a struct of - // pointers and `qsa_state_init` writes them - a contiguous array would need the arena to be laid out the - // same way, which is a coupling with nothing to gain. Only the range's ordinals are initialized; the - // rest stay value-initialized nulls. The FIRST ALLOCATED one (the session's primary, ordinal qsa_ord0) - // owns the RoPE table that the others - and the prefill staging identity, and the MTP drafter - borrow. - const uint64_t first = qsa_state_bytes(g, max_cells, true), rest = qsa_state_bytes(g, max_cells, false); - s.qsa_state_arena = take(g.n_qsa_layers() > 0 ? first + (uint64_t) (s.qsa_alloc - 1) * rest : 0); - s.qsa_states = new QsaState[(size_t) g.n_qsa_layers()](); - s.qsa_buf_arena = take(qsa_buffers_bytes(g, max_cells)); - - uint8_t* qp = (uint8_t*) s.qsa_state_arena; - // a layer whose pinned RAM could not be had (KV streaming's host copy) is half-built: going on would have the - // attention read null host pointers at the first request ("illegal memory access"), so the session fails here - for (int64_t j = 0; j < s.qsa_alloc; ++j) - if (qsa_state_init(g, max_cells, qp + (j == 0 ? 0 : first + (uint64_t) (j - 1) * rest), - s.qsa_states[s.qsa_ord0 + j], j == 0 ? nullptr : &s.qsa_states[s.qsa_ord0]) == 0) - return 0; - qsa_buffers_init(g, max_cells, s.qsa_buf_arena, s.qsa_bufs); - - s.moe_arena = take(moe_buffers_bytes(g, k)); - moe_buffers_init(g, k, s.moe_arena, s.moe); - s.block_arena = take(block_buffers_bytes(g)); - block_buffers_init(g, s.block_arena, s.block); - // THE PLE HISTORY: NG_HIST rows of hc_dim floats, row-fastest. Sequence state, carved here and zeroed by - // `session_zero`; it survives every token, which is the whole point of a conv history. - s.ple_hist = ple_hist_bytes(g) ? (float*) take(ple_hist_bytes(g)) : nullptr; - s.R = s.block.R; - return used; -} - -void session_release(SessionState& s) { - for (int64_t j = 0; s.qsa_states != nullptr && j < s.qsa_alloc; ++j) - if (s.qsa_states[j].owns_rope) { - strata::kernels::rope_table_release(s.qsa_states[j].cos_tab); - s.qsa_states[j].owns_rope = false; - } -} - -void session_zero(SessionState& s, const ModelGeometry& g, const float* R_init, void* stream) { - cudaStream_t cs = (cudaStream_t) stream; - // the residual: `hc` copies of the one vector a caller hands in. A real sequence's first token is the - // embedding broadcast to every stream, which is the reference's own initial condition. - if (R_init != nullptr) { - for (int64_t c = 0; c < g.hc; ++c) - cudaMemcpyAsync(s.block.R + (size_t) c * g.n_embd, R_init, (size_t) g.n_embd * 4, - cudaMemcpyDeviceToDevice, cs); - } else { - cudaMemsetAsync(s.block.R, 0, (size_t) g.hc * g.n_embd * 4, cs); - } - // every owned GDN layer's recurrence and conv history - cudaMemsetAsync(s.gdn_state, 0, (size_t) s.gdn_alloc * gdn_state_floats(g) * 4, cs); - // and every owned QSA layer's cache and indexer - for (int64_t j = 0; j < s.qsa_alloc; ++j) qsa_state_zero(s.qsa_states[s.qsa_ord0 + j], g, stream); - // **AND THE PLE'S CONV HISTORY AND TOKEN WINDOW.** A sequence that started with a warm history would - // convolve over rows belonging to a different sequence - the conv reads NG_HIST previous NORMALIZED rows, - // so a stale one is a real contribution and not a zero. The token window resets to `NG_HIST`-many nulls - // for the same reason: `ngram_rows` treats a missing predecessor as the EOS cut, which is what a sequence - // boundary IS. - if (s.ple_hist != nullptr) cudaMemsetAsync(s.ple_hist, 0, (size_t) ple_hist_bytes(g), cs); - s.ple_prev[0] = -1; - s.ple_prev[1] = -1; - s.ple_token = -1; -} - -/// Sets `s.gdn.state`/`conv_state` for `layer`, which is what makes one layer's GDN state its own. Shared by -/// the direct and captured paths so the two cannot disagree about which slice a layer owns. -void gdn_point_at(const ModelGeometry& g, int64_t layer, SessionState& s) { - if (is_qsa_layer(g, layer)) return; - int64_t gdn_index = 0; - for (int64_t l = 0; l < layer; ++l) if (!is_qsa_layer(g, l)) ++gdn_index; - s.gdn.state = s.gdn_state + (size_t) (gdn_index - s.gdn_ord0) * gdn_state_floats(g); - s.gdn.conv_state = s.gdn.state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; -} - -/// The per-token staging every QSA layer's captured H2D reads FROM. Must run before each replay: the graphs -/// captured the SOURCE POINTER, not the value, and that is exactly why the buffers are pinned and fixed. -void stage_token(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s) { - const strata::kernels::QsaShapes sh = qsa_shapes(g); // the one builder (qsa_shapes.hpp): dense width = n_kv - 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); - for (int64_t h = 0; h < g.n_head; ++h) q.host_pos[h] = (int32_t) (pos_base + pos); - } -} - -bool session_capture(const WeightTable& tables, const ModelGeometry& g, SessionState& s, const float* parts, - SessionGraphs& gr, std::string& err, bool split, int64_t layer_lo, int64_t layer_hi) { - if (gr.captured) return true; - if (layer_hi < 0 || layer_hi > g.n_layers) layer_hi = g.n_layers; - if (layer_lo < 0) layer_lo = 0; - gr.execs = new cudaGraphExec_t[(size_t) g.n_layers](); - gr.posts = new cudaGraphExec_t[(size_t) g.n_layers](); - for (int64_t i = 0; i < g.n_layers; ++i) gr.posts[i] = nullptr; - if (split) { - gr.preA = new cudaGraphExec_t[(size_t) g.n_layers](); - gr.preB = new cudaGraphExec_t[(size_t) g.n_layers](); - for (int64_t i = 0; i < g.n_layers; ++i) { gr.preA[i] = nullptr; gr.preB[i] = nullptr; } - for (int k = 0; k < 5; ++k) { - gr.preP[k] = new cudaGraphExec_t[(size_t) g.n_layers](); - for (int64_t i = 0; i < g.n_layers; ++i) gr.preP[k][i] = nullptr; - } - } - gr.split_captured = split; - gr.n = 0; - - int64_t qsa_index = s.qsa_ord0; - for (int64_t l = layer_lo; l < layer_hi; ++l) { - gdn_point_at(g, l, s); - const bool qsa = is_qsa_layer(g, l); - QsaState& qst = qsa ? s.qsa_states[qsa_index] : s.qsa_states[s.qsa_primary()]; - - // **TWO GRAPHS PER LAYER, SPLIT AT THE ROUTER.** `pre` ends with the doorbell rung; the host then runs - // the CPU pool on what it published; `post` combines those experts with THIS layer's weights. Capturing - // them together is what the old single graph could not do, and the reason it could not is that - // `moe_combine` needs the pool's answer and the pool needs the router's. - auto capture = [&](bool post, cudaGraphExec_t* out, const char* what, int half = 0, - int stage_prefix = 0) -> bool { - cudaStream_t cs = nullptr; - if (cudaStreamCreate(&cs) != cudaSuccess) { - err = std::string("session_capture: stream create failed"); - return false; - } - if (cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { - err = "session_capture: begin failed at layer " + std::to_string(l); - return false; - } - err.clear(); - // R0.9: `half` is 0 for every mode except the split capture, where it selects a prefix of the - // stages so the mixer and the FFN-front-plus-router can be timed separately. - const bool ok = post - ? block_layer_post(tables, g, l, s.k, s.moe, s.block, parts, (void*) cs, err) - : block_layer_pre(tables, g, l, 0, 0, s.gdn, qst, s.qsa_bufs, s.moe, s.k, - s.block, (void*) cs, err, s.db, s.ple.ready() ? &s.ple : nullptr, - half, stage_prefix); - if (!ok) { - err = "session_capture: " + std::string(what) + " layer " + std::to_string(l) + ": " + err; - return false; - } - cudaGraph_t graph = nullptr; - const cudaError_t ce = cudaStreamEndCapture(cs, &graph); - cudaStreamDestroy(cs); - if (ce != cudaSuccess) { - err = "session_capture: " + std::string(what) + " layer " + std::to_string(l) + ": " + - cudaGetErrorString(ce) + " (a synchronous call in the layer?)"; - return false; - } - if (cudaGraphInstantiate(out, graph, 0) != cudaSuccess) { - err = "session_capture: instantiate failed at layer " + std::to_string(l); - return false; - } - cudaGraphDestroy(graph); - return true; - }; - if (!capture(/*post=*/false, &gr.execs[l], "pre")) return false; - if (!capture(/*post=*/true, &gr.posts[l], "post")) return false; - if (split) { - if (!capture(/*post=*/false, &gr.preA[l], "preA", /*half=*/1)) return false; - if (!capture(/*post=*/false, &gr.preB[l], "preB", /*half=*/2)) return false; - // Prefixes 1..5, ALL through the new parameter - including the fifth, so that it and the fourth - // differ only in the one stage between them and not in how many nodes their graphs carry. - for (int k = 1; k <= 5; ++k) - if (!capture(/*post=*/false, &gr.preP[k - 1][l], "preP", /*half=*/0, /*stage_prefix=*/k)) - return false; - } - ++gr.n; - if (qsa) ++qsa_index; - } - gr.captured = true; - gr.parts_dev = const_cast(parts); // the address the graphs baked in; the loop copies here - return true; -} - -bool session_replay(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, SessionGraphs& gr, - void* stream, std::string& err) { - if (!gr.captured || gr.n != g.n_layers) { err = "session_replay: not captured"; return false; } - cudaStream_t cs = (cudaStream_t) stream; - stage_token(g, pos, pos_base, s); - for (int64_t l = 0; l < g.n_layers; ++l) { - const cudaError_t e = cudaGraphLaunch(gr.execs[l], cs); - if (e != cudaSuccess) { - err = "session_replay: layer " + std::to_string(l) + ": " + cudaGetErrorString(e); - return false; - } - } - return true; -} - -bool session_replay_full(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, - SessionGraphs& gr, void* stream, std::string& err) { - if (!gr.captured || gr.n != g.n_layers || gr.posts == nullptr) { - err = "session_replay_full: not captured with post graphs"; - return false; - } - cudaStream_t cs = (cudaStream_t) stream; - stage_token(g, pos, pos_base, s); - for (int64_t l = 0; l < g.n_layers; ++l) { - // `pre[l]` then `post[l]`, in the order `session_loop` uses. The two are ordered on one stream, and - // `post[l]` reads what `pre[l]` wrote, so they cannot be reordered or run concurrently. - cudaError_t e = cudaGraphLaunch(gr.execs[l], cs); - if (e != cudaSuccess) { - err = "session_replay_full: pre[" + std::to_string(l) + "]: " + cudaGetErrorString(e); - return false; - } - e = cudaGraphLaunch(gr.posts[l], cs); - if (e != cudaSuccess) { - err = "session_replay_full: post[" + std::to_string(l) + "]: " + cudaGetErrorString(e); - return false; - } - } - return true; -} - -bool session_replay_stages_per_layer(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, - SessionGraphs& gr, void* stream, std::vector& mixer_per_layer, - double& ms_ffn, double& ms_post, std::string& err) { - if (!gr.split_captured || gr.preA == nullptr || gr.preB == nullptr) { - err = "session_replay_stages: not captured with the split"; - return false; - } - cudaStream_t cs = (cudaStream_t) stream; - stage_token(g, pos, pos_base, s); - - // Four events PER LAYER rather than four reused ones: reusing them would need a synchronisation after - // every layer to read them before the next launch overwrote them, and a per-layer sync would report the - // serialised time rather than the graph's. - const int64_t n = g.n_layers; - std::vector ev((size_t) (n * 4)); - for (auto& e : ev) { - if (cudaEventCreate(&e) != cudaSuccess) { err = "session_replay_stages: event create"; return false; } - } - struct Free { - std::vector* v; - ~Free() { for (auto& e : *v) cudaEventDestroy(e); } - } frees{&ev}; - - for (int64_t l = 0; l < n; ++l) { - cudaEventRecord(ev[(size_t) (l * 4 + 0)], cs); - if (cudaGraphLaunch(gr.preA[l], cs) != cudaSuccess) { err = "stages: preA"; return false; } - cudaEventRecord(ev[(size_t) (l * 4 + 1)], cs); - if (cudaGraphLaunch(gr.preB[l], cs) != cudaSuccess) { err = "stages: preB"; return false; } - cudaEventRecord(ev[(size_t) (l * 4 + 2)], cs); - if (cudaGraphLaunch(gr.posts[l], cs) != cudaSuccess) { err = "stages: post"; return false; } - cudaEventRecord(ev[(size_t) (l * 4 + 3)], cs); - } - if (cudaStreamSynchronize(cs) != cudaSuccess) { err = "stages: final sync"; return false; } - - mixer_per_layer.assign((size_t) n, 0.0); - ms_ffn = 0; ms_post = 0; - for (int64_t l = 0; l < n; ++l) { - float a = 0, b = 0, c = 0; - cudaEventElapsedTime(&a, ev[(size_t) (l * 4 + 0)], ev[(size_t) (l * 4 + 1)]); - cudaEventElapsedTime(&b, ev[(size_t) (l * 4 + 1)], ev[(size_t) (l * 4 + 2)]); - cudaEventElapsedTime(&c, ev[(size_t) (l * 4 + 2)], ev[(size_t) (l * 4 + 3)]); - mixer_per_layer[(size_t) l] = (double) a; - ms_ffn += b; ms_post += c; - } - return true; -} - -bool session_replay_stages(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, - SessionGraphs& gr, void* stream, double& ms_mixer, double& ms_ffn, double& ms_post, - std::string& err) { - std::vector per; - if (!session_replay_stages_per_layer(g, pos, pos_base, s, gr, stream, per, ms_ffn, ms_post, err)) return false; - ms_mixer = 0; - for (double v : per) ms_mixer += v; - return true; -} - -bool session_replay_stage_sweep(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, - SessionGraphs& gr, void* stream, int k, double& ms, std::string& err) { - if (!gr.split_captured || gr.preP[0] == nullptr) { - err = "session_replay_stage_sweep: not captured with the split"; - return false; - } - if (k < 1 || k > 5) { err = "session_replay_stage_sweep: k must be 1..5"; return false; } - cudaStream_t cs = (cudaStream_t) stream; - stage_token(g, pos, pos_base, s); - - cudaEvent_t a, b; - if (cudaEventCreate(&a) != cudaSuccess || cudaEventCreate(&b) != cudaSuccess) { - err = "session_replay_stage_sweep: event create"; - return false; - } - cudaEventRecord(a, cs); - for (int64_t l = 0; l < g.n_layers; ++l) { - const cudaError_t e = cudaGraphLaunch(gr.preP[k - 1][l], cs); - if (e != cudaSuccess) { - cudaEventDestroy(a); - cudaEventDestroy(b); - err = std::string("session_replay_stage_sweep: launch: ") + cudaGetErrorString(e); - return false; - } - } - cudaEventRecord(b, cs); - if (cudaStreamSynchronize(cs) != cudaSuccess) { - cudaEventDestroy(a); - cudaEventDestroy(b); - err = "session_replay_stage_sweep: sync"; - return false; - } - float v = 0; - cudaEventElapsedTime(&v, a, b); - cudaEventDestroy(a); - cudaEventDestroy(b); - ms = (double) v; - return true; -} - -bool session_replay_stage_prefixes(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, - SessionGraphs& gr, void* stream, std::vector& stage_ms, - std::vector& mixer_per_layer, std::string& err) { - if (!gr.split_captured || gr.preP[0] == nullptr) { - err = "session_replay_stage_prefixes: not captured with the split"; - return false; - } - cudaStream_t cs = (cudaStream_t) stream; - stage_token(g, pos, pos_base, s); - const int64_t n = g.n_layers; - const size_t r_floats = (size_t) g.hc * (size_t) g.n_embd; - - float* saved = nullptr; - if (cudaMalloc((void**) &saved, r_floats * sizeof(float)) != cudaSuccess) { - err = "session_replay_stage_prefixes: could not save the residual"; - return false; - } - std::vector ev((size_t) (n * 6)); - bool ev_ok = true; - for (auto& e : ev) if (cudaEventCreate(&e) != cudaSuccess) { ev_ok = false; break; } - if (!ev_ok) { - for (auto& e : ev) cudaEventDestroy(e); - cudaFree(saved); - err = "session_replay_stage_prefixes: event create"; - return false; - } - struct Cleanup { - std::vector* v; - float* p; - ~Cleanup() { for (auto& e : *v) cudaEventDestroy(e); cudaFree(p); } - } cleanup{&ev, saved}; - - double t[5] = {0, 0, 0, 0, 0}; - mixer_per_layer.assign((size_t) n, 0.0); - for (int64_t l = 0; l < n; ++l) { - // The residual as this layer receives it, before any prefix has advanced it. - cudaMemcpyAsync(saved, s.block.R, r_floats * sizeof(float), cudaMemcpyDeviceToDevice, cs); - for (int k = 1; k <= 5; ++k) { - if (k > 1) cudaMemcpyAsync(s.block.R, saved, r_floats * sizeof(float), cudaMemcpyDeviceToDevice, cs); - cudaEventRecord(ev[(size_t) (l * 6 + k - 1)], cs); - const cudaGraphExec_t ge = (k == 5) ? gr.execs[l] : gr.preP[k - 1][l]; - const cudaError_t e = cudaGraphLaunch(ge, cs); - if (e != cudaSuccess) { - err = std::string("session_replay_stage_prefixes: launch prefix ") + std::to_string(k) + ": " + - cudaGetErrorString(e); - return false; - } - } - cudaEventRecord(ev[(size_t) (l * 6 + 5)], cs); - } - if (cudaStreamSynchronize(cs) != cudaSuccess) { err = "prefixes: final sync"; return false; } - - float t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0; - for (int64_t l = 0; l < n; ++l) { - float a = 0, b = 0, c = 0, d = 0, e = 0; - cudaEventElapsedTime(&a, ev[(size_t) (l * 6 + 0)], ev[(size_t) (l * 6 + 1)]); - cudaEventElapsedTime(&b, ev[(size_t) (l * 6 + 1)], ev[(size_t) (l * 6 + 2)]); - cudaEventElapsedTime(&c, ev[(size_t) (l * 6 + 2)], ev[(size_t) (l * 6 + 3)]); - cudaEventElapsedTime(&d, ev[(size_t) (l * 6 + 3)], ev[(size_t) (l * 6 + 4)]); - cudaEventElapsedTime(&e, ev[(size_t) (l * 6 + 4)], ev[(size_t) (l * 6 + 5)]); - t1 += a; t2 += b; t3 += c; t4 += d; t5 += e; - mixer_per_layer[(size_t) l] = (double) c; // prefix 3 IS the mixer: stages 0..2 - } - t[0] = t1; - t[1] = t2 - t1; - t[2] = t3 - t2; - t[3] = t4 - t3; - t[4] = t5 - t4; - stage_ms.assign(t, t + 5); - return true; -} - -void session_graphs_free(SessionGraphs& gr) { - if (gr.execs) { - for (int64_t i = 0; i < gr.n; ++i) cudaGraphExecDestroy(gr.execs[i]); - delete[] gr.execs; - } - if (gr.posts) { - for (int64_t i = 0; i < gr.n; ++i) - if (gr.posts[i] != nullptr) cudaGraphExecDestroy(gr.posts[i]); - delete[] gr.posts; - } - if (gr.preA) { - for (int64_t i = 0; i < gr.n; ++i) - if (gr.preA[i] != nullptr) cudaGraphExecDestroy(gr.preA[i]); - delete[] gr.preA; - } - if (gr.preB) { - for (int64_t i = 0; i < gr.n; ++i) - if (gr.preB[i] != nullptr) cudaGraphExecDestroy(gr.preB[i]); - delete[] gr.preB; - } - for (int k = 0; k < 5; ++k) { - if (gr.preP[k] == nullptr) continue; - for (int64_t i = 0; i < gr.n; ++i) - if (gr.preP[k][i] != nullptr) cudaGraphExecDestroy(gr.preP[k][i]); - delete[] gr.preP[k]; - gr.preP[k] = nullptr; - } - gr.preA = nullptr; - gr.preB = nullptr; - gr.split_captured = false; - gr.posts = nullptr; - gr.execs = nullptr; - gr.parts_dev = nullptr; - gr.n = 0; - gr.captured = false; -} - -bool SessionLoopScratch::init(size_t parts_bytes_in, std::string& err) { - if (y_miss != nullptr || probe != nullptr) { - err = "SessionLoopScratch::init: already initialised"; - return false; - } - parts_bytes = parts_bytes_in; - // MAPPED as well as pinned: the token graph's handoff kernel reads it through its device pointer. - if (cudaHostAlloc((void**) &y_miss, parts_bytes, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess) { - err = "SessionLoopScratch: cudaHostAlloc for the pool's staging failed"; - return false; - } - std::memset(y_miss, 0, parts_bytes); - if (cudaEventCreate(&probe) != cudaSuccess) { - err = "SessionLoopScratch: cudaEventCreate failed"; - free(); - return false; - } - // **PIN THE HOST ONCE, NOT ONCE PER TOKEN.** `ExpertPool` builds its workers from `physical_cores(true)`, - // which drops the first physical core so the host loop can spin without taking a worker's cycles - and - // nothing in the pool can pin the host, so if this does not happen the spin is free to land on a worker's - // core or its SMT sibling. The symptom is not an error: it is a CPU path at 26.9 GB/s where the same pool - // runs at 36.32. It was being done and undone on EVERY token, which is a syscall pair on the critical path - // for a property that wants to hold for the whole session. - const std::vector cores = strata::kernels::cpu::physical_cores(false); - if (!cores.empty()) { - pinned_core = strata::kernels::cpu::pin_current_thread(cores[0]); - pinned = pinned_core.valid; - } - return true; -} - -void SessionLoopScratch::free() { - // Restores the caller's affinity on every path, including teardown: a library that silently leaves its - // caller's thread nailed to one core is worse than one that never pinned at all. - if (pinned) { - strata::kernels::cpu::restore_thread_affinity(pinned_core); - pinned = false; - pinned_core = {}; - } - if (probe != nullptr) { cudaEventDestroy(probe); probe = nullptr; } - if (y_miss != nullptr) { cudaFreeHost(y_miss); y_miss = nullptr; } - parts_bytes = 0; -} - -bool session_loop(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, SessionGraphs& gr, - PoolFn pool, HitFn hits, void* user, bool overlap, void* stream, std::string& err, - float* dump_layers, SessionLoopScratch* scratch) { - if (!gr.captured || gr.n != g.n_layers) { err = "session_loop: not captured"; return false; } - if (gr.parts_dev == nullptr) { err = "session_loop: the graphs were captured without a parts buffer"; return false; } - if (s.db == nullptr) { err = "session_loop: no doorbell; the loop has nothing to poll"; return false; } - - cudaStream_t cs = (cudaStream_t) stream; - const int64_t k = s.k; - const size_t parts_bytes = (size_t) k * g.n_embd * 4; - ++gr.calls_total; - - // ================================ THE POSITION, WHICH THIS LOOP NEVER STAGED ================================ - // - // **EVERY TOKEN AFTER THE FIRST USED TO REPLAY POSITION 0.** The QSA layers read their per-token counts from - // `st.step` and `st.pos_dev`, which are DEVICE buffers filled by an H2D copy captured INTO each graph. A - // graph bakes the SOURCE POINTER, not the value - so the copy re-reads the pinned host buffers on every - // replay, and those hold whatever was last written there. `session_capture` left them at position 0. - // - // `layer.hpp` documents the requirement this loop was missing: "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." `session_replay` calls `stage_token`; - // `session_loop` did not. **A single-token test cannot see a position that never advances** - which is why - // the whole suite passed while a 20-token prompt rotated every token at position 0. - stage_token(g, pos, pos_base, s); - - // ---- **THE TOKEN PATH ALLOCATES NOTHING (P2.T10, review finding H3).** - // - // Everything this loop needs on the host - the pinned staging for the pool's answer, the doorbell probe - // event, and the host pin - lives in a `SessionLoopScratch` owned by the SESSION and passed in. It used to - // be created here, once per token, and `cudaFreeHost` at the end of the call IMPLICITLY SYNCHRONISES THE - // DEVICE, so every token finished with a device-wide sync that nothing had asked for. A comment here said - // "allocated once"; once per token is not once. - // - // Passing `nullptr` keeps the old behaviour so existing callers and tests are unaffected: the loop builds a - // local scratch and frees it on every exit path below, including the error returns. - SessionLoopScratch local; - if (scratch == nullptr) { - if (!local.init(parts_bytes, err)) return false; - scratch = &local; - } - struct LocalFree { - SessionLoopScratch* p; - ~LocalFree() { if (p != nullptr) p->free(); } - } local_free{scratch == &local ? &local : nullptr}; - if (scratch->parts_bytes != parts_bytes) { - err = "session_loop: the scratch was sized for a different k or n_embd"; - return false; - } - - // HOST-side staging for the pool's answer. It is copied to `gr.parts_dev` before the next launch, on the - // same stream, so the ordering is the stream's and no captured node is needed for it. - // - // ---- **PINNED, BECAUSE A COPY FROM PAGEABLE MEMORY IS NOT ASYNCHRONOUS AT ALL.** - // - // `cudaMemcpyAsync` with a pageable source cannot DMA: the driver first memcpys the bytes into an internal - // pinned bounce buffer, SYNCHRONOUSLY, on this thread, and only then enqueues the transfer. So the "async" - // copy would be a blocking memcpy plus a driver round trip, on the critical path of all 48 layers. The - // doorbell's `h_x_f` is `cudaHostAlloc(Mapped)` for exactly this reason and this buffer is the same kind of - // object. - float* y_miss = scratch->y_miss; - cudaEvent_t probe = scratch->probe; - - // the first layer has no previous layer's experts: `y_miss` starts at zero, which is what "hits are empty - // in this phase" means once every miss has been computed - cudaMemcpyAsync(gr.parts_dev, y_miss, parts_bytes, cudaMemcpyHostToDevice, cs); - doorbell_reset(*s.db); - uint32_t expected = 0; - - // **`pre[0]` IS LAUNCHED BEFORE THE LOOP SO EVERY ITERATION HAS THE SAME SHAPE**: poll the ring that - // `pre[l]` published, run the pool on it, combine, then start layer `l+1`'s `pre`. - // - // SLOT 0 OF THE DUMP IS THE INPUT, not a layer output. `s.R` holds the embedding broadcast to every stream - // when this function is entered, which is the reference's `hc_init` node - so dumping it here is what splits - // "the input to layer 0 is already wrong" from "layer 0 is wrong". - if (dump_layers != nullptr) { - const size_t n = (size_t) g.hc * (size_t) g.n_embd; - const cudaError_t de = cudaMemcpyAsync(dump_layers, s.R, n * sizeof(float), cudaMemcpyDeviceToHost, cs); - if (de != cudaSuccess) { - err = "session_loop: dump the input residual: " + std::string(cudaGetErrorString(de)); - return false; - } - } - { - const auto t0 = std::chrono::steady_clock::now(); - const cudaError_t le = cudaGraphLaunch(gr.execs[0], cs); - if (le != cudaSuccess) { - err = "session_loop: launch pre[0]: " + std::string(cudaGetErrorString(le)); - return false; - } - cudaEventRecord(probe, cs); - (void) t0; - } - - for (int64_t l = 0; l < g.n_layers; ++l) { - const auto t_launch = std::chrono::steady_clock::now(); - - // ---- poll for the ring. **THE DRIVER CALL IS NOW A FALLBACK, NOT THE MECHANISM.** - const uint32_t want = ++expected; - bool rang = false; - bool mid_graph = false; - // VOLATILE, because the device writes this through mapped pinned memory and a cached host line would - // never see it. Read through a volatile pointer so the compiler re-issues the load every iteration - - // otherwise this whole spin collapses into `while (true) { }`. - volatile uint32_t* const seq = s.db->h_seq; - for (;;) { - // **THE PER-ITERATION DRIVER CALL IS REQUIRED, AND THREE EXPERIMENTS NOW SAY SO.** Round 287 - // throttled this to one call in 64 and broke tests 51 and 56; adding `__threadfence_system()` to - // `doorbell_ring_kernel` and a volatile read here, then throttling, broke them again. So the call - // is not merely flushing submission (round 195's reading) and it is not a missing fence either: on - // this driver, the device's write to mapped pinned memory becomes host-visible only when the driver - // is entered. The fence and the volatile read are kept because they are correct and cost nothing - - // without them the ring's ordering against `x_f`/`ids`/`weights` is unstated - but they do not - // remove the need for the call, and nothing here should be read as claiming they do. - const cudaError_t q = cudaEventQuery(probe); - if (!rang && *seq >= want) { - rang = true; - mid_graph = (q != cudaSuccess); - } - if (q == cudaSuccess) break; // the graph has ended - if (q != cudaErrorNotReady) { - err = "session_loop: query at layer " + std::to_string(l) + ": " + cudaGetErrorString(q); - return false; - } - if (rang) break; // rung, and the graph is still running: the overlap - STRATA_SPIN_PAUSE(); - } - if (mid_graph) ++gr.rings_mid_graph; - // the window, from just before the launch to the instant the ring was seen - const auto t_ring = std::chrono::steady_clock::now(); - gr.ms_to_ring += std::chrono::duration(t_ring - t_launch).count(); - if (!rang) { - // The graph finished without the ring being observed. `h_seq` is monotonic, so this is not a race - // - it means the ring never happened, which is the failure round 199 found in a captured event. - err = "session_loop: layer " + std::to_string(l) + " ended without ringing"; - return false; - } - - // ---- **THE GPU'S HALF GOES FIRST, SO IT RUNS WHILE THE CPU DOES ITS HALF.** `Launch` only enqueues: - // the quantize and the grouped expert kernel land on `main_cs` and the GPU starts on them immediately, - // while the host is still inside `pool` below. Nothing here waits. - if (hits != nullptr) hits(user, cs, HitPhase::Launch, s.db->h_ids, k); - - // ---- the pool, on the bytes the doorbell published. **THESE ARE LAYER `l`'s EXPERTS.** - if (pool != nullptr) pool(user, s.db->h_x_f, s.db->h_ids, s.db->h_weights, g.n_embd, k, y_miss); - - // ---- **AND THEY ARE COMBINED BY LAYER `l`, NOT BY LAYER `l+1`.** - // - // This copy and the launch below are the whole of the L100 fix. `moe_combine` multiplies `parts` by - // THIS layer's `b.weights`, so `parts` must be THIS layer's expert outputs; the previous form copied - // the pool's answer into `parts_dev` for the NEXT layer, which computed - // `sum_j w_{l+1}[j] * expert_{ids_l,j}(x_l)` - both the selection and the input one layer stale while - // the weights were current. It produced finite, fluent, deterministic tokens that were not the - // model's, and no timing test could see it. - cudaMemcpyAsync(gr.parts_dev, y_miss, parts_bytes, cudaMemcpyHostToDevice, cs); - // ---- **AND THEN THE COMBINE.** Stream-ordered after the copy above, so `hit_out` is added to misses - // that are already in `parts`, and before `post[l]`, whose `moe_combine` reads the sum. A no-op when - // there is no VRAM tier or nothing is resident, which is every layer until the cache warms. - if (hits != nullptr) hits(user, cs, HitPhase::Combine, nullptr, 0); - { - const cudaError_t pe = cudaGraphLaunch(gr.posts[l], cs); - if (pe != cudaSuccess) { - err = "session_loop: launch post[" + std::to_string(l) + "]: " + cudaGetErrorString(pe); - return false; - } - } - // ---- the C1 oracle. `s.R` now holds layer `l`'s residual and keeps it until `post[l+1]` writes it, so - // a copy enqueued HERE - after `post[l]`, before `pre[l+1]` - is ordered correctly by the stream alone. - // Nothing is synchronised: the loop's existing final sync is what completes these. See the note on - // `dump_layers` in session.hpp for why this is an enqueue and not a read. - if (dump_layers != nullptr) { - const size_t n = (size_t) g.hc * (size_t) g.n_embd; - const cudaError_t de = cudaMemcpyAsync(dump_layers + (size_t) (l + 1) * n, s.R, n * sizeof(float), - cudaMemcpyDeviceToHost, cs); - if (de != cudaSuccess) { - err = "session_loop: dump layer " + std::to_string(l) + ": " + cudaGetErrorString(de); - return false; - } - } - if (!overlap) { - // THE COMPARISON ARM. The same sequence with the pipeline removed: the CPU does not start until the - // layer is over, so nothing overlaps and the difference is attributable to the doorbell alone. - if (cudaStreamSynchronize(cs) != cudaSuccess) { - err = "session_loop: sync at layer " + std::to_string(l); - return false; - } - } - // ---- and layer l+1's routing starts. `pre[l+1]` touches none of the buffers `post[l]` reads, because - // the two are ordered on one stream and `pre[l+1]`'s first use of `bb.mixed`/`bb.inject` is its own - // `gr_read`, which comes after `post[l]` has consumed them. - if (l + 1 < g.n_layers) { - const cudaError_t ne = cudaGraphLaunch(gr.execs[l + 1], cs); - if (ne != cudaSuccess) { - err = "session_loop: launch pre[" + std::to_string(l + 1) + "]: " + cudaGetErrorString(ne); - return false; - } - cudaEventRecord(probe, cs); - } - // ---- **THE SECOND HALF OF THE ROUND TRIP, AND THE HALF NOTHING WAS MEASURING.** - // - // From seeing the ring to having queued the next `pre`. Everything in here is a driver call, and on - // the token path the GPU has nothing left to run for most of it - `pre[l]` has already rung, and - // `post[l]` cannot start until this code launches it. So this interval is GPU-idle time, and it is - // the number that decides whether the fix is R2.4 (fewer launches per layer) or a faster kernel. - // - // It INCLUDES the `!overlap` synchronisation when that arm is selected, which is deliberate: that arm - // exists to show what the pipeline is worth, and hiding its cost here would defeat the comparison. - gr.ms_host += std::chrono::duration(std::chrono::steady_clock::now() - t_ring).count(); - } - if (cudaStreamSynchronize(cs) != cudaSuccess) { err = "session_loop: final sync"; return false; } - return true; -} - -bool session_token(const WeightTable& tables, const ModelGeometry& g, int64_t pos, int32_t pos_base, - SessionState& s, const float* parts, void* stream, bool sync_every_layer, - std::string& err) { - cudaStream_t cs = (cudaStream_t) stream; - int64_t qsa_index = 0; - int64_t gdn_index = 0; - - for (int64_t l = 0; l < g.n_layers; ++l) { - // THE GDN LAYERS EACH GET THEIR OWN STATE, and `GdnBuffers` carries it - so the session points the - // shared scratch at the right slice before each call. Sharing one state across 36 layers would make - // every layer start from the previous layer's recurrence, which produces a perfectly finite answer. - if (!is_qsa_layer(g, l)) { - s.gdn.state = s.gdn_state + (size_t) gdn_index * gdn_state_floats(g); - s.gdn.conv_state = s.gdn.state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; - ++gdn_index; - } - - err.clear(); - const bool ok = is_qsa_layer(g, l) - ? block_layer(tables, g, l, pos, pos_base, s.gdn, s.qsa_states[qsa_index], s.qsa_bufs, s.moe, s.k, - s.block, parts, stream, err, nullptr, s.ple.ready() ? &s.ple : nullptr) - : block_layer(tables, g, l, pos, pos_base, s.gdn, s.qsa_states[0], s.qsa_bufs, s.moe, s.k, - s.block, parts, stream, err, nullptr, s.ple.ready() ? &s.ple : nullptr); - if (!ok) { - err = "layer " + std::to_string(l) + ": " + err; - return false; - } - if (is_qsa_layer(g, l)) ++qsa_index; - - if (sync_every_layer) { - // THE DEBUG MODE, and its cost is the point: it is a real synchronisation after every layer, which - // P2.X3 forbids in the fast path. It exists to turn an ASYNCHRONOUS error - a kernel reading a - // buffer a later layer wrote, or an out-of-range launch - into a failure AT THE LAYER THAT CAUSED - // IT, instead of a wrong number 40 layers later or at the end of the token. - const cudaError_t e = cudaStreamSynchronize(cs); - if (e != cudaSuccess) { - err = "layer " + std::to_string(l) + ": " + cudaGetErrorString(e); - return false; - } - } - } - return true; -} - -} // namespace strata::core - -namespace strata::core { - -bool session_capture_token(const WeightTable& tables, const ModelGeometry& g, SessionState& s, float* parts_dev, - const float* y_miss_host, size_t parts_bytes, TokenGraph& tg, std::string& err, - const TokenHits* hits) { - if (hits != nullptr && !hits->on()) { err = "session_capture_token: incomplete hit configuration"; return false; } - if (tg.captured) return true; - if (s.db == nullptr || s.db->d_flag == nullptr || s.db->d_seq == nullptr) { - err = "session_capture_token: the doorbell has no flag"; - return false; - } - if (parts_dev == nullptr || y_miss_host == nullptr || parts_bytes == 0) { - err = "session_capture_token: parts buffers are required"; - return false; - } - float* y_dev = nullptr; - if (cudaHostGetDevicePointer((void**) &y_dev, const_cast(y_miss_host), 0) != cudaSuccess || !y_dev) { - err = "session_capture_token: the parts staging is not mapped pinned memory"; - return false; - } - cudaStream_t cs = nullptr; - if (cudaStreamCreate(&cs) != cudaSuccess) { err = "session_capture_token: stream create failed"; return false; } - if (cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { - cudaStreamDestroy(cs); - err = "session_capture_token: begin capture failed"; - return false; - } - int64_t qsa_index = 0; - bool ok = true; - for (int64_t l = 0; l < g.n_layers && ok; ++l) { - gdn_point_at(g, l, s); - const bool qsa = is_qsa_layer(g, l); - QsaState& qst = qsa ? s.qsa_states[qsa_index] : s.qsa_states[0]; - err.clear(); - ok = block_layer_pre(tables, g, l, 0, 0, s.gdn, qst, s.qsa_bufs, s.moe, s.k, s.block, (void*) cs, err, s.db, - s.ple.ready() ? &s.ple : nullptr); - if (!ok) { err = "session_capture_token: pre layer " + std::to_string(l) + ": " + err; break; } - if (hits != nullptr) { - // After the ring (and the shared expert): the GPU's experts run while the CPU computes the misses. - strata::kernels::moe_hit_select(s.moe.ids, hits->d_res + l * hits->n_expert, (int) s.k, - (int) hits->n_expert, hits->d_slot, hits->d_dst, hits->d_count, (void*) cs); - strata::kernels::quantize_q8_0_scaled(s.block.mixed, hits->x_q8, hits->x_scale, g.n_embd, (void*) cs); - strata::kernels::moe_hit_grouped_s2_dev(hits->cache_base, hits->d_slot, hits->d_dst, hits->d_count, s.k, - hits->blob, hits->x_q8, hits->scratch, hits->hit_out, (void*) cs, - hits->x_scale); - } - strata::kernels::doorbell_wait(s.db->d_flag, s.db->d_seq, (void*) cs); - // A kernel, not a memcpy node: a copy-engine node splits the WDDM submission (measured 67 flushes/token). - strata::kernels::copy_from_mapped(parts_dev, y_dev, (int64_t) (parts_bytes / sizeof(float)), (void*) cs); - if (hits != nullptr) - strata::kernels::moe_hit_add(parts_dev, hits->hit_out, hits->d_dst, hits->d_count, s.k, g.n_embd, (void*) cs); - ok = block_layer_post(tables, g, l, s.k, s.moe, s.block, parts_dev, (void*) cs, err); - if (!ok) { err = "session_capture_token: post layer " + std::to_string(l) + ": " + err; break; } - if (qsa) ++qsa_index; - } - cudaGraph_t graph = nullptr; - const cudaError_t ce = cudaStreamEndCapture(cs, &graph); - cudaStreamDestroy(cs); - if (!ok) { if (graph) cudaGraphDestroy(graph); return false; } - if (ce != cudaSuccess) { - err = std::string("session_capture_token: end capture: ") + cudaGetErrorString(ce); - return false; - } - const cudaError_t ie = cudaGraphInstantiate(&tg.exec, graph, 0); - cudaGraphDestroy(graph); - if (ie != cudaSuccess) { - err = std::string("session_capture_token: instantiate: ") + cudaGetErrorString(ie); - return false; - } - tg.captured = true; - tg.n_layers = g.n_layers; - tg.y_src = y_miss_host; - tg.parts_bytes = parts_bytes; - return true; -} - -bool session_run_token(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, TokenGraph& tg, - PoolFn pool, void* user, float* y_miss_host, void* stream, std::string& err) { - if (!tg.captured) { err = "session_run_token: not captured"; return false; } - if (y_miss_host != tg.y_src) { err = "session_run_token: the staging buffer is not the captured one"; return false; } - cudaStream_t cs = (cudaStream_t) stream; - ++tg.calls; - stage_token(g, pos, pos_base, s); - doorbell_reset(*s.db); - const cudaError_t le = cudaGraphLaunch(tg.exec, cs); - if (le != cudaSuccess) { err = std::string("session_run_token: launch: ") + cudaGetErrorString(le); return false; } - (void) cudaStreamQuery(cs); // one flush, so WDDM submits the graph now - static const int flush_us = [] { - const char* e = std::getenv("STRATA_TG_FLUSH_US"); - return e ? std::atoi(e) : 2000; // 24 Sep: 0 flushes run as fast as 5 us ones; this only notices faults - }(); - volatile uint32_t* const seq = s.db->h_seq; - volatile uint32_t* const flag = s.db->h_flag; - using Clock = std::chrono::steady_clock; - for (int64_t l = 0; l < g.n_layers; ++l) { - const uint32_t want = (uint32_t) (l + 1); - const auto t0 = Clock::now(); - auto last_flush = t0; - uint32_t spins = 0; - progress_at("token: waiting for the GPU to reach layer", l); - while (*seq < want) { - STRATA_SPIN_PAUSE(); - if ((++spins & 1023u) != 0) continue; - const auto now = Clock::now(); - if (now - last_flush > std::chrono::microseconds(flush_us)) { - // A slow ring: flush the submission queue once more, and notice a fault or a finished graph. - last_flush = now; - ++tg.flushes; - const cudaError_t q = cudaStreamQuery(cs); - if (q != cudaErrorNotReady && *seq < want) { - err = "session_run_token: layer " + std::to_string(l) + " never rang (" + - (q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")"; - return false; - } - } - if (now - t0 > std::chrono::seconds(20)) { - err = "session_run_token: timed out waiting for layer " + std::to_string(l); - return false; - } - } - const auto t1 = Clock::now(); - progress_at("token: the CPU experts of layer", l); - if (pool != nullptr) pool(user, s.db->h_x_f, s.db->h_ids, s.db->h_weights, g.n_embd, s.k, y_miss_host); - std::atomic_thread_fence(std::memory_order_seq_cst); - _mm_sfence(); - *flag = want; - const auto t2 = Clock::now(); - tg.ms_wait += std::chrono::duration(t1 - t0).count(); - tg.ms_pool += std::chrono::duration(t2 - t1).count(); - } - progress_at("token: waiting for the GPU to finish the token"); - const cudaError_t se = cudaStreamSynchronize(cs); - if (se != cudaSuccess) { err = std::string("session_run_token: ") + cudaGetErrorString(se); return false; } - progress_at("decode"); - progress_beat(); - return true; -} - -void token_graph_free(TokenGraph& tg) { - if (tg.exec) cudaGraphExecDestroy(tg.exec); - tg = TokenGraph{}; -} - -} // namespace strata::core diff --git a/src/core/verify.cpp b/src/core/verify.cpp deleted file mode 100644 index 4a144c3..0000000 --- a/src/core/verify.cpp +++ /dev/null @@ -1,2268 +0,0 @@ -// 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) -#include -#endif - -#include "strata/core/native_head.hpp" -#include "strata/core/on_device.hpp" -#include "strata/core/peer_experts.hpp" -#include "strata/kernels/iq_kernels.hpp" -#include "strata/kernels/cpu/expert_layout.hpp" -#include "strata/kernels/bf16_gemv.hpp" -#include "strata/kernels/native_router.hpp" -#include "strata/kernels/native_moe.hpp" -#include "strata/kernels/cpu/expert.hpp" -#include "strata/kernels/elementwise.hpp" -#include "strata/kernels/fused_gr.hpp" -#include "strata/kernels/cvec.hpp" -#include "strata/kernels/gr.hpp" -#include "strata/kernels/kv_q4.hpp" -#include "strata/kernels/kv_q8.hpp" -#include "strata/kernels/native_mmvq.hpp" -#include "strata/kernels/native_qsa.hpp" -#include "strata/kernels/native_qsa_indexer.hpp" -#include "strata/kernels/native_rope.hpp" -#include "strata/kernels/ngram.hpp" -#include "strata/kernels/ple.hpp" -#include "strata/kernels/qsa.hpp" -#include "strata/kernels/qsa_decode_attn.hpp" -#include "strata/kernels/qsa_select.hpp" -#include "strata/kernels/quantize_act.hpp" -#include "strata/kernels/rope.hpp" -#include "strata/kernels/s2_expert_grouped.hpp" -#include "strata/kernels/sampler.hpp" -#include "strata/core/progress.hpp" -#include "strata/kernels/shared_expert.hpp" -#include "strata/kernels/verify_kernels.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace strata::core { -namespace { - -constexpr float EPS = 1e-6f; -using Clock = std::chrono::steady_clock; -double ms_since(Clock::time_point t) { return std::chrono::duration(Clock::now() - t).count(); } -const bool g_dbg = std::getenv("STRATA_VERIFY_DEBUG") != nullptr; -#define VDBG(...) do { if (g_dbg) { std::fprintf(stderr, "verify dbg: " __VA_ARGS__); std::fflush(stderr); } } while (0) - -struct Bump { - uint8_t* base = nullptr; - uint64_t used = 0; - template T* take(uint64_t n) { - T* p = base ? (T*) (base + used) : nullptr; - used += (n * sizeof(T) + 255) & ~255ull; - return p; - } -}; - -// #649 (HIP, opt-in A/Bs for the gfx1030 verify timeouts; CUDA never reads them) -// STRATA_VERIFY_COHERENT=1 the handshake words and rows in explicitly coherent (fine-grained) host memory -// STRATA_DOORBELL_STORE=1 the GPU stores each step's ring instead of read-modify-writing it over PCIe -bool env_on(const char* name) { - const char* e = std::getenv(name); - return e != nullptr && e[0] != 0 && e[0] != '0'; -} -#if defined(STRATA_USE_HIP) -const bool g_coherent = env_on("STRATA_VERIFY_COHERENT"); -const bool g_doorbell_store = env_on("STRATA_DOORBELL_STORE"); -#endif -const bool g_trace = env_on("STRATA_VERIFY_TRACE"); - -bool mapped(size_t bytes, void** h, void** d) { -#if defined(STRATA_USE_HIP) - if (g_coherent) { - if (hipHostMalloc(h, bytes, hipHostMallocMapped | hipHostMallocCoherent | - (peer_portable() ? hipHostMallocPortable : 0)) != hipSuccess) - return false; - std::memset(*h, 0, bytes); - return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess; - } -#endif - if (cudaHostAlloc(h, bytes, cudaHostAllocMapped | (peer_portable() ? cudaHostAllocPortable : 0)) != cudaSuccess) return false; // multi-GPU: portable only with a peer - the peer card writes its rows into them - std::memset(*h, 0, bytes); - return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess; -} - -// the one builder (strata/core/qsa_shapes.hpp): a dense geometry has its three indexer widths zero together -strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { return strata::core::qsa_shapes(g); } - -const WeightRef* need(const LayerView& v, const char* suffix, std::string& err) { - const WeightRef* r = v.get(suffix); - if (r == nullptr && err.empty()) err = v.name(suffix) + " is missing"; - return r; -} - -bool native_of(const WeightRef* w, const std::string& name, std::string& err) { - if (w == nullptr) return false; - if (w->native_data == nullptr) { - err = "verify: " + name + " is not served natively (run with --native)"; - return false; - } - return true; -} - -} // 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 g_diag_verifier{nullptr}; -void diag_active_verifier(std::FILE* f) { - if (const Verifier* v = g_diag_verifier.load()) v->diag(f); -} -// #267: every live verifier (a layer split has one per stage), for the release before the engine ends -constexpr int kLiveMax = 16; -std::atomic g_live[kLiveMax]; -void release_live_verifiers(std::FILE* f) { - for (auto& slot : g_live) - if (Verifier* v = slot.load()) { - const Clock::time_point t0 = Clock::now(); - const bool done = v->release_gpu_waits(5000); - if (f != nullptr) - std::fprintf(f, "strata: released the verify window's GPU waits (#267): the GPU %s\n", - done ? ("finished in " + std::to_string((long long) ms_since(t0)) + " ms").c_str() - : "did not finish within 5 s"); - } - if (f != nullptr) std::fflush(f); -} -// #649: the host side of STRATA_VERIFY_TRACE - a ring of the last kTraceN handshake events of every verifier -struct TraceEv { - int64_t t_ns; - const void* who; - int64_t window, step, layer, aux; - uint32_t seq, flag, a, b; - const char* what; -}; -constexpr uint64_t kTraceN = 4096; -TraceEv g_trace_ring[kTraceN]; -std::atomic g_trace_next{0}; -int64_t trace_now_ns() { - return std::chrono::duration_cast(Clock::now().time_since_epoch()).count(); -} -std::string released_note(bool drained) { - return drained ? "; its GPU waits were released and the GPU finished (#267)" - : "; its GPU waits were released but the GPU did not finish within 5 s (#267)"; -} -// #267 test hook: STRATA_TEST_VERIFY_STALL=N withholds the last layer's flag in the N-th window (1-based), so the -// GPU spins on a flag nobody raises - the bounded window wait and the release are then what ends it. Unset: never. -const int64_t g_test_stall = [] { - const char* e = std::getenv("STRATA_TEST_VERIFY_STALL"); - return e != nullptr ? (int64_t) std::atoll(e) : (int64_t) 0; -}(); -} // namespace - -bool Verifier::release_gpu_waits(int timeout_ms) { - released_.store(true); - trace_ev("RELEASE", -1, -1, timeout_ms); - // the words the spin kernels read (wait_flag_ge, wait_flag_ge_or) are mapped host memory, so a store here - // reaches them with no API call; UINT32_MAX is past every ring. (E-6's skip words are device memory, but - // wait_flag_ge_or also returns on its flag.) A host function raising flag B later only raises. - for (uint32_t* p : {h_flag_, h_flagA_, h_flagB_}) - if (p != nullptr) *(volatile uint32_t*) p = UINT32_MAX; - std::atomic_thread_fence(std::memory_order_seq_cst); - _mm_sfence(); - const OnDevice on_device(device_); - const Clock::time_point t0 = Clock::now(); - for (cudaStream_t s : {cs_, copy_}) { - if (s == nullptr) continue; - while (cudaStreamQuery(s) == cudaErrorNotReady) { - if (ms_since(t0) > timeout_ms) { - trace_ev("RELEASE-NOT-DRAINED", -1, -1, (int64_t) ms_since(t0)); - return false; - } - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } - } - trace_ev("RELEASE-DRAINED", -1, -1, (int64_t) ms_since(t0)); // aux: ms the GPU took to finish once released - return true; -} - -void Verifier::trace_ev(const char* what, int64_t step, int64_t layer, int64_t aux) const { - if (!g_trace) return; - auto rd = [](const uint32_t* p) { return p ? *(const volatile uint32_t*) p : 0u; }; - TraceEv& e = g_trace_ring[g_trace_next.fetch_add(1) % kTraceN]; - e = {trace_now_ns(), this, windows, step, layer, aux, rd(h_seq_), rd(h_flag_), rd(h_flagA_), rd(h_flagB_), what}; -} - -void Verifier::trace_dump(std::FILE* f) const { - if (!g_trace || f == nullptr) return; - static const char* names[kProfPer] = {"pre", "hc-read0", "qkv gemv", "conv", "ab", "z", "rec", "kv-idx", - "k/v rope", "kv append", "q", "scores+topk", "kv-resolve", "attention", - "gate", "", "out-proj", "router+ring", "shared", "waitA", "VRAM hits", "waitB", - "PCIe grp", "waitCPU", "combine", "", "head", "", "", "", "", "", ""}; - const uint64_t end = g_trace_next.load(); - const uint64_t n = end < 160 ? end : 160; - std::fprintf(f, "strata verify trace (#649): the last %llu handshake events (host clock, us before the last; " - "words: seq = GPU rang, flag = CPU served, A = plan, B = copies)\n", (unsigned long long) n); - const int64_t t_last = n ? g_trace_ring[(end - 1) % kTraceN].t_ns : 0; - for (uint64_t i = end - n; i < end; ++i) { - const TraceEv& e = g_trace_ring[i % kTraceN]; - if (e.what == nullptr) continue; - std::fprintf(f, " %10.1f %-20s v%p window %lld step %lld layer %lld aux %lld | seq %u flag %u A %u B %u\n", - (double) (t_last - e.t_ns) / 1000.0, e.what, e.who, (long long) e.window, (long long) e.step, - (long long) e.layer, (long long) e.aux, e.seq, e.flag, e.a, e.b); - } - if (trace_h_ == nullptr || g_ == nullptr) return; - // the breadcrumbs: every stamp point the GPU passed in this window (ns of the GPU clock after the window's first) - unsigned long long t0 = ~0ull; - for (size_t i = 0; i < trace_n_; ++i) { - const unsigned long long t = *(const volatile unsigned long long*) (trace_h_ + i); - if (t != 0 && t < t0) t0 = t; - } - if (t0 == ~0ull) { - std::fprintf(f, "strata verify trace: no GPU breadcrumb in this window (the GPU never started it)\n"); - return; - } - int64_t last_l = -1; - for (int64_t l = 0; l <= g_->n_layers; ++l) - for (int i = 0; i < kProfPer; ++i) - for (int grp = 0; grp < 2; ++grp) - if (trace_h_[(size_t) ((l * kProfPer + i) * 2 + grp)] != 0) last_l = l; - std::fprintf(f, "strata verify trace: GPU breadcrumbs (us after the window's first), the GPU got as far as layer " - "%lld:\n", (long long) last_l); - for (int64_t l = std::max(0, last_l - 2); l <= std::min(g_->n_layers, last_l + 1); ++l) - for (int grp = 0; grp < 2; ++grp) { - std::string line; - char b[64]; - for (int i = 0; i < kProfPer; ++i) { - const unsigned long long t = trace_h_[(size_t) ((l * kProfPer + i) * 2 + grp)]; - if (t == 0) continue; - std::snprintf(b, sizeof b, " %s(%d)=%.1f", names[i], i, (double) (t - t0) / 1000.0); - line += b; - } - if (!line.empty()) - std::fprintf(f, " layer %lld group %d:%s\n", (long long) l, grp, line.c_str()); - } - std::fflush(f); -} - -void Verifier::diag(std::FILE* f) const { - auto rd = [](const uint32_t* p) { return p ? *(const volatile uint32_t*) p : 0u; }; - // #251: outside a verify stage these are the LAST window's numbers (it finished), not the stalled work's - const char* where = progress().where.load(); - const bool current = where != nullptr && std::strncmp(where, "verify window", 13) == 0; - std::fprintf(f, " verify window%s: %d tokens at position %lld, host at layer step %u; the GPU rang %u; flags: " - "served %u, plan (A) %u, copies (B) %u\n", current ? "" : " (last window, not the current stage)", - last_t_, (long long) last_pos0_, cur_layer_ + 1, rd(h_seq_), rd(h_flag_), rd(h_flagA_), rd(h_flagB_)); - trace_dump(f); // #649: STRATA_VERIFY_TRACE=1 only -} - -Verifier::~Verifier() { - const Verifier* self = this; - g_diag_verifier.compare_exchange_strong(self, nullptr); - for (auto& slot : g_live) { - Verifier* me = this; - slot.compare_exchange_strong(me, nullptr); - } - if (cs_) cudaStreamSynchronize(cs_); - if (sh_cs_) cudaStreamSynchronize(sh_cs_); - for (auto& e : exec_) - if (e) cudaGraphExecDestroy(e); - if (commit_exec_) cudaGraphExecDestroy(commit_exec_); - for (auto& kv : exec_bm_) - if (kv.second) cudaGraphExecDestroy(kv.second); - for (auto& kv : commit_bm_) - if (kv.second) cudaGraphExecDestroy(kv.second); - if (arena_b_) cudaFree(arena_b_); - if (h_commitb_) cudaFreeHost(h_commitb_); - if (cs_) cudaStreamDestroy(cs_); - if (sh_cs_) cudaStreamDestroy(sh_cs_); - if (copy_) { cudaStreamSynchronize(copy_); cudaStreamDestroy(copy_); } - if (commit_done_) cudaEventDestroy(commit_done_); - if (ev_fork_) cudaEventDestroy(ev_fork_); - if (ev_join_) cudaEventDestroy(ev_join_); - if (arena_) cudaFree(arena_); - void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_, - h_flagA_, h_plan_, h_flagB_}; - for (void* h : hosts) - if (h) cudaFreeHost(h); -} - -bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& ss, const VerifyHits& hits, - const NativeHead* head, int max_t, std::string& err) { - g_diag_verifier.store(this); - diag_verify_fn().store(&diag_active_verifier); - for (auto& slot : g_live) { - Verifier* none = nullptr; - if (slot.load() == this || slot.compare_exchange_strong(none, this)) break; - } - release_gpu_fn().store(&release_live_verifiers); - cudaGetDevice(&device_); // a layer split's stage on another GPU: its streams, graphs and buffers live there - strata::kernels::fused_gr_check(); // once per card: which bitwise-equal hyper-connection read runs there - wt_ = &wt; - g_ = &g; - ss_ = &ss; - hits_ = hits; - head_ = head; - max_t_ = max_t; - sampling_.greedy = true; // a fresh verifier samples greedily until set_sampling says otherwise - sampling_.temperature = 0.0f; - if (max_t < 2 || max_t > strata::kernels::kVerifyMaxT || max_t > strata::kernels::cpu::MAXT) { - err = "verify: the window must hold 2.." + std::to_string(strata::kernels::kVerifyMaxT) + " tokens"; - return false; - } - if (hits.d_res == nullptr || hits.cache_base == nullptr || hits.blob <= 0) { - err = "verify: needs the profile-filled VRAM expert tier (--expert-profile and --expert-cache); with " - "--expert-cache auto, no VRAM was left for it - the 'no VRAM is left for the expert cache' line above " - "says how much is short and what makes room (a smaller --max-context, --kv q4_0, setup --draft-vocab en, " - "images on the CPU)"; - return false; - } - std::string why; - if (!layer_verify_compatible(g, why)) { - err = "verify: " + why + " (the verify window reproduces the default native decode path)"; - return false; - } - if (!verify_geometry_supported(g, ss.k, why)) { - err = "verify: " + why; - return false; - } - if (le_ < 0) le_ = g.n_layers; - if (lb_ < 0 || lb_ >= le_ || le_ > g.n_layers || (lb_ > 0 && hand_in_ == nullptr) || - (le_ < g.n_layers && hand_out_ == nullptr)) { - err = "verify: the stage's layer range or its hand-off buffers are wrong"; - return false; - } - const WeightRef* wo = wt.find("output.weight"); - if (wo == nullptr) { err = "verify: output.weight is missing"; return false; } - n_vocab_ = wo->ne1; - - const strata::kernels::QsaShapes s = shapes_of(g); - cap_ = strata::kernels::qsa_selection_cap(ss.qsa_states[ss.qsa_primary()].max_cells, s); // dense: max_cells - 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; - const uint64_t C = (uint64_t) g.ssm_conv_channels, ZV = (uint64_t) g.ssm_value_dim, HV = (uint64_t) g.ssm_v_heads; - const uint64_t NH = (uint64_t) g.n_head, HD = (uint64_t) g.head_dim, NKV = (uint64_t) g.n_head_kv; - const uint64_t IQ = (uint64_t) g.idx_q_heads, ID = (uint64_t) g.idx_key_dim; - const uint64_t nG = (uint64_t) g.n_gdn_layers(), nQ = (uint64_t) g.n_qsa_layers(); - const uint64_t HS = (uint64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM; - const uint64_t TS = (uint64_t) (s.idx_block - 1) * ID; - const int max_in = (int) std::max(std::max(N, ZV), NH * HD); - - // ---- mapped staging - bool ok = mapped(T * 4, (void**) &h_tok_, (void**) &m_tok_) && - mapped(T * strata::kernels::kStepCount * 4, (void**) &h_step_, (void**) &m_step_) && - mapped(T * (NH + NKV + IQ) * 4, (void**) &h_pos_, (void**) &m_pos_) && - mapped((2 + T) * 4 + 16, (void**) &h_commit_, (void**) &m_commit_) && - mapped(T * N * 4, (void**) &h_ple_, (void**) &m_ple_) && - mapped(T * 4 + 16, (void**) &h_out_, (void**) &m_out_) && - mapped(T * N * 4, (void**) &h_x_, (void**) &m_x_) && - mapped(T * K * 4, (void**) &h_ids_, (void**) &m_ids_) && - mapped(T * K * 4, (void**) &h_w_, (void**) &m_w_) && - mapped(64, (void**) &h_seq_, (void**) &m_seq_) && - mapped(64, (void**) &h_flag_, (void**) &m_flag_) && - mapped(64, (void**) &h_flagA_, (void**) &m_flagA_) && - mapped(64, (void**) &h_flagB_, (void**) &m_flagB_) && - mapped(T * K * N * 4, (void**) &h_ymiss_, (void**) &m_ymiss_); - if (!ok) { err = "verify: mapped staging allocation failed"; return false; } - // the GPU plan: counts(4) | start(cap+1) | dst(cap) | tok(cap) | pad | ptr(cap u64) | ptr2(cap u64) | start2(cap+1) - { - const int64_t cap = (int64_t) (T * K); - const int64_t i32 = 4 + (cap + 1) + cap + cap; - const int64_t ptr_off = (i32 + 1) & ~1ll; - plan_i32_ = ptr_off + 4 * cap + (cap + 1) + 1; - if (!mapped((size_t) plan_i32_ * 4 * 2 + 64, (void**) &h_plan_, (void**) &m_plan_)) { - err = "verify: mapped plan allocation failed"; - return false; - } - sink_.counts = h_plan_; - sink_.start = h_plan_ + 4; - sink_.dst = sink_.start + cap + 1; - sink_.tok = sink_.dst + cap; - sink_.ptr = (unsigned long long*) (h_plan_ + ptr_off); - sink_.ptr2 = sink_.ptr + cap; - sink_.start2 = h_plan_ + ptr_off + 4 * cap; - sink_.cap = cap; - sink_.publish = &Verifier::publish_plan; - sink_.fetch = &Verifier::fetch_dma; - sink_.ctx = this; - } - - // ---- the device arena: the same sequence counted, then carved - auto carve = [&](Bump& b) { - tok_ = b.take(T); step_ = b.take(T * strata::kernels::kStepCount); - pos_ = b.take(T * (NH + NKV + IQ)); commit_ = b.take(2 + T); - ple_ = b.take(T * N); emb_ = b.take(T * N); R_ = b.take(T * HC * N); - mixed_ = b.take(T * N); bo_ = b.take(T * N); - inj_ = b.take(T * HC); inj2_ = b.take(T * HC); - lo_ = b.take(T * (uint64_t) g.hc_lr); rs_ = b.take(T * HC); xn_ = b.take(T * HC * N); - xq_ = b.take(strata::kernels::native_q8_1_bytes(max_in, (int) T)); - sh_xq_ = b.take(strata::kernels::native_q8_1_bytes(max_in, (int) T)); - qkv_L_ = b.take(nG * T * C); h_L_ = b.take(nG * T * C); - gate_L_ = b.take(nG * T * HV); beta_L_ = b.take(nG * T * HV); - z_ = b.take(T * ZV); y_ = b.take(T * ZV); y_dummy_ = b.take(T * ZV); - qfull_ = b.take(T * NH * 2 * HD); qcur_ = b.take(T * NH * HD); - kcur_ = b.take(T * NKV * HD); vcur_ = b.take(T * NKV * HD); - idx_raw_L_ = b.take(nQ * T * ID); qidx_ = b.take(T * IQ * ID); - if (!dense) { scores_ = b.take(T * (uint64_t) max_blocks_); sel_ = b.take(T * (uint64_t) cap_); } - attn_ = b.take(T * NH * HD); attn32_ = b.take(T * NH * HD); - attn_scratch_ = b.take(T * (uint64_t) attn_scratch_floats_); - tail_snap_ = b.take(nQ * TS); - logits_ = b.take(T * (uint64_t) g.n_expert); w_ = b.take(T * K); ids_ = b.take(T * K); - shared_ = b.take(T * N); parts_ = b.take(T * K * N); hit_out_ = b.take(T * K * N); - hit_slot_ = b.take(T * K); hit_dst_ = b.take(T * K); hit_count_ = b.take(4); - plan_ = b.take(2 * ((uint64_t) plan_i32_ + 16)); - staging_ = b.take((uint64_t) kStagingBlobs * strata::kernels::cpu::expert_layout().max_blob); - hit_xq_ = b.take(T * (N / 32) * 34); hit_xs_ = b.take(T * (N / 32)); - nat_xq_ = b.take(T * (N / 32) * 36); - hit_scratch_ = b.take(std::max( - strata::kernels::moe_hit_grouped_scratch_bytes((int64_t) (T * K), g.n_embd, g.n_ff), - strata::kernels::native_expert_scratch_bytes((int64_t) (T * K), g.n_ff))); - head_mixed_ = b.take(T * N); head_inj_ = b.take(HC); - sh_bf16_ = b.take(T * N); sh_gate_ = b.take(T * (uint64_t) g.n_ff); - sh_up_ = b.take(T * (uint64_t) g.n_ff); sh_g_ = b.take(T + 4); - head_logits_ = b.take(T * (uint64_t) n_vocab_); - hist_snap_ = b.take(T * HS); - }; - Bump count; - carve(count); - if (cudaMalloc(&arena_, count.used) != cudaSuccess) { - err = "verify: the device arena (" + std::to_string(count.used >> 20) + " MiB) does not fit"; - return false; - } - cudaMemset(arena_, 0, count.used); - if (g_trace && trace_h_ == nullptr) { // #649: the breadcrumbs, mapped so they read while the GPU hangs - trace_n_ = (size_t) (g.n_layers + 1) * kProfPer * 2; - if (!mapped(trace_n_ * 8, (void**) &trace_h_, (void**) &trace_m_)) { - (void) cudaGetLastError(); - trace_h_ = trace_m_ = nullptr; - trace_n_ = 0; - } -#if defined(STRATA_USE_HIP) - std::fprintf(stderr, "strata verify trace (#649): on; coherent words %s, doorbell %s, HIP_HOST_COHERENT=%s " - "HSA_ENABLE_SDMA=%s GPU_MAX_HW_QUEUES=%s\n", g_coherent ? "explicit" : "default", - g_doorbell_store ? "stored" : "incremented", std::getenv("HIP_HOST_COHERENT") ? std::getenv("HIP_HOST_COHERENT") : "-", - std::getenv("HSA_ENABLE_SDMA") ? std::getenv("HSA_ENABLE_SDMA") : "-", - std::getenv("GPU_MAX_HW_QUEUES") ? std::getenv("GPU_MAX_HW_QUEUES") : "-"); -#else - std::fprintf(stderr, "strata verify trace (#649): on\n"); -#endif - } - prof_on_ = std::getenv("STRATA_VERIFY_PROFILE") != nullptr; - if (prof_on_) { - const size_t np = (size_t) g.n_layers * kProfPer + 4; - if (cudaMalloc((void**) &prof_, np * 8) != cudaSuccess) { prof_on_ = false; prof_ = nullptr; cudaGetLastError(); } - else { cudaMemset(prof_, 0, np * 8); prof_h_.assign(np, 0); } - } - Bump real; - real.base = (uint8_t*) arena_; - carve(real); - sink_.staging = (unsigned long long) staging_; - sink_.staging_cap = kStagingBlobs; - (void) TS; - if (cudaStreamCreateWithFlags(©_, cudaStreamNonBlocking) != cudaSuccess) { - err = "verify: copy stream create failed"; - return false; - } - if (cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess || - cudaStreamCreateWithFlags(&sh_cs_, cudaStreamNonBlocking) != cudaSuccess) { - err = "verify: stream create failed"; - return false; - } - if (cudaEventCreateWithFlags(&commit_done_, cudaEventDisableTiming) != cudaSuccess || - cudaEventCreateWithFlags(&ev_fork_, cudaEventDisableTiming) != cudaSuccess || - cudaEventCreateWithFlags(&ev_join_, cudaEventDisableTiming) != cudaSuccess) { - err = "verify: event create failed"; - return false; - } - // Check whether 100% of experts across [lb_, le_) are resident in this stage's VRAM cache. - // When true, every layer plans on device and writes directly into parts_ without any CPU doorbells, - // wait_flag_ge spins, PCIe empty launches, or moe_hit_add copies. - all_resident_ = false; - if (hits.h_res != nullptr && hits.d_res != nullptr && hits.cache_base != nullptr) { - const char* v_ar = std::getenv("STRATA_VERIFY_ALL_RESIDENT"); - if (v_ar == nullptr || std::atoi(v_ar) != 0) { - bool all_ok = true; - for (int64_t l = lb_; l < le_ && all_ok; ++l) { - for (int64_t e = 0; e < g.n_expert; ++e) { - if (hits.h_res[l * g.n_expert + e] < 0) { - all_ok = false; - break; - } - } - } - all_resident_ = all_ok; - } - } - // E-6: a layer whose routed experts are all resident is planned on the device (STRATA_VERIFY_DEVICE_PLAN=1: on; - // exact, but neutral on RIBPC 1-2 GPUs: off by default) - { - const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN"); - device_plan_ = !all_resident_ && (v != nullptr && std::atoi(v) != 0); - } - if (all_resident_ || device_plan_) { - bool ok2 = true; - if (device_plan_) - ok2 = cudaMalloc((void**) &skip_, 64) == cudaSuccess && cudaMemset(skip_, 0, 64) == cudaSuccess; - if (ok2 && hits.slot_off != nullptr && hits.n_slots > 0) { - ok2 = cudaMalloc((void**) &slot_off_d_, (size_t) hits.n_slots * sizeof(unsigned long long)) == cudaSuccess && - cudaMemcpy(slot_off_d_, hits.slot_off, (size_t) hits.n_slots * sizeof(unsigned long long), - cudaMemcpyHostToDevice) == cudaSuccess; - } - if (!ok2) { cudaGetLastError(); all_resident_ = false; device_plan_ = false; } - } - std::fprintf(stderr, "strata verify: window up to %d tokens, %.1f MiB of device buffers%s\n", max_t, - (double) count.used / 1048576.0, - all_resident_ ? " (100% VRAM resident: zero-doorbell graph)" : ""); - return true; -} - -const float* Verifier::final_R(int t) const { return R_ + (size_t) t * (size_t) (g_->hc * g_->n_embd); } - -// ================================ THE WINDOW, AS CAPTURED ================================ -// -// Plan v0.3 P6 (split window): with `groups_ == 2` the window's tokens are cut into two groups A = [0, T/2 up) and -// B = the rest, and the stream is ordered -// -// pre(0,A) pre(0,B) | post(0,A) pre(1,A) | post(0,B) pre(1,B) | post(1,A) pre(2,A) | ... -// -// so the CPU computes A's experts of layer l while the GPU runs B's mixer and router of layer l, and B's experts -// while the GPU combines A and runs A's layer l+1. B's mixer only needs A's mixer of the same layer (K/V, GDN -// state), never A's experts, so nothing waits that did not wait before. Every token's arithmetic is unchanged. -bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { - using namespace strata::kernels; - const ModelGeometry& g = *g_; - const WeightTable& wt = *wt_; - SessionState& ss = *ss_; - const int64_t N = g.n_embd, HC = g.hc, K = ss.k, C = g.ssm_conv_channels, ZV = g.ssm_value_dim; - const int64_t HV = g.ssm_v_heads, HK = g.ssm_k_heads, NH = g.n_head, HD = g.head_dim, NKV = g.n_head_kv; - const int64_t IQ = g.idx_q_heads, ID = g.idx_key_dim, NE = g.n_expert, MT = max_t_; - const QsaShapes s = shapes_of(g); - const GrShapes gs{g.n_embd, g.hc, g.hc_lr}; - 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); - const int64_t HS = (int64_t) NG_HIST * NG_HC_DIM; - const int64_t TS = (s.idx_block - 1) * ID; - const bool ple_on = ss.ple.ready() && ple_stage(); - if (HC == 1 && ple_on) { - err = "verify: the plain block (hc = 1) has no per-layer embedding, but the session's PLE is wired"; - return false; - } - const float eps = (float) g.rms_eps; - auto Rt = [&](int t) { return R_ + (size_t) t * HC * N; }; // at hc = 1 the rows are contiguous: Rt(tb) spans n rows - // hc = 1: the plain block's F32 norm weights (layer.hpp, "the plain block"), checked as layer.cpp checks them - auto plain_w = [&](const LayerView& v, const char* suffix) -> const float* { - const WeightRef* w = need(v, suffix, err); - if (w == nullptr) return nullptr; - if (w->kind != WeightKind::F32 || w->elements != N || w->data == nullptr) { - err = v.name(suffix) + " is engine form " + std::to_string((int) w->kind) + " of " + - std::to_string(w->elements) + " elements; the plain block reads F32 x " + std::to_string(N); - return nullptr; - } - return (const float*) w->data; - }; - 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) { - if (prof_on_ && grp == 0) gpu_stamp(prof_, (int) (l * kProfPer + i), cs); - if (trace_m_ != nullptr) gpu_stamp(trace_m_, (int) ((l * kProfPer + i) * 2 + grp), cs); // #649 - }; - const int tb_[2] = {0, (T + 1) / 2}, te_[2] = {G == 2 ? (T + 1) / 2 : T, T}; - if (!batch_rec_) groups_[T] = G; - const int64_t nQall = g.n_qsa_layers(); - // a batch window: row t is slot t, whose state lives in its own session - auto slot_ss = [&](int t) -> SessionState& { return batch_rec_ ? *slots_[(size_t) brow_[t]] : ss; }; - const int hrow0 = batch_rec_ ? row_base_ : 0; // a slot group's own hand-off rows - - // ---- the window's inputs, from mapped staging - copy_i32_from_mapped(tok_, m_tok_, T, cs); - copy_i32_from_mapped(step_, m_step_, (int64_t) T * kStepCount, cs); - copy_i32_from_mapped(pos_, m_pos_, (int64_t) MT * (NH + NKV + IQ), cs); - // per-ROW positions of the K rows [t][NKV] and the indexer query rows [t][IQ] (for batched RoPE) - const int32_t* pos_k = pos_ + MT * NH; - const int32_t* pos_i = pos_ + MT * (NH + NKV); - - // ---- the embeddings, broadcast to the hc streams - or, in a later stage of a layer split, the previous stage's - // residual, pending write and inject (see set_stage) - const int64_t HB = Verifier::handoff_floats(g); - if (lb_ > 0) { - const float* hin = hand_in_ + (size_t) hrow0 * HB; // the group's rows: [R][bo][inj] contiguous - copy_from_mapped(R_, hin, (int64_t) T * HC * N, cs); - copy_from_mapped(bo_, hin + (size_t) T * HC * N, (int64_t) T * N, cs); - copy_from_mapped(inj2_, hin + (size_t) T * (HC + 1) * N, (int64_t) T * HC, cs); - } else if (const NativeEmbed* ne = native_embed()) { // plan v0.3 P6: the GGUF-form table - ne->gather_dev(tok_, T, emb_, cs); - broadcast_streams(emb_, R_, N, (int) HC, T, cs); - } else { - const WeightRef* w = wt.find("token_embd.weight"); - if (w == nullptr || w->codebook_iq4nl || (w->code_bits != 2 && w->code_bits != 4 && w->code_bits != 8)) { - err = "verify: token_embd.weight is missing or not an S2/S4/S8 tensor"; - return false; - } - const auto* codes = (const uint8_t*) w->data; - const auto* scales = (const float*) (codes + w->codes_bytes); - const auto* offsets = w->has_offset ? (const float*) (codes + w->codes_bytes + w->scales_bytes) : nullptr; - const uint64_t row_codes = (uint64_t) (w->ne0 / (8 / w->code_bits)); - const uint64_t row_groups = (uint64_t) (w->ne0 / w->group_elems); - embedding_gather_dev(codes, scales, offsets, tok_, T, w->ne0, w->code_bits, w->code_bias, w->group_elems, - row_codes, row_groups, emb_, cs); - broadcast_streams(emb_, R_, N, (int) HC, T, cs); - } - - // per-layer state indices (GDN and QSA layers are numbered separately) - std::vector gdn_idx((size_t) g.n_layers, -1), qsa_idx((size_t) g.n_layers, -1); - { - int64_t qi = 0, gi = 0; - for (int64_t l = 0; l < g.n_layers; ++l) { - if (is_qsa_layer(g, l)) qsa_idx[(size_t) l] = qi++; - else gdn_idx[(size_t) l] = gi++; - } - } - - // ---------------------------------------------------------------- pre(l, group): up to the ring - auto pre = [&](int64_t l, int grp) -> bool { - const int tb = tb_[grp], te = te_[grp], n = te - tb; - stamp(l, 0, grp); - const LayerView v(wt, l); - const char* pfx[2] = {"hc_attn_", "hc_ffn_"}; - const WeightRef *wn[2] = {}, *wd[2] = {}, *wu[2] = {}, *wi[2] = {}; - const float *w_attn = nullptr, *w_post = nullptr; // hc = 1: the plain block's two norms - if (HC == 1) { - w_attn = plain_w(v, "attn_norm.weight"); - if (w_attn == nullptr) return false; - w_post = plain_w(v, "post_attention_norm.weight"); - if (w_post == nullptr) return false; - } else - 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); - wu[h] = need(v, (std::string(pfx[h]) + "up.weight").c_str(), err); - wi[h] = need(v, (std::string(pfx[h]) + "inject.weight").c_str(), err); - if (!wn[h] || !wd[h] || !wu[h] || !wi[h]) return false; - } - // the previous layer's FFN write, folded into this layer's first read (a control vector after it has - // already applied it); the plain block has no pending write (its residual adds are applied in place) - bool pending = HC > 1 && l > 0 && !cvec().covers(l - 1); - if (l == 1 && ple_on) { - if (grp == 0) { - if (all_resident_) wait_flag_ge(m_flag_, 1, cs); - copy_from_mapped(ple_, m_ple_, (int64_t) T * N, cs); - } - float* normalized = (float*) ((uint8_t*) ss.ple.scratch + ple_block_scratch_bytes()); - static const bool ple_batch_env = [] { - const char* e = std::getenv("STRATA_PLE_BATCH"); - return !e || e[0] != '0'; - }(); - const bool ple_batch_kv = ple_batch_env && dec_batch && n > 1 && ss.ple.w.key_bf16 != nullptr && - ss.ple.w.value_bf16 != nullptr && ple_native_bf16_enabled() && - ple_native_postops_enabled(); - if (ple_batch_kv) { - try { - bf16_gemv_fp32_mmvf_multi(ple_ + (size_t) tb * N, N, ss.ple.w.key_bf16, - xn_ + (size_t) tb * HC * N, HC * N, N, HC * N, n, cs); - bf16_gemv_fp32_mmvf_multi(ple_ + (size_t) tb * N, N, ss.ple.w.value_bf16, - z_ + (size_t) tb * N, N, N, N, n, cs); - } catch (const std::exception& e) { - err = std::string("verify PLE multi: ") + e.what(); - return false; - } - } - for (int t = tb; t < te; ++t) { - gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs); - PleOut po; - po.normalized = normalized; - po.result = Rt(t); - float* hist = batch_rec_ ? slot_ss(t).ple_hist : ss.ple.hist; // the row's own history - try { - if (ple_batch_kv) { - ple_block_projected(xn_ + (size_t) t * HC * N, z_ + (size_t) t * N, Rt(t), hist, - ss.ple.w, po, ss.ple.scratch, cs); - } else { - ple_block(ple_ + t * N, Rt(t), hist, ss.ple.w, po, ss.ple.scratch, cs); - } - ple_history_advance(hist, normalized, cs); - } catch (const std::exception& e) { - err = std::string("verify PLE: ") + e.what(); - return false; - } - copy_from_mapped(hist_snap_ + (size_t) t * HS, hist, HS, cs); - } - pending = false; - } - auto gr_read_group = [&](int half, bool apply, float* inj_prev, float* inj_out) { - FusedGrArgs fa[kFusedGrMaxT]; - for (int t = tb; t < te; ++t) { - FusedGrArgs& a = fa[t - tb]; - a.R = Rt(t); a.R_out = Rt(t); a.apply = apply; - a.bo_prev = bo_ + t * N; a.inj_prev = inj_prev + t * HC; - a.w_norm = (const float*) wn[half]->data; a.w_down = (const uint16_t*) wd[half]->data; - a.w_up = (const uint16_t*) wu[half]->data; a.w_inject = (const uint16_t*) wi[half]->data; - a.eps = EPS; a.lo = lo_ + t * g.hc_lr; a.rs = rs_ + t * HC; - a.inject_out = inj_out + t * HC; a.mixed = mixed_ + t * N; - } - fused_gr_read_multi(fa, n, xn_ + (size_t) tb * HC * N, cs, (prof_on_ && grp == 0) ? prof_ : nullptr, - (int) (l * kProfPer + (half == 0 ? 27 : 30))); - }; - float* xm = mixed_ + tb * N; - try { - // x = rms_norm(R) * attn_norm over the group's n rows (`attn_norm-N`), or the GR read - if (HC == 1) plain_norm_rows(Rt(tb), w_attn, xm, N, eps, n, cs); - else gr_read_group(0, pending, inj2_, inj_); - } catch (const std::exception& e) { - err = "verify layer " + std::to_string(l) + " attn_norm: " + e.what(); - return false; - } - stamp(l, 1, grp); - try { - if (!is_qsa_layer(g, l)) { - // ======================= GDN ======================= - const WeightRef *wqkv = need(v, "attn_qkv.weight", err), *wg = need(v, "attn_gate.weight", err), - *wout = need(v, "ssm_out.weight", err), *wa = need(v, "ssm_alpha.weight", err), - *wb = need(v, "ssm_beta.weight", err), *wc = need(v, "ssm_conv1d.weight", err), - *wnm = need(v, "ssm_norm.weight", err), *wdt = need(v, "ssm_dt.bias", err), - *wsa = need(v, "ssm_a", err); - if (!wqkv || !wg || !wout || !wa || !wb || !wc || !wnm || !wdt || !wsa) return false; - if (!native_of(wqkv, v.name("attn_qkv.weight"), err) || !native_of(wg, v.name("attn_gate.weight"), err) || - !native_of(wout, v.name("ssm_out.weight"), err)) - return false; - const int64_t gi = gdn_idx[(size_t) l]; - float* state = ss.gdn_state + (size_t) (gi - ss.gdn_ord0) * gdn_floats; - float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; - float* qkv = qkv_L_ + (size_t) gi * MT * C; - float* hb = h_L_ + (size_t) gi * MT * C; - float* gate = gate_L_ + (size_t) gi * MT * HV; - float* beta = beta_L_ + (size_t) gi * MT * HV; - native_quantize_q8_1(xm, xq_, (int) N, n, cs); - native_mmvq(wqkv->native_type, wqkv->native_data, xq_, qkv + (size_t) tb * C, (int) N, (int) C, n, cs); - stamp(l, 2, grp); - if (batch_rec_) { // each row from its own slot's conv history, one row each - for (int t = tb; t < te; ++t) { - SessionState& sx = slot_ss(t); - const float* cx = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats + - (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; - gdn_conv_l2_multi(cx, qkv + (size_t) t * C, (const float*) wc->data, hb + (size_t) t * C, (int) C, - (int) (2 * HK), EPS, 1, cs, 0); - } - } else - gdn_conv_l2_multi(conv, qkv, (const float*) wc->data, hb, (int) C, (int) (2 * HK), EPS, n, cs, tb); - stamp(l, 3, grp); - gdn_ab_multi(xm, (const uint16_t*) wa->data, (const uint16_t*) wb->data, (const float*) wdt->data, - (const float*) wsa->data, gate + (size_t) tb * HV, beta + (size_t) tb * HV, (int) N, (int) HV, - n, cs); - stamp(l, 4, grp); - native_mmvq(wg->native_type, wg->native_data, xq_, z_ + (size_t) tb * ZV, (int) N, (int) ZV, n, cs); - stamp(l, 5, grp); - // the recurrence from the untouched state over tokens [0, te); outputs only for this group's - if (batch_rec_) { // each row's recurrence from its own slot's state, one token - for (int t = tb; t < te; ++t) { - SessionState& sx = slot_ss(t); - float* stx = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats; - gdn_step_norm_multi(stx, hb + (size_t) t * C, (int) C, gate + (size_t) t * HV, beta + (size_t) t * HV, - z_ + (size_t) t * ZV, (const float*) wnm->data, EPS, g.gdn_gate(), - y_ + (size_t) t * ZV, (int) HK, (int) HV, 1, nullptr, cs, 0); - } - } else - gdn_step_norm_multi(state, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, g.gdn_gate(), y_, - (int) HK, (int) HV, te, nullptr, cs, tb); - 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); - } else { - // ======================= QSA ======================= - const int64_t qi = qsa_idx[(size_t) l]; - const QsaState& st = ss.qsa_states[qi]; - // Qwen3.6 (3.3): dense attention - no indexer tensors, no raw key, no scores, no top-k; the split-K - // kernel reads every cell (a null ids is the identity) with the width n_kv from each row's step - const bool has_idx = g.has_indexer(); - const WeightRef *wq = need(v, "attn_q.weight", err), - *wk = need(v, "attn_k.weight", err), *wv = need(v, "attn_v.weight", err), - *wo = need(v, "attn_output.weight", err), - *wqn = need(v, "attn_q_norm.weight", err), *wkn = need(v, "attn_k_norm.weight", err); - const WeightRef *wik = has_idx ? need(v, "indexer.k_proj.weight", err) : nullptr, - *wiq = has_idx ? need(v, "indexer.q_proj.weight", err) : nullptr, - *wiqn = has_idx ? need(v, "indexer.q_norm.weight", err) : nullptr, - *wikn = has_idx ? need(v, "indexer.k_norm.weight", err) : nullptr; - if (!wq || !wk || !wv || !wo || !wqn || !wkn || (has_idx && (!wik || !wiq || !wiqn || !wikn))) return false; - 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; - auto norm_rope = [&](float* data, const WeightRef* norm, int rows, int cols, const int32_t* pos) { - if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, EPS, cs); - else rms_norm_weighted(data, (const float*) norm->data, rows, cols, EPS, cs); - if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), pos, cs); - else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, pos, cs); - }; - float* idx_raw = idx_raw_L_ + (size_t) qi * MT * ID; - // the per-token GEMVs / norms / RoPEs / copies of this layer as one launch over the - // window's rows each - row-wise identical arithmetic (STRATA_DEC_BATCH=0: token by token) - const bool qb = dec_batch && n > 1 && native_qsa_enabled() && native_rope_enabled() && !st.kv_q4; - native_quantize_q8_1(xm, xq_, (int) N, n, cs); - if (!has_idx) {} - else if (qb) bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wik->data, idx_raw + tb * ID, ID, N, ID, n, cs); - 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); - native_mmvq(wk->native_type, wk->native_data, xq_, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs); - native_mmvq(wv->native_type, wv->native_data, xq_, vcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs); - if (qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV); - else for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH); - if (st.kv_rot) { // K and V rotated before they are stored (kv_q4.hpp) - fwht256_inplace_cuda(kcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); - fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); - } else if (st.kv_hybrid) { // K8V4: only V is rotated - fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); - } - stamp(l, 8, grp); - if (!has_idx) {} - else if (batch_rec_) { // every slot's indexer tail, restored by its commit - 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); - } else - if (grp == 0) copy_from_mapped(tail_snap_ + (size_t) qi * TS, st.idx_tail, TS, cs); - for (int t = tb; t < te; ++t) { - const QsaState& st = slot_ss(t).qsa_states[qi]; // the row's own K/V (ss's outside a batch) - const int32_t* step_t = step_ + t * kStepCount; - if (st.kv_hybrid) { // K8V4: the unused half's lanes folded onto the used pool (layer.cpp) - kv_append_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, step_t, - kcur_ + t * NKV * HD, kcur_ + t * NKV * HD, s, cs, nullptr); - kv_append_q4_step(st.v_q4, st.v_q4, st.page_table, step_t, vcur_ + t * NKV * HD, - vcur_ + t * NKV * HD, s, cs, nullptr); - } else if (st.kv_q4) - kv_append_q4_step(st.k_q4, st.v_q4, st.page_table, step_t, 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, - 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, 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}; - native_qsa_indexer_append(idx_raw + t * ID, step_ + t * kStepCount + kStepPos, 0, - (const float*) wikn->data, EPS, ib, s, sx.max_cells, - rope_scaling(), cs); - } - stamp(l, 9, grp); - native_mmvq(wq->native_type, wq->native_data, xq_, qfull_ + tb * NH * 2 * HD, (int) N, (int) (NH * 2 * HD), - n, cs); - if (qb) { - if (cudaMemcpy2DAsync(qcur_ + tb * NH * HD, (size_t) HD * 4, qfull_ + tb * NH * 2 * HD, (size_t) HD * 2 * 4, - (size_t) HD * 4, (size_t) (n * NH), cudaMemcpyDeviceToDevice, cs) != cudaSuccess) { - err = "verify: the q/gate split failed"; - return false; - } - 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); // = - 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; - if (cudaMemcpy2DAsync(qc, (size_t) HD * 4, qfull_ + t * NH * 2 * HD, (size_t) HD * 2 * 4, - (size_t) HD * 4, (size_t) NH, cudaMemcpyDeviceToDevice, cs) != cudaSuccess) { - err = "verify: the q/gate split failed"; - return false; - } - norm_rope(qc, wqn, (int) NH, (int) HD, pos_ + t * NH); - if (st.kv_rot) fwht256_inplace_cuda(qc, NH, cs); // = - } - 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); - norm_rope(qx, wiqn, (int) IQ, (int) ID, pos_ + t * NH); - } - } - 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]; - qsa_block_scores(sx.idx_pooled, sx.idx_dead, qidx_ + t * IQ * ID, step_ + t * kStepCount, 1, - max_blocks_, s, scores_ + (size_t) t * max_blocks_, cs); - qsa_block_topk(scores_ + (size_t) t * max_blocks_, step_ + t * kStepCount, 1, max_blocks_, cap_, s, - sel_ + (size_t) t * cap_, cs); - qsa_kv_resolve(sx, *g_, sel_ + (size_t) t * cap_, step_ + t * kStepCount, 1, cap_, cs); - const QsaAttnPools px = qsa_attn_pools(sx); - qsa_decode_attn_batch(qcur_ + t * NH * HD, px, sel_ + (size_t) t * cap_, step_ + t * kStepCount, - cap_, s, attn_scratch_ + (size_t) t * attn_scratch_floats_, - attn_ + t * NH * HD, 1, cs); - } - } else { - qsa_block_scores(st.idx_pooled, st.idx_dead, qidx_ + tb * IQ * ID, step_ + tb * kStepCount, n, max_blocks_, - s, scores_ + (size_t) tb * max_blocks_, cs); - qsa_block_topk(scores_ + (size_t) tb * max_blocks_, step_ + tb * kStepCount, n, max_blocks_, cap_, s, - sel_ + (size_t) tb * cap_, cs); - stamp(l, 11, grp); - // KV streaming: the n selections' blocks resident (device-side, inside the graph) - qsa_kv_resolve(st, *g_, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, n, cap_, cs); - stamp(l, 12, grp); - const QsaAttnPools pools = qsa_attn_pools(st); - qsa_decode_attn_batch(qcur_ + tb * NH * HD, pools, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, cap_, - s, attn_scratch_ + (size_t) tb * attn_scratch_floats_, attn_ + tb * NH * HD, n, cs); - } - stamp(l, 13, grp); - if (st.kv_rot || st.kv_hybrid) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = H - if (qb) native_qsa_gate_apply(attn_ + tb * NH * HD, qfull_ + tb * NH * 2 * HD, attn32_ + tb * NH * HD, - (int) (n * NH), (int) HD, cs); - else - for (int t = tb; t < te; ++t) { - if (native_qsa_enabled()) - native_qsa_gate_apply(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, attn32_ + t * NH * HD, - (int) NH, (int) HD, cs); - else - qsa_gate_apply_f32(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, s, attn32_ + t * NH * HD, cs); - } - stamp(l, 14, grp); - native_quantize_q8_1(attn32_ + tb * NH * HD, xq_, (int) (NH * HD), n, cs); - native_mmvq(wo->native_type, wo->native_data, xq_, bo_ + tb * N, (int) (NH * HD), (int) N, n, cs); - } - } catch (const std::exception& e) { - err = "verify layer " + std::to_string(l) + ": " + e.what(); - return false; - } - stamp(l, 16, grp); - try { - if (HC == 1) { // R += mixer out (`attn_residual-N`), then x = rms_norm(R) * post_attention_norm - plain_residual_rows(Rt(tb), bo_ + tb * N, N, n, cs); - plain_norm_rows(Rt(tb), w_post, xm, N, eps, n, cs); - } else gr_read_group(1, true, inj_, inj2_); - } catch (const std::exception& e) { - err = "verify layer " + std::to_string(l) + " post_attention_norm: " + e.what(); - return false; - } - static const bool sh_stream_env = [] { - const char* e = std::getenv("STRATA_SH_STREAM"); - return !e || e[0] != '0'; - }(); - const bool sh_fork = sh_stream_env && !prof_on_ && sh_cs_ != nullptr && ev_fork_ != nullptr && ev_join_ != nullptr; - cudaStream_t sh_stream = sh_fork ? sh_cs_ : cs; - if (sh_fork) { - cudaEventRecord(ev_fork_, cs); - cudaStreamWaitEvent(sh_cs_, ev_fork_, 0); - } - // the window's rows routed in 2 launches (one router GEMV reading the weight once, one - // top-10) instead of 2 per token; every row's arithmetic is the single-token call's (STRATA_DEC_BATCH=0: old) - const WeightRef* w_router = v.get("ffn_gate_inp.weight"); - if (dec_batch && n > 1 && w_router != nullptr && native_router_enabled() && NE == 512 && K == 10) { - try { - bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) w_router->data, logits_ + tb * NE, NE, N, - NE, n, cs); - native_router_top10_multi(logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, n, cs); - } catch (const std::exception& e) { err = "verify router: " + std::string(e.what()); return false; } -#if defined(STRATA_HIP_GFX906) - } else if (dec_batch) { - // gfx906: the Coder's 256-expert router (the native router is 512 x 10 only) for the whole window in one - // multi-column BF16 projection and one top-k, bitwise the per-token calls (route_window_parity); ~3 ms - // of a ~55 ms verify window on 2x MI50. STRATA_ROUTE_PER_TOKEN=1: the per-token calls. - if (!moe_route_window(wt, g, l, K, ss.moe, mixed_ + tb * N, logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, n, - cs, err)) - return false; -#endif - } else - for (int t = tb; t < te; ++t) { - MoEBuffers mb = ss.moe; - mb.logits = logits_ + t * NE; mb.ids = ids_ + t * K; mb.weights = w_ + t * K; - if (!moe_route(wt, g, l, K, mb, mixed_ + t * N, cs, err, nullptr)) return false; - } - if (all_resident_) { - resident_plan(ids_ + tb * K, n * (int) K, (int) K, hits_.d_res + l * g.n_expert, (int) g.n_expert, - hits_.cache_base, slot_off_d_, (long long) hits_.blob, - plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, nullptr, 0, cs); - } else { - if (device_plan_) // E-6: every routed expert resident: this group's plan without the host - resident_plan(ids_ + tb * K, n * (int) K, (int) K, hits_.d_res + l * g.n_expert, (int) g.n_expert, - hits_.cache_base, slot_off_d_, (long long) hits_.blob, - plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, skip_ + grp, - (uint32_t) ((l - lb_) * G + grp + 1), cs); -#if defined(STRATA_USE_HIP) - if (g_doorbell_store) // #649 A/B: the step's ring stored, not incremented over PCIe - doorbell_publish_value(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N, - m_ids_ + tb * K, m_w_ + tb * K, m_seq_, (uint32_t) ((l - lb_) * G + grp + 1), cs); - else -#endif - if (remote_opt_) // #578: the helper GPUs reduce with the routing weights - publish them - doorbell_publish(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N, - m_ids_ + tb * K, m_w_ + tb * K, m_seq_, cs); - else { - const int32_t* layer_res = hits_.d_res != nullptr ? (hits_.d_res + l * g.n_expert) : nullptr; - doorbell_publish_res(xm, ids_ + tb * K, layer_res, (int) g.n_expert, (int64_t) n * N, (int64_t) n * K, - m_x_ + tb * N, m_ids_ + tb * K, m_seq_, cs); - } - } - stamp(l, 17, grp); - { - const WeightRef *wgi = need(v, "ffn_gate_inp_shexp.weight", err), *wsg = need(v, "ffn_gate_shexp.weight", err), - *wsu = need(v, "ffn_up_shexp.weight", err), *wsd = need(v, "ffn_down_shexp.weight", err); - if (!wgi || !wsg || !wsu || !wsd) return false; - if (!native_of(wsg, v.name("ffn_gate_shexp.weight"), err) || !native_of(wsu, v.name("ffn_up_shexp.weight"), err) || - !native_of(wsd, v.name("ffn_down_shexp.weight"), err)) - return false; - NativeSharedWeights nsw; - nsw.gate_type = wsg->native_type; nsw.gate_data = wsg->native_data; - nsw.up_type = wsu->native_type; nsw.up_data = wsu->native_data; - nsw.down_type = wsd->native_type; nsw.down_data = wsd->native_data; - nsw.q8_1 = sh_fork ? sh_xq_ : xq_; - if (!shared_expert_native_bf16_enabled()) { - if (dec_batch) f32_to_bf16_bulk(mixed_ + tb * N, sh_bf16_ + tb * N, (int64_t) n * N, sh_stream); // contiguous rows - else for (int t = tb; t < te; ++t) f32_to_bf16_bulk(mixed_ + t * N, sh_bf16_ + t * N, N, sh_stream); - } - try { - shared_expert_multi(n, xm, sh_bf16_ + tb * N, nsw, (const uint16_t*) wgi->data, sh_gate_ + (size_t) tb * g.n_ff, - sh_up_ + (size_t) tb * g.n_ff, sh_g_ + tb, shared_ + tb * N, N, g.n_ff, sh_stream); - } catch (const std::exception& e) { - err = std::string("verify shared expert: ") + e.what(); - return false; - } - if (sh_fork) cudaEventRecord(ev_join_, sh_cs_); - } - if (strata::kernels::cpu::expert_layout().native) - quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs); - else - quantize_q8_0_scaled(xm, hit_xq_ + (size_t) tb * (N / 32) * 34, hit_xs_ + (size_t) tb * (N / 32), (int64_t) n * N, cs); - stamp(l, 18, grp); - return true; - }; - - // ---------------------------------------------------------------- post(l, group): experts, combine - static const bool fuse_head_gr_env = [] { - const char* e = std::getenv("STRATA_FUSE_HEAD_GR"); - return e && e[0] == '1'; - }(); - const bool fuse_head_gr = fuse_head_gr_env && HC > 1 && (le_ == g.n_layers) && (head_ != nullptr && head_->loaded()) && - !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; - const uint32_t ring = (uint32_t) ((l - lb_) * G + grp + 1); - const int64_t cap = (int64_t) n * K, capx = (int64_t) max_t_ * K; - int32_t* pl = plan_ + (size_t) grp * (size_t) (plan_i32_ + 16); - const int32_t* p_counts = pl; - const int32_t* p_start = pl + 4; - const int32_t* p_dst = p_start + capx + 1; - const int32_t* p_tok = p_dst + capx; - const int64_t ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll; - const unsigned long long* p_ptr = (const unsigned long long*) (pl + ptr_off); - const unsigned long long* p_ptr2 = p_ptr + capx; - const int32_t* p_start2 = pl + ptr_off + 4 * capx; - float* hit_out = hit_out_ + (size_t) tb * K * N; - float* parts_out = parts_ + (size_t) tb * K * N; - const auto& lay = strata::kernels::cpu::expert_layout(); - // plan v0.3 P6: the VRAM groups now; the PCIe groups once the copy engine has landed them in staging. - // `gy`: the native launch's groups side by side (0: cap, one block row per possible group). - auto grouped = [&](const unsigned long long* gp, const int32_t* gs, const int32_t* gn, int64_t gy, float* dst_buf) { - if (lay.native) { - // the layer's GGUF formats (i-quant gate/up, Q2_0 / IQ4_NL down) - const auto& f = lay.fmt[(size_t) l]; - const NativeExpertLayout L = native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff); - native_expert_grouped(L, gp, gs, gn, p_dst, p_tok, cap, cap, - nat_xq_ + (size_t) tb * (N / 32) * 36, hit_scratch_, dst_buf, cs, gy); - } else { - moe_grouped_s2(gp, gs, gn, p_dst, p_tok, cap, cap, hit_xq_ + (size_t) tb * (N / 32) * 34, - hit_xs_ + (size_t) tb * (N / 32), hit_scratch_, dst_buf, cs); - } - }; - if (all_resident_) { - stamp(l, 19, grp); - grouped(p_ptr, p_start, p_counts, 0, parts_out); - stamp(l, 20, grp); - } else { - if (device_plan_) { // E-6: skipped when the device planned this group (all its experts resident) - wait_flag_ge_or(m_flagA_, ring, skip_ + grp, cs); - copy_i32_from_mapped_unless(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, skip_ + grp, ring, cs); - } else { - wait_flag_ge(m_flagA_, ring, cs); // the pool published this group's GPU plan - copy_i32_from_mapped(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, cs); - } - stamp(l, 19, grp); - grouped(p_ptr, p_start, p_counts, 0, hit_out); - stamp(l, 20, grp); - if (device_plan_) wait_flag_ge_or(m_flagB_, ring, skip_ + grp, cs); - else wait_flag_ge(m_flagB_, ring, cs); // the PCIe share is in staging (DMA) or mapped - if (sink_.pcie_mode == 2) { // stage it with a copy kernel, then point at staging - const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs; - uint8_t* stage = staging_ + (size_t) (grp * per) * lay.max_blob; - fetch_blobs(p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), (int) per, cs); - rebase_ptrs((unsigned long long*) p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), cs); - } - stamp(l, 21, grp); - // the PCIe share is pcie_frac of the misses: a few groups when the cache is cold, usually none (always none at - // pcie_frac 0), so its launch is kPcieGroupRows block rows striding over the groups, not cap of them - grouped(p_ptr2, p_start2, p_counts + 2, kPcieGroupRows, hit_out); - stamp(l, 22, grp); - if (device_plan_) { // no CPU share when the device planned the group: its rows are zeros - wait_flag_ge_or(m_flag_, ring, skip_ + grp, cs); - copy_or_zero_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (long long) n * K * N, - skip_ + grp, ring, cs); - } else { - wait_flag_ge(m_flag_, ring, cs); // the CPU's share is in the mapped rows - stamp(l, 23, grp); - if (remote_opt_) // #578: the helper's rows come back reduced; skip them as well - remote_opt_->copy_rows(parts_out, m_ymiss_ + (size_t) tb * K * N, tb, n, p_dst, p_counts + 1, cs); - else if (dec_batch) // only the CPU rows cross PCIe (p_dst[0, counts[1]) = the GPU's own rows) - copy_rows_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K, N, - p_dst, p_counts + 1, cs); - else - copy_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K * N, cs); - } - moe_hit_add(parts_out, hit_out, p_dst, p_counts + 1, cap, N, cs); - } - if (!prof_on_ && sh_cs_ != nullptr && ev_fork_ != nullptr && ev_join_ != nullptr) { - cudaStreamWaitEvent(cs, ev_join_, 0); - } - if (dec_batch && n > 1 && native_moe_combine_enabled()) { // one launch for the window's rows - try { - native_moe_combine_multi(parts_ + (size_t) tb * K * N, w_ + tb * K, shared_ + tb * N, bo_ + tb * N, N, K, n, cs); - } catch (const std::exception& e) { err = "verify combine: " + std::string(e.what()); return false; } - } else - for (int t = tb; t < te; ++t) { - MoEBuffers mb = ss.moe; - mb.weights = w_ + t * K; mb.shared = shared_ + t * N; - if (!moe_combine_parts(g, l, K, mb, parts_ + (size_t) t * K * N, bo_ + t * N, cs, err)) return false; - } - if (remote_opt_) remote_opt_->combine(bo_ + tb * N, y_dummy_ + tb * N, tb, n, - device_plan_ ? skip_ + grp : nullptr, ring, cs); - stamp(l, 24, grp); - if (HC == 1) { // R += ffn out (`l_out-N`): in place, every layer; then a control vector if one covers it - try { - plain_residual_rows(Rt(tb), bo_ + tb * N, N, n, cs); - if (cvec().covers(l)) cvec_apply(Rt(tb), l, n, N, nullptr, 0, nullptr, 0, false, cs); - } catch (const std::exception& e) { - err = "verify layer " + std::to_string(l) + " residual: " + e.what(); - return false; - } - } else if (l == g.n_layers - 1) { - if (!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); - } - } else if (cvec().covers(l)) { - cvec_apply(Rt(tb), l, n, HC * N, bo_ + tb * N, N, inj2_ + tb * HC, HC, true, cs); - } - return true; - }; - - for (int grp = 0; grp < G; ++grp) - if (!pre(lb_, grp)) return false; - for (int64_t l = lb_; l < le_; ++l) - for (int grp = 0; grp < G; ++grp) { - if (!post(l, grp)) return false; - if (l + 1 < le_ && !pre(l + 1, grp)) return false; - } - if (le_ < g.n_layers) { // a layer split's earlier stage: hand the residual on, no head - float* hout = hand_out_ + (size_t) hrow0 * HB; - copy_from_mapped(hout, R_, (int64_t) T * HC * N, cs); - copy_from_mapped(hout + (size_t) T * HC * N, bo_, (int64_t) T * N, cs); - copy_from_mapped(hout + (size_t) T * (HC + 1) * N, inj2_, (int64_t) T * HC, cs); - return true; - } - - // ---- the head, T columns, and the argmax of each - stamp(g.n_layers, 0, 0); - { - const WeightRef *hn = nullptr, *hd = nullptr, *hu = nullptr; - if (HC > 1) { - hn = wt.find("output_hc_norm.weight"); hd = wt.find("output_hc_down.weight"); hu = wt.find("output_hc_up.weight"); - if (!hn || !hd || !hu) { err = "verify: an output_hc_* weight is missing"; return false; } - } - if (HC == 1 && head_ != nullptr && head_->loaded()) { - // the plain head: `result_norm = rms_norm(R) * output_norm` for the T rows in one launch (row t is the - // single-token `lm_head_mix`); the canonical head below goes through `lm_head`, which branches the same way - const WeightRef* wn = wt.find("output_norm.weight"); - if (wn == nullptr) { err = "verify: output_norm.weight is missing (the plain block's head norm)"; return false; } - if (wn->kind != WeightKind::F32 || wn->elements != N || wn->data == nullptr) { - err = "verify: output_norm.weight is engine form " + std::to_string((int) wn->kind) + " of " + - std::to_string(wn->elements) + " elements; the plain head reads F32 x " + std::to_string(N); - return false; - } - try { plain_norm_rows(R_, (const float*) wn->data, head_mixed_, N, eps, T, cs); } - catch (const std::exception& e) { err = std::string("verify output_norm: ") + e.what(); return false; } - } else if (fuse_head_gr) { - FusedGrArgs fa[kFusedGrMaxT]; - for (int t = 0; t < T; ++t) { - FusedGrArgs& a = fa[t]; - a.R = Rt(t); a.R_out = Rt(t); a.apply = true; - a.bo_prev = bo_ + t * N; a.inj_prev = inj2_ + t * HC; - a.w_norm = (const float*) hn->data; - a.w_down = (const uint16_t*) hd->data; - a.w_up = (const uint16_t*) hu->data; - a.w_inject = nullptr; - a.eps = EPS; - a.lo = lo_ + t * g.hc_lr; - a.rs = rs_ + t * HC; - a.inject_out = head_inj_; - a.mixed = head_mixed_ + t * N; - } - fused_gr_read_multi(fa, T, xn_, cs); - } else { - for (int t = 0; t < T; ++t) { - BlockBuffers bb = ss.block; - bb.R = Rt(t); - bb.mixed = head_mixed_ + t * N; - if (head_ != nullptr && head_->loaded()) { - if (!lm_head_mix(wt, g, bb, cs, err)) return false; - } else if (!lm_head(wt, g, bb, head_logits_ + (size_t) t * n_vocab_, cs, err)) { - return false; - } - } - } - if (head_ != nullptr && head_->loaded()) { - try { - native_quantize_q8_1(head_mixed_, xq_, (int) N, T, cs); - native_mmvq(head_->type(), head_->weights(), xq_, head_logits_, (int) N, (int) n_vocab_, T, cs); - } catch (const std::exception& e) { - err = std::string("verify head: ") + e.what(); - return false; - } - } - // Greedy, the default, is recorded here as before (no extra launch or sync per window). A request that - // samples or penalizes is sampled again host-side after the replay (run()) with its own parameters and a - // fresh draw counter: a captured sampler would bake them in and replay the same draws forever. - SamplerParams sp; - sp.greedy = true; - sp.temperature = 0.0f; - sample_tokens(head_logits_, T, (int) n_vocab_, nullptr, 0, sp, m_out_, cs); - } - stamp(g.n_layers, 1, 0); - return true; -} - -std::string Verifier::profile_report() { - if (!prof_on_ || prof_windows_ == 0) return std::string(); - static const char* names[kProfPer] = {"-", "hc-read0", "q8+qkv/q-idx gemv", "conv", "ab", "z", "rec", "q8+kv-idx", - "k/v+norm-rope", "kv+idx append", "q+q-idx", "scores+topk", "kv-resolve", - "attention", "gate", "", "out-proj", "hc-read1+router", "shared+quant", - "waitA", "VRAM hits", "waitB", "PCIe grp", "waitCPU", "copy+combine", - "(gap)", "head", " hc0 norm", " hc0 down", " hc0 up", "", "", ""}; - std::string out; - char b[80]; - double total = 0; - for (int k = 0; k < 2; ++k) { - out += k == 0 ? " GDN layers:" : " | QSA layers:"; - for (int i = 0; i < kProfPer; ++i) { - if (prof_sum_[k][i] <= 0) continue; - total += prof_sum_[k][i]; - std::snprintf(b, sizeof b, " %s %.2f", names[i], prof_sum_[k][i] / 1e6 / (double) prof_windows_); - out += b; - } - } - std::snprintf(b, sizeof b, " | total %.2f ms/window over %lld windows", total / 1e6 / (double) prof_windows_, (long long) prof_windows_); - out += b; - for (auto& r : prof_sum_) for (double& d : r) d = 0; - prof_windows_ = 0; - return out; -} - -bool Verifier::capture(int T, std::string& err) { - if (exec_[T] != nullptr) return true; - if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { - err = "verify: begin capture failed"; - return false; - } - std::string rerr; - const bool ok = record_window(T, cs_, rerr); - cudaGraph_t graph = nullptr; - const cudaError_t ce = cudaStreamEndCapture(cs_, &graph); - if (!ok) { - if (graph) cudaGraphDestroy(graph); - err = rerr; - return false; - } - if (ce != cudaSuccess) { - err = std::string("verify: end capture: ") + cudaGetErrorString(ce); - return false; - } -#if !defined(STRATA_USE_HIP) // a CUDA debug listing (node types, kernel names) - if (std::getenv("STRATA_VERIFY_NODES") != nullptr) { // what the window graph holds - size_t nn = 0; - cudaGraphGetNodes(graph, nullptr, &nn); - std::vector nodes(nn); - cudaGraphGetNodes(graph, nodes.data(), &nn); - std::map kinds; - for (cudaGraphNode_t nd : nodes) { - cudaGraphNodeType ty; - cudaGraphNodeGetType(nd, &ty); - std::string name = "type" + std::to_string((int) ty); - if (ty == cudaGraphNodeTypeKernel) { - cudaKernelNodeParams kp{}; - if (cudaGraphKernelNodeGetParams(nd, &kp) == cudaSuccess) { -#if CUDART_VERSION >= 12030 // cudaFuncGetName arrived in CUDA 12.3 - const char* fn = nullptr; - if (cudaFuncGetName(&fn, kp.func) == cudaSuccess && fn) name = fn; -#endif - } - } else if (ty == cudaGraphNodeTypeMemcpy) name = "memcpy"; - else if (ty == cudaGraphNodeTypeMemset) name = "memset"; - ++kinds[name]; - } - std::vector> v; - for (auto& [k2, c] : kinds) v.push_back({c, k2}); - std::sort(v.rbegin(), v.rend()); - std::fprintf(stderr, "strata verify: the %d-token window graph has %zu nodes:", T, nn); - for (size_t i = 0; i < v.size() && i < 40; ++i) std::fprintf(stderr, " %d x %.60s;", v[i].first, v[i].second.c_str()); - std::fprintf(stderr, "\n"); - } -#endif - const cudaError_t ie = cudaGraphInstantiate(&exec_[T], graph, 0); - cudaGraphDestroy(graph); - if (ie != cudaSuccess) { - err = std::string("verify: instantiate: ") + cudaGetErrorString(ie); - return false; - } - const cudaError_t ue = cudaGraphUpload(exec_[T], cs_); - const cudaError_t us = cudaStreamSynchronize(cs_); - std::fprintf(stderr, "strata verify: captured the %d-token window (upload %s, sync %s)\n", T, - cudaGetErrorString(ue), cudaGetErrorString(us)); - return true; -} - -bool Verifier::capture_commit(std::string& err) { - if (commit_exec_ != nullptr) return true; - using namespace strata::kernels; - const ModelGeometry& g = *g_; - SessionState& ss = *ss_; - const QsaShapes s = shapes_of(g); - const int64_t C = g.ssm_conv_channels, HV = g.ssm_v_heads, ID = g.idx_key_dim, MT = max_t_; - 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); - const int64_t TS = (s.idx_block - 1) * ID; - const int64_t HS = (int64_t) NG_HIST * NG_HC_DIM; - if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { - err = "verify: begin commit capture failed"; - return false; - } - bool ok = true; - try { - copy_i32_from_mapped(commit_, m_commit_, 2 + MT, cs_); - int64_t qsa_index = 0, gdn_index = 0; - for (int64_t l = 0; l < lb_; ++l) (is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1; - for (int64_t l = lb_; l < le_ && ok; ++l) { - const LayerView v(*wt_, l); - if (!is_qsa_layer(g, l)) { - const WeightRef* wnm = need(v, "ssm_norm.weight", err); - if (!wnm) { ok = false; break; } - float* state = ss.gdn_state + (size_t) (gdn_index - ss.gdn_ord0) * gdn_floats; - float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; - const float* qkv = qkv_L_ + (size_t) gdn_index * MT * C; - gdn_conv_commit(conv, qkv, (int) C, commit_, cs_); - gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C, (int) C, gate_L_ + (size_t) gdn_index * MT * HV, - beta_L_ + (size_t) gdn_index * MT * HV, z_, (const float*) wnm->data, EPS, g.gdn_gate(), - y_dummy_, (int) g.ssm_k_heads, (int) HV, (int) MT, commit_, cs_, (int) MT); - ++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); - if (!wikn) { ok = false; break; } - copy_from_mapped(st.idx_tail, tail_snap_ + (size_t) qsa_index * TS, TS, cs_); - const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; - for (int64_t t = 0; t < MT; ++t) - native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + t) * ID, commit_ + 2 + t, 0, - (const float*) wikn->data, EPS, ib, s, st.max_cells, - rope_scaling(), cs_); - ++qsa_index; - } - } - if (ok && ss.ple.ready() && ple_stage()) copy_indexed(ss.ple.hist, hist_snap_, HS, commit_ + 1, HS, cs_); - } catch (const std::exception& e) { - err = std::string("verify commit: ") + e.what(); - ok = false; - } - cudaGraph_t graph = nullptr; - const cudaError_t ce = cudaStreamEndCapture(cs_, &graph); - if (!ok) { - if (graph) cudaGraphDestroy(graph); - return false; - } - if (ce != cudaSuccess || cudaGraphInstantiate(&commit_exec_, graph, 0) != cudaSuccess) { - if (graph) cudaGraphDestroy(graph); - err = std::string("verify: commit capture: ") + cudaGetErrorString(ce); - return false; - } - cudaGraphDestroy(graph); - return true; -} - -void Verifier::stage_inputs(int T, const int32_t* tokens, int64_t pos0) { - using namespace strata::kernels; - const ModelGeometry& g = *g_; - const QsaShapes s = shapes_of(g); - int32_t* const pk = h_pos_ + (size_t) max_t_ * g.n_head; - int32_t* const pi = pk + (size_t) max_t_ * g.n_head_kv; - for (int t = 0; t < T; ++t) { - h_tok_[t] = tokens[t]; - qsa_step_fill(h_step_ + t * kStepCount, pos0 + t, s); - const int32_t pos_t = (int32_t) (pos0 + t); - for (int64_t h = 0; h < g.n_head; ++h) h_pos_[t * g.n_head + h] = pos_t; - for (int64_t h = 0; h < g.n_head_kv; ++h) pk[t * g.n_head_kv + h] = pos_t; - for (int64_t h = 0; h < g.idx_q_heads; ++h) pi[t * g.idx_q_heads + h] = pos_t; - } - *(volatile uint32_t*) h_seq_ = 0; - *(volatile uint32_t*) h_flag_ = 0; - *(volatile uint32_t*) h_flagA_ = 0; - *(volatile uint32_t*) h_flagB_ = 0; - std::atomic_thread_fence(std::memory_order_seq_cst); - last_t_ = T; - last_pos0_ = pos0; - for (int t = 0; t < T; ++t) last_tokens_[t] = tokens[t]; - staged_ = true; -} - -void Verifier::collect_profile() { - const ModelGeometry& g = *g_; - cudaMemcpy(prof_h_.data(), prof_, prof_h_.size() * 8, cudaMemcpyDeviceToHost); - const int64_t L = g.n_layers; - auto at = [&](int64_t l, int i) { return prof_h_[(size_t) (l * kProfPer + i)]; }; - // D8: the derived columns below read stamps the hc-read kernels write themselves or the next - // layer's first. A slot no kernel stamped is 0 and its unsigned difference wrapped to ~1e19 ns - - // which is why (gap)/head/hc0 printed ~1e14 ms per window. A missing or out-of-order stamp now - // contributes nothing. - const auto gap = [](unsigned long long to, unsigned long long from) { - return (from != 0 && to != 0 && to >= from) ? (double) (to - from) : 0.0; - }; - for (int64_t l = 0; l < L; ++l) { - const int kind = is_qsa_layer(g, l) ? 1 : 0; - unsigned long long prev = at(l, 0); - for (int i = 1; i <= 24; ++i) { - const unsigned long long x = at(l, i); - if (x == 0 || x < prev) continue; - prof_sum_[kind][i] += (double) (x - prev); - prev = x; - } - if (l + 1 < L) prof_sum_[kind][25] += gap(at(l + 1, 0), at(l, 24)); - const double dn = gap(at(l, 27), at(l, 0)), dd = gap(at(l, 28), at(l, 27)), du = gap(at(l, 1), at(l, 28)); - if (dn > 0 && dd > 0 && du > 0) { // the split exists: show it split, not twice - prof_sum_[kind][27] += dn; // hc-read0: norm - prof_sum_[kind][28] += dd; // down - prof_sum_[kind][29] += du; // up (through both halves, as before) - prof_sum_[kind][1] -= gap(at(l, 1), at(l, 0)); // (hc-read0 shown split) - } - } - prof_sum_[0][26] += gap(at(L, 1), at(L, 0)); - ++prof_windows_; -} - -bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, void* user, int32_t* out, - std::string& err) { - using namespace strata::kernels; - const OnDevice on_device(device_); - last_batch_ = false; - if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; } - if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; } - const ModelGeometry& g = *g_; - SessionState& ss = *ss_; - if (pos0 + T > ss.qsa_states[ss.qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; } - if (!capture(T, err) || !capture_commit(err)) return false; - VDBG("captured; staging\n"); - const Clock::time_point t0 = Clock::now(); - if (!staged_) stage_inputs(T, tokens, pos0); - staged_ = false; - const bool do_ple = ss.ple.ready() && ple_stage(); - uint32_t ple_rows[kVerifyMaxT * PLE_N_HEADS]; - if (do_ple) { - int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]}; - for (int t = 0; t < T; ++t) { - ngram_rows(&tokens[t], prev, 1, ss.ple.consts, ple_rows + t * PLE_N_HEADS); - prev[0] = prev[1]; - prev[1] = tokens[t]; - ss.ple.table->prefetch_rows(ple_rows + t * PLE_N_HEADS); - } - } - if (trace_h_ != nullptr) std::memset(trace_h_, 0, trace_n_ * 8); // #649: this window's breadcrumbs only - std::atomic_thread_fence(std::memory_order_seq_cst); - trace_ev("WINDOW", -1, -1, pos0 * 16 + T); - ms_host += ms_since(t0); - VDBG("staged; launching\n"); - const cudaError_t le = cudaGraphLaunch(exec_[T], cs_); - trace_ev("LAUNCHED", -1, -1, (int64_t) le); - if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; } - (void) cudaStreamQuery(cs_); - VDBG("launched\n"); - volatile uint32_t* const seq = h_seq_; - volatile uint32_t* const flag = h_flag_; - const int G = groups_[T] > 0 ? groups_[T] : 1; - const int gtb[2] = {0, (T + 1) / 2}, gte[2] = {G == 2 ? (T + 1) / 2 : T, T}; - const int64_t steps = (le_ - lb_) * G; - const bool test_stall = g_test_stall > 0 && windows + 1 == g_test_stall; // #267 test hook (off: false) - if (all_resident_ && !test_stall) { - if (do_ple) { - const Clock::time_point tp = Clock::now(); - if (!ss.ple.table->gather_batch(ple_rows, (size_t) T, h_ple_, err)) return false; - std::atomic_thread_fence(std::memory_order_seq_cst); - _mm_sfence(); - *flag = 1; - ms_host += ms_since(tp); - } else { - *flag = 1; - } - } else - for (int64_t k = 0; k < steps; ++k) { - const int64_t l = lb_ + k / G; - const int grp = (int) (k % G); - const uint32_t want = (uint32_t) (k + 1); - const Clock::time_point a = Clock::now(); - auto last_flush = a; - uint32_t spins = 0; - progress_at("verify window: waiting for the GPU to reach layer", l); - while (*seq < want) { - _mm_pause(); - if ((++spins & 1023u) != 0) continue; - const auto now = Clock::now(); - if (now - last_flush > std::chrono::microseconds(2000)) { - last_flush = now; - const cudaError_t q = cudaStreamQuery(cs_); - if (q != cudaErrorNotReady && *seq < want) { - trace_ev("NEVER-RANG", k, l, (int64_t) q); - trace_dump(stderr); - err = "verify: layer " + std::to_string(l) + " never rang (" + - (q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")"; - return false; - } - } - if (now - a > std::chrono::seconds(20)) { - // #267: the caller ends the engine; no spin kernel may outlive it - trace_ev("TIMEOUT", k, l, (int64_t) cudaStreamQuery(cs_)); - if (g_trace) { - diag(stderr); // the words and the breadcrumbs before the release ... - const bool drained = release_gpu_waits(5000); - trace_dump(stderr); // ... and after it: did the GPU move once its waits were raised? - err = "verify: timed out at layer " + std::to_string(l) + released_note(drained); - return false; - } - err = "verify: timed out at layer " + std::to_string(l) + released_note(release_gpu_waits(5000)); - return false; - } - } - const Clock::time_point b = Clock::now(); - if (g_trace) trace_ev("RANG", k, l, (int64_t) std::chrono::duration_cast(b - a).count()); - VDBG("layer %lld rang\n", (long long) l); - cur_layer_ = want - 1; - set_plan_slot(grp); - const int tb = gtb[grp], n = gte[grp] - gtb[grp]; - progress_at("verify window: the CPU experts of layer", l); - if (remote_opt_) remote_opt_->begin(h_w_ + (size_t) tb * ss.k, tb, n); - if (pool != nullptr) - pool(user, h_x_ + (size_t) tb * g.n_embd, h_ids_ + (size_t) tb * ss.k, n, ss.k, - h_ymiss_ + (size_t) tb * ss.k * g.n_embd, l); - if (remote_opt_) remote_opt_->end(); - VDBG("layer %lld served\n", (long long) l); - if (g_trace) trace_ev(*(volatile uint32_t*) h_flagA_ == want ? "SERVED" : "SERVED-NO-PLAN-YET", k, l, - (int64_t) ms_since(b)); // aux: ms the CPU experts took - progress_tick(); - std::atomic_thread_fence(std::memory_order_seq_cst); - _mm_sfence(); - if (*(volatile uint32_t*) h_flagA_ != want) { // the pool did not publish a plan: an empty one - sink_.counts[0] = 0; - sink_.counts[1] = 0; - sink_.counts[2] = 0; - sink_.start[0] = 0; - sink_.start2[0] = 0; - std::atomic_thread_fence(std::memory_order_seq_cst); - *(volatile uint32_t*) h_flagA_ = want; - raise_flag(h_flagB_, want); - } - // Layer 1's pre(1, 0) copies h_ple_ -> ple_ after Layer 0's wait_flag_ge(m_flag_, 1). - // By collecting PLE here at k == 0 (after publishing flagA/flagB for Layer 0 so the GPU can run - // Layer 0's VRAM experts, and before raising *flag = 1), the NVMe PLE reads overlap with both - // MtpDrafter::draft and Layer 0's attention + router + expert execution! - if (k == 0 && do_ple) { - const Clock::time_point tp = Clock::now(); - if (!ss.ple.table->gather_batch(ple_rows, (size_t) T, h_ple_, err)) return false; - std::atomic_thread_fence(std::memory_order_seq_cst); - _mm_sfence(); - ms_host += ms_since(tp); - } - if (!(test_stall && k + 1 == steps)) *flag = want; - ms_wait += std::chrono::duration(b - a).count(); - ms_pool += ms_since(b); - } - // (#646 staged the next stage's inputs here; 0.1.39b keeps the layer split's order: each stage stages its own) - progress_at("verify window: waiting for the GPU to finish the window (flags A/B/M raised)", (int64_t) T); - // #267: a window the GPU never finishes (a spin kernel that never sees its flag) holds the host here; the stall - // watchdog then releases every verifier's GPU waits (release_live_verifiers) before it ends the engine, so no - // spin kernel outlives the process - the case that left Windows GPUs "lost" until a power cycle. The wait - // itself stays a blocking sync: a cudaStreamQuery poll here cost IQ3_S ~3% decode (a core calling the driver - // beside the expert workers). - trace_ev("SYNC", -1, -1, 0); - const cudaError_t se = cudaStreamSynchronize(cs_); - trace_ev("SYNCED", -1, -1, (int64_t) se); - if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; } - commit_pending_ = false; - progress_at("verify window: waiting for the expert copies", (int64_t) T); - if (copy_used_) { - cudaStreamSynchronize(copy_); // no host function of this window may raise flag B in the next one - copy_used_ = false; - } - if (prof_on_ && G == 1) collect_profile(); // the window's GPU stage stamps - // ---- a sampled or penalized request: the head's sampling again, host-side so its parameters are this call's - // own (a captured kernel would replay the same draws forever). Row t's draw is Philox(seed, pos0 + t): tied to - // the POSITION it samples, not to how the text was cut into windows, so a seed replays the same text whatever - // the drafts were. Exact: a rejected row's draw is discarded, and no kept decision depends on a reused draw. - if (le_ < g.n_layers) { // a layer split's earlier stage: the hand-off is written (synced above) - ++windows; - return next_ == nullptr || next_->run(T, tokens, pos0, pool, next_user_, out, err); - } - const bool sampled = !sampling_.greedy && sampling_.temperature > 0.0f; - if (head_sampling_ && (sampled || hist_d_ != nullptr)) { - SamplerParams sp = sampling_; - sp.counter = (uint64_t) pos0; - sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_); - if (cudaStreamSynchronize(cs_) != cudaSuccess) { // m_out_ is the mapped h_out_: synced, it is readable - err = "verify: the head sampling failed"; - return false; - } - } - for (int t = 0; t < T; ++t) out[t] = ((volatile int32_t*) h_out_)[t]; - if (static const bool dbg = std::getenv("STRATA_DBG_NAN") != nullptr; dbg) { // debug: the first non-finite head - static bool reported = false; - if (!reported) { - std::vector h((size_t) T * (size_t) n_vocab_); - cudaMemcpy(h.data(), head_logits_, h.size() * 4, cudaMemcpyDeviceToHost); - for (int t = 0; t < T && !reported; ++t) { - int64_t bad = 0; - for (int64_t v = 0; v < n_vocab_; ++v) bad += !std::isfinite(h[(size_t) t * n_vocab_ + v]); - if (bad) { - reported = true; - std::fprintf(stderr, "strata dbg: verify window at position %lld, row %d: %lld of %lld logits non-finite " - "(token out %d)\n", (long long) pos0, t, (long long) bad, (long long) n_vocab_, out[t]); - } - } - } - } - VDBG("window done\n"); - ++windows; - progress_at("decode"); - progress_beat(); - return true; -} - -void Verifier::set_plan_slot(int grp) { - const int64_t cap = sink_.cap; - int32_t* base = h_plan_ + (size_t) grp * (size_t) plan_i32_; - const int64_t i32 = 4 + (cap + 1) + cap + cap; - const int64_t ptr_off = (i32 + 1) & ~1ll; - sink_.counts = base; - sink_.start = base + 4; - sink_.dst = sink_.start + cap + 1; - sink_.tok = sink_.dst + cap; - sink_.ptr = (unsigned long long*) (base + ptr_off); - sink_.ptr2 = sink_.ptr + cap; - sink_.start2 = base + ptr_off + 4 * cap; - const int G = last_batch_ ? 1 : (groups_[last_t_] > 0 ? groups_[last_t_] : 1); - const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs; - sink_.staging = (unsigned long long) (staging_ + (size_t) (grp * per) * strata::kernels::cpu::expert_layout().max_blob); - sink_.staging_cap = per; -} - -// Flag B only rises: a host function of an earlier layer may run after a later layer already raised it directly. -void Verifier::raise_flag(uint32_t* flag, uint32_t value) { - volatile long* f = (volatile long*) flag; -#if defined(_WIN32) - long cur = *f; - while ((uint32_t) cur < value) { - const long prev = _InterlockedCompareExchange(f, (long) value, cur); - if (prev == cur) break; - cur = prev; - } -#else - uint32_t cur = __atomic_load_n((uint32_t*) flag, __ATOMIC_SEQ_CST); - while (cur < value && !__atomic_compare_exchange_n((uint32_t*) flag, &cur, value, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {} -#endif -} - -// Plan v0.3 P6: the PCIe share by DMA. The copy engine moves the blobs while the CPU computes its own share and the -// GPU its VRAM experts; a host function raises flag B when they have landed (the graph waits for it before the PCIe -// groups). Staging is split between the two token groups of a split window. -void Verifier::fetch_dma(void* ctx, const uint8_t* const* src, int n, size_t bytes) { - Verifier* v = (Verifier*) ctx; - const uint32_t want = v->cur_layer_ + 1; - if (n <= 0) { raise_flag(v->h_flagB_, want); return; } - v->copy_used_ = true; - uint8_t* stage = (uint8_t*) v->sink_.staging; // this group's half in a split window - for (int i = 0; i < n; ++i) cudaMemcpyAsync(stage + (size_t) i * bytes, src[i], bytes, cudaMemcpyHostToDevice, v->copy_); - FlagSet& fs = v->flag_sets_[v->cur_layer_ % (sizeof v->flag_sets_ / sizeof v->flag_sets_[0])]; - fs.flag = v->h_flagB_; - fs.value = want; - cudaLaunchHostFunc(v->copy_, [](void* p) { FlagSet* s = (FlagSet*) p; raise_flag(s->flag, s->value); }, &fs); -} - -void Verifier::publish_plan(void* ctx) { - Verifier* v = (Verifier*) ctx; - _mm_sfence(); - *(volatile uint32_t*) v->h_flagA_ = v->cur_layer_ + 1; -} - -bool Verifier::window_logprobs(const int32_t* targets, int T, int64_t pos0, int32_t extra_id, std::FILE* out, - std::string& err) { - if (next_ != nullptr) return next_->window_logprobs(targets, T, pos0, extra_id, out, err); - const OnDevice on_device(device_); - if (head_logits_ == nullptr || n_vocab_ <= 0 || T <= 0 || targets == nullptr || out == nullptr) { - err = "window_logprobs: no head logits for this window"; - return false; - } - // run() synchronized cs_ before returning, so the head of this window is complete - std::vector h((size_t) T * (size_t) n_vocab_); - if (cudaMemcpy(h.data(), head_logits_, h.size() * sizeof(float), cudaMemcpyDeviceToHost) != cudaSuccess) { - err = "window_logprobs: the head logits copy failed"; - return false; - } - for (int t = 0; t < T; ++t) { - const float* row = h.data() + (size_t) t * (size_t) n_vocab_; - const int32_t tgt = targets[t]; - if (tgt < 0 || (int64_t) tgt >= n_vocab_) continue; - int64_t top = 0; - for (int64_t v = 1; v < n_vocab_; ++v) - if (row[v] > row[top]) top = v; - const double maxv = row[top]; - const bool has_extra = extra_id >= 0 && (int64_t) extra_id < n_vocab_; - double sum = 0.0, sum_without = 0.0; // the second skips extra_id: no cancellation when it holds ~all mass - for (int64_t v = 0; v < n_vocab_; ++v) { - const double e = std::exp((double) row[v] - maxv); - sum += e; - if (v != (int64_t) extra_id) sum_without += e; - } - const double lse = maxv + std::log(sum); - const double extra = has_extra ? (double) row[extra_id] - lse : NAN; - const double without = has_extra && tgt != extra_id && sum_without > 0.0 - ? (double) row[tgt] - (maxv + std::log(sum_without)) : NAN; - std::fprintf(out, "%lld\t%d\t%.9f\t%lld\t%.9f\t%d\t%.9f\t%.9f", (long long) (pos0 + t), (int) tgt, - (double) row[tgt] - lse, (long long) top, maxv - lse, (int) (top == (int64_t) tgt), extra, - without); - // STRATA_LOGPOS_TOPK=K: the K most likely tokens and their log-probabilities too (`id:logprob`), for a - // top-k comparison with another engine on the same tokens (docs/UNSLOTH_Q4.md) - static const int topk = [] { - const char* v = std::getenv("STRATA_LOGPOS_TOPK"); - return v != nullptr ? std::max(0, std::min(256, std::atoi(v))) : 0; - }(); - if (topk > 0) { - std::vector order((size_t) n_vocab_); - for (int64_t v = 0; v < n_vocab_; ++v) order[(size_t) v] = (int32_t) v; - std::partial_sort(order.begin(), order.begin() + topk, order.end(), - [&](int32_t a, int32_t b) { return row[a] > row[b]; }); - for (int j = 0; j < topk; ++j) - std::fprintf(out, "\t%d:%.6f", order[(size_t) j], (double) row[order[(size_t) j]] - lse); - } - std::fprintf(out, "\n"); - } - std::fflush(out); - return true; -} - -namespace { bool g_commit_async = false; } -void Verifier::set_commit_async(bool on) { g_commit_async = on && std::getenv("STRATA_COMMIT_SYNC") == nullptr; } - -bool Verifier::commit(int n_keep, std::string& err) { - const OnDevice on_device(device_); - if (n_keep < 1 || n_keep > last_t_) { err = "verify: commit count out of range"; return false; } - const Clock::time_point t0 = Clock::now(); - h_commit_[0] = n_keep; - h_commit_[1] = n_keep - 1; - for (int t = 0; t < max_t_; ++t) h_commit_[2 + t] = t < n_keep ? (int32_t) (last_pos0_ + t) : -1; - std::atomic_thread_fence(std::memory_order_seq_cst); - const cudaError_t le = cudaGraphLaunch(commit_exec_, cs_); - if (le != cudaSuccess) { err = std::string("verify: commit launch: ") + cudaGetErrorString(le); return false; } - // set_commit_async: no wait here - the next window runs on the same stream after it, and the drafter (its own - // stream) reads only this window's final rows and its own K/V. h_commit_ is next written after the next window's - // results are read, i.e. after this graph has run. Everything else waits on commit_done_ (wait_commit). - if (!g_commit_async || next_ != nullptr) { - const cudaError_t se = cudaStreamSynchronize(cs_); - if (se != cudaSuccess) { err = std::string("verify: commit: ") + cudaGetErrorString(se); return false; } - } else { - const cudaError_t re = cudaEventRecord(commit_done_, cs_); - if (re != cudaSuccess) { err = std::string("verify: commit event: ") + cudaGetErrorString(re); return false; } - (void) cudaStreamQuery(cs_); - commit_pending_ = true; - } - if (ple_stage()) // stages that share one session must advance it once - for (int t = 0; t < n_keep; ++t) { - ss_->ple_prev[0] = ss_->ple_prev[1]; - ss_->ple_prev[1] = last_tokens_[t]; - } - ms_commit += ms_since(t0); - return next_ == nullptr || next_->commit(n_keep, err); -} - -bool Verifier::wait_commit(std::string& err) { - if (commit_pending_) { - const OnDevice on_device(device_); - commit_pending_ = false; - const cudaError_t se = cudaEventSynchronize(commit_done_); - if (se != cudaSuccess) { err = std::string("verify: commit: ") + cudaGetErrorString(se); return false; } - } - return next_ == nullptr || next_->wait_commit(err); -} - - -// ================================ BATCH WINDOWS (see init_slots) ================================ - -bool Verifier::init_slots(const std::vector& slots, std::string& err) { - const OnDevice on_device(device_); - if (g_ == nullptr || ss_ == nullptr) { err = "verify: init_slots before init"; return false; } - if (slots.empty() || (int) slots.size() > max_t_) { - err = "verify: init_slots needs 1.." + std::to_string(max_t_) + " sessions"; - return false; - } - for (SessionState* x : slots) { - if (x == nullptr || x->layer_lo != ss_->layer_lo || x->layer_hi != ss_->layer_hi || - x->max_cells != ss_->max_cells || x->gdn_ord0 != ss_->gdn_ord0 || x->qsa_ord0 != ss_->qsa_ord0) { - err = "verify: a slot's session is not carved like the stage's own (layer range, context)"; - return false; - } - } - const strata::kernels::QsaShapes s = shapes_of(*g_); - const int64_t S = (int64_t) slots.size(), CB = 2 + max_t_; - const int64_t TS = (s.idx_block - 1) * g_->idx_key_dim, nQ = g_->n_qsa_layers(); - void* d = nullptr; - if (!mapped((size_t) (S * CB * 4 + 16), (void**) &h_commitb_, (void**) &m_commitb_)) { - err = "verify: the batch commit staging failed"; - return false; - } - const uint64_t a = ((uint64_t) S * CB * 4 + 255) & ~255ull; - if (cudaMalloc(&d, a + (uint64_t) S * std::max(nQ, 1) * TS * 4) != cudaSuccess) { - err = "verify: the batch buffers do not fit"; - return false; - } - arena_b_ = d; - commitb_ = (int32_t*) d; - tail_snap_b_ = (float*) ((uint8_t*) d + a); - slots_ = slots; - slot_sp_.assign(slots.size(), sampling_); // greedy until set_slot_sampling - std::fprintf(stderr, "strata verify: batch windows of up to %lld sequences (layers [%lld, %lld))\n", (long long) S, - (long long) lb_, (long long) le_); - return true; -} - -bool Verifier::capture_batch(const int* rows, int S, int hbase, std::string& err) { - cudaGraphExec_t& ex = exec_bm_[batch_key(rows, S, hbase)]; - if (ex != nullptr) return true; - if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { - err = "verify: begin batch capture failed"; - return false; - } - batch_rec_ = true; - row_base_ = hbase; - for (int t = 0; t < S; ++t) brow_[t] = rows[t]; - std::string rerr; - const bool ok = record_window(S, cs_, rerr); - batch_rec_ = false; - row_base_ = 0; - cudaGraph_t graph = nullptr; - const cudaError_t ce = cudaStreamEndCapture(cs_, &graph); - if (!ok || ce != cudaSuccess) { - if (graph) cudaGraphDestroy(graph); - err = !ok ? rerr : std::string("verify: end batch capture: ") + cudaGetErrorString(ce); - return false; - } - const cudaError_t ie = cudaGraphInstantiate(&ex, graph, 0); - cudaGraphDestroy(graph); - if (ie != cudaSuccess) { err = std::string("verify: batch instantiate: ") + cudaGetErrorString(ie); return false; } - cudaGraphUpload(ex, cs_); - cudaStreamSynchronize(cs_); - std::string list; - for (int t = 0; t < S; ++t) list += (t ? "," : "") + std::to_string(rows[t]); - std::fprintf(stderr, "strata verify: captured the batch window over slots %s\n", list.c_str()); - return true; -} - -bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::string& err) { - cudaGraphExec_t& cex = commit_bm_[batch_key(rows, S, hbase)]; - if (cex != nullptr) return true; - using namespace strata::kernels; - const ModelGeometry& g = *g_; - const QsaShapes s = shapes_of(g); - const int64_t C = g.ssm_conv_channels, HV = g.ssm_v_heads, ZV = g.ssm_value_dim, ID = g.idx_key_dim, MT = max_t_; - const int64_t CB = 2 + MT, nQ = g.n_qsa_layers(); - 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); - const int64_t TS = (s.idx_block - 1) * ID; - const int64_t HS = (int64_t) NG_HIST * NG_HC_DIM; - if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { - err = "verify: begin batch commit capture failed"; - return false; - } - bool ok = true; - try { - for (int t = 0; t < S; ++t) - copy_i32_from_mapped(commitb_ + (size_t) rows[t] * CB, m_commitb_ + (size_t) rows[t] * CB, CB, cs_); - int64_t qsa_index = 0, gdn_index = 0; - for (int64_t l = 0; l < lb_; ++l) (is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1; - for (int64_t l = lb_; l < le_ && ok; ++l) { - const LayerView v(*wt_, l); - if (!is_qsa_layer(g, l)) { - const WeightRef* wnm = need(v, "ssm_norm.weight", err); - if (!wnm) { ok = false; break; } - for (int t = 0; t < S; ++t) { - SessionState& sx = *slots_[(size_t) rows[t]]; - const int32_t* keep = commitb_ + (size_t) rows[t] * CB; - float* state = sx.gdn_state + (size_t) (gdn_index - sx.gdn_ord0) * gdn_floats; - float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; - gdn_conv_commit(conv, qkv_L_ + (size_t) gdn_index * MT * C + (size_t) t * C, (int) C, keep, cs_); - gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C + (size_t) t * C, (int) C, - gate_L_ + (size_t) gdn_index * MT * HV + (size_t) t * HV, - beta_L_ + (size_t) gdn_index * MT * HV + (size_t) t * HV, z_ + (size_t) t * ZV, - (const float*) wnm->data, EPS, g.gdn_gate(), y_dummy_ + (size_t) t * ZV, - (int) g.ssm_k_heads, (int) HV, 1, keep, cs_); - } - ++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; } - for (int t = 0; t < S; ++t) { - const QsaState& st = slots_[(size_t) rows[t]]->qsa_states[qsa_index]; - copy_from_mapped(st.idx_tail, tail_snap_b_ + ((size_t) rows[t] * nQ + qsa_index) * TS, TS, cs_); - const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; - native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + t) * ID, commitb_ + (size_t) rows[t] * CB + 2, - 0, (const float*) wikn->data, EPS, ib, s, st.max_cells, rope_scaling(), cs_); - } - ++qsa_index; - } - } - if (ok && ss_->ple.ready() && ple_stage()) - for (int t = 0; t < S; ++t) - copy_indexed(slots_[(size_t) rows[t]]->ple_hist, hist_snap_ + (size_t) t * HS, HS, - commitb_ + (size_t) rows[t] * CB + 1, HS, cs_); - } catch (const std::exception& e) { - err = std::string("verify batch commit: ") + e.what(); - ok = false; - } - cudaGraph_t graph = nullptr; - const cudaError_t ce = cudaStreamEndCapture(cs_, &graph); - if (!ok) { - if (graph) cudaGraphDestroy(graph); - return false; - } - if (ce != cudaSuccess || cudaGraphInstantiate(&cex, graph, 0) != cudaSuccess) { - if (graph) cudaGraphDestroy(graph); - err = std::string("verify: batch commit capture: ") + cudaGetErrorString(ce); - return false; - } - cudaGraphDestroy(graph); - return true; -} - -bool Verifier::stage_batch(const int* rows, int S, int hbase, const int32_t* tokens, const int64_t* pos, - std::string& err) { - using namespace strata::kernels; - if (S < 1 || S > max_t_ || hbase < 0 || hbase + S > (int) slots_.size()) { - err = "verify: batch rows out of range (init_slots)"; - return false; - } - for (int t = 0; t < S; ++t) { - bool dup = false; - for (int u = 0; u < t; ++u) dup = dup || rows[u] == rows[t]; - if (rows[t] < 0 || rows[t] >= (int) slots_.size() || dup) { err = "verify: a batch row's slot is out of range or twice"; return false; } - } - if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; } - const ModelGeometry& g = *g_; - for (int t = 0; t < S; ++t) - if (pos[t] < 0 || pos[t] + 1 > slots_[(size_t) rows[t]]->max_cells) { - err = "verify: slot " + std::to_string(rows[t]) + " runs past its context"; - return false; - } - if (!capture_batch(rows, S, hbase, err) || !capture_commit_batch(rows, S, hbase, err)) return false; - const Clock::time_point t0 = Clock::now(); - const QsaShapes s = shapes_of(g); - for (int t = 0; t < S; ++t) { - h_tok_[t] = tokens[t]; - qsa_step_fill(h_step_ + t * kStepCount, pos[t], s); - for (int64_t h = 0; h < g.n_head; ++h) h_pos_[t * g.n_head + h] = (int32_t) pos[t]; - int32_t* pk = h_pos_ + (size_t) max_t_ * g.n_head; - int32_t* pi = pk + (size_t) max_t_ * g.n_head_kv; - for (int64_t h = 0; h < g.n_head_kv; ++h) pk[t * g.n_head_kv + h] = (int32_t) pos[t]; - for (int64_t h = 0; h < g.idx_q_heads; ++h) pi[t * g.idx_q_heads + h] = (int32_t) pos[t]; - } - if (ss_->ple.ready() && ple_stage()) { - uint32_t ple_rows[kVerifyMaxT * PLE_N_HEADS]; // (not `rows`: that is the slots of the window's rows) - for (int t = 0; t < S; ++t) { - const SessionState& sx = *slots_[(size_t) rows[t]]; - int32_t prev[2] = {sx.ple_prev[0], sx.ple_prev[1]}; - ngram_rows(&tokens[t], prev, 1, ss_->ple.consts, ple_rows + t * PLE_N_HEADS); - } - if (!ss_->ple.table->gather_batch(ple_rows, (size_t) S, h_ple_, err)) return false; - } - // the commit's rows (a batch window keeps every row): [1, 0, position, -1 ..] per slot - const int64_t CB = 2 + max_t_; - for (int t = 0; t < S; ++t) { - int32_t* c = h_commitb_ + (size_t) rows[t] * CB; - c[0] = 1; - c[1] = 0; - c[2] = (int32_t) pos[t]; - for (int64_t j = 3; j < CB; ++j) c[j] = -1; - } - *(volatile uint32_t*) h_seq_ = 0; - *(volatile uint32_t*) h_flag_ = 0; - *(volatile uint32_t*) h_flagA_ = 0; - *(volatile uint32_t*) h_flagB_ = 0; - std::atomic_thread_fence(std::memory_order_seq_cst); - last_t_ = S; - for (int t = 0; t < S; ++t) last_rows_[t] = rows[t]; - row_base_ = hbase; // the graphs' key (and nothing else) reads it until the next stage_batch - last_batch_ = true; - for (int t = 0; t < S; ++t) { last_tokens_[t] = tokens[t]; last_pos_b_[t] = pos[t]; } - ms_host += ms_since(t0); - return true; -} - -bool Verifier::run_slots(int S, const int32_t* tokens, const int64_t* pos, PoolMultiFn pool, void* user, int32_t* out, - std::string& err) { - int rows[8] = {}; - for (int t = 0; t < S && t < 8; ++t) rows[t] = t; - return run_slot_rows(rows, S, tokens, pos, pool, user, out, err); -} - -bool Verifier::run_slot_rows(const int* rows, int S, const int32_t* tokens, const int64_t* pos, PoolMultiFn pool, - void* user, int32_t* out, std::string& err) { - using namespace strata::kernels; - const OnDevice on_device(device_); - const ModelGeometry& g = *g_; - if (!stage_batch(rows, S, 0, tokens, pos, err)) return false; - const cudaError_t le = cudaGraphLaunch(exec_bm_[batch_key(rows, S, 0)], cs_); - if (le != cudaSuccess) { err = std::string("verify: batch launch: ") + cudaGetErrorString(le); return false; } - (void) cudaStreamQuery(cs_); - volatile uint32_t* const seq = h_seq_; - volatile uint32_t* const flag = h_flag_; - const int64_t steps = le_ - lb_; - for (int64_t k = 0; k < steps; ++k) { - const int64_t l = lb_ + k; - const uint32_t want = (uint32_t) (k + 1); - const Clock::time_point a = Clock::now(); - auto last_flush = a; - uint32_t spins = 0; - progress_at("verify batch: waiting for the GPU to reach layer", l); - while (*seq < want) { - _mm_pause(); - if ((++spins & 1023u) != 0) continue; - const auto now = Clock::now(); - if (now - last_flush > std::chrono::microseconds(2000)) { - last_flush = now; - const cudaError_t q = cudaStreamQuery(cs_); - if (q != cudaErrorNotReady && *seq < want) { - err = "verify batch: layer " + std::to_string(l) + " never rang (" + - (q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")"; - return false; - } - } - if (now - a > std::chrono::seconds(20)) { - err = "verify batch: timed out at layer " + std::to_string(l) + released_note(release_gpu_waits(5000)); - return false; - } - } - const Clock::time_point b = Clock::now(); - cur_layer_ = want - 1; - set_plan_slot(0); - progress_at("verify batch: the CPU experts of layer", l); - if (pool != nullptr) pool(user, h_x_, h_ids_, S, ss_->k, h_ymiss_, l); - progress_tick(); - std::atomic_thread_fence(std::memory_order_seq_cst); - _mm_sfence(); - if (*(volatile uint32_t*) h_flagA_ != want) { // the pool did not publish a plan: an empty one - sink_.counts[0] = 0; - sink_.counts[1] = 0; - sink_.counts[2] = 0; - sink_.start[0] = 0; - sink_.start2[0] = 0; - std::atomic_thread_fence(std::memory_order_seq_cst); - *(volatile uint32_t*) h_flagA_ = want; - raise_flag(h_flagB_, want); - } - *flag = want; - ms_wait += std::chrono::duration(b - a).count(); - ms_pool += ms_since(b); - } - const cudaError_t se = cudaStreamSynchronize(cs_); - if (se != cudaSuccess) { err = std::string("verify batch: ") + cudaGetErrorString(se); return false; } - cudaStreamSynchronize(copy_); - if (prof_on_) collect_profile(); - ++windows; - if (le_ < g.n_layers) return next_ == nullptr || next_->run_slot_rows(rows, S, tokens, pos, pool, next_user_, out, err); - if (!sample_rows(S, err)) return false; - for (int t = 0; t < S; ++t) out[t] = ((volatile int32_t*) h_out_)[t]; - progress_at("decode"); - progress_beat(); - return true; -} - -bool Verifier::commit_slots(std::string& err) { - const OnDevice on_device(device_); - if (!last_batch_ || last_t_ < 1) { err = "verify: commit_slots without a batch window"; return false; } - const int S = last_t_; - const Clock::time_point t0 = Clock::now(); - std::atomic_thread_fence(std::memory_order_seq_cst); - const cudaError_t le = cudaGraphLaunch(commit_bm_[batch_key(last_rows_, S, row_base_)], cs_); - if (le != cudaSuccess) { err = std::string("verify: batch commit launch: ") + cudaGetErrorString(le); return false; } - const cudaError_t se = cudaStreamSynchronize(cs_); - if (se != cudaSuccess) { err = std::string("verify: batch commit: ") + cudaGetErrorString(se); return false; } - if (ple_stage()) - for (int t = 0; t < S; ++t) { - SessionState& sx = *slots_[(size_t) last_rows_[t]]; - sx.ple_prev[0] = sx.ple_prev[1]; - sx.ple_prev[1] = last_tokens_[t]; - } - ms_commit += ms_since(t0); - return next_ == nullptr || next_->commit_slots(err); -} - -bool Verifier::sample_rows(int S, std::string& err) { - bool any = false; - for (int t = 0; t < S; ++t) { - strata::kernels::SamplerParams sp = slot_sp_[(size_t) last_rows_[t]]; - if (sp.greedy || sp.temperature <= 0.0f) continue; - sp.counter = (uint64_t) last_pos_b_[t]; // Philox(seed, position): the solo window's draw for this position - sp.penalty_last_n = 0; - strata::kernels::sample_tokens(head_logits_ + (size_t) t * (size_t) n_vocab_, 1, (int) n_vocab_, nullptr, 0, sp, - m_out_ + t, cs_); - any = true; - } - if (any && cudaStreamSynchronize(cs_) != cudaSuccess) { err = "verify batch: the row sampling failed"; return false; } - return true; -} - -bool Verifier::batch_launch(int base, int S, const int32_t* tokens, const int64_t* pos, std::string& err) { - const OnDevice on_device(device_); - if (b_running_) { err = "verify: batch_launch while this stage is busy"; return false; } - int rows[8] = {}; - for (int t = 0; t < S && t < 8; ++t) rows[t] = base + t; - if (!stage_batch(rows, S, base, tokens, pos, err)) return false; - cudaError_t le = cudaGraphLaunch(exec_bm_[batch_key(rows, S, base)], cs_); - if (le == cudaSuccess) le = cudaGraphLaunch(commit_bm_[batch_key(rows, S, base)], cs_); // right behind it: every row is kept - if (le != cudaSuccess) { err = std::string("verify: batch launch: ") + cudaGetErrorString(le); return false; } - (void) cudaStreamQuery(cs_); - if (ple_stage()) // the host's side of the commit (the hash's last two tokens) - for (int t = 0; t < S; ++t) { - SessionState& sx = *slots_[(size_t) rows[t]]; - sx.ple_prev[0] = sx.ple_prev[1]; - sx.ple_prev[1] = tokens[t]; - } - b_running_ = true; - b_k_ = 0; - b_steps_ = le_ - lb_; - b_last_ = Clock::now(); - return true; -} - -int Verifier::batch_poll(PoolMultiFn pool, void* user, std::string& err) { - if (!b_running_) return 1; - const OnDevice on_device(device_); - volatile uint32_t* const seq = h_seq_; - const int S = last_t_; - while (b_k_ < b_steps_) { - const uint32_t want = (uint32_t) (b_k_ + 1); - if (*seq < want) { - const auto now = Clock::now(); - if (now - b_last_ > std::chrono::milliseconds(2)) { - const cudaError_t q = cudaStreamQuery(cs_); - if (q != cudaErrorNotReady && *seq < want) { - err = "verify batch: layer " + std::to_string(lb_ + b_k_) + " never rang (" + - (q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")"; - b_running_ = false; - return -1; - } - if (now - b_last_ > std::chrono::seconds(20)) { - err = "verify batch: timed out at layer " + std::to_string(lb_ + b_k_) + released_note(release_gpu_waits(5000)); - b_running_ = false; - return -1; - } - } - return 0; - } - const Clock::time_point b = Clock::now(); - cur_layer_ = want - 1; - set_plan_slot(0); - if (pool != nullptr) pool(user, h_x_, h_ids_, S, ss_->k, h_ymiss_, lb_ + b_k_); - progress_tick(); - std::atomic_thread_fence(std::memory_order_seq_cst); - _mm_sfence(); - if (*(volatile uint32_t*) h_flagA_ != want) { // the pool did not publish a plan: an empty one - sink_.counts[0] = 0; - sink_.counts[1] = 0; - sink_.counts[2] = 0; - sink_.start[0] = 0; - sink_.start2[0] = 0; - std::atomic_thread_fence(std::memory_order_seq_cst); - *(volatile uint32_t*) h_flagA_ = want; - raise_flag(h_flagB_, want); - } - *(volatile uint32_t*) h_flag_ = want; - ms_pool += ms_since(b); - b_last_ = Clock::now(); - ++b_k_; - } - const cudaError_t q = cudaStreamQuery(cs_); - if (q == cudaErrorNotReady) return 0; - if (q != cudaSuccess) { err = std::string("verify batch: ") + cudaGetErrorString(q); b_running_ = false; return -1; } - const cudaError_t qc = cudaStreamQuery(copy_); // no host function of this window may raise flag B in the next - if (qc == cudaErrorNotReady) return 0; - if (prof_on_) collect_profile(); - if (last_stage()) { - if (!sample_rows(S, err)) { b_running_ = false; return -1; } - for (int t = 0; t < S; ++t) b_out_[t] = ((volatile int32_t*) h_out_)[t]; - } - ++windows; - b_running_ = false; - progress_beat(); - return 1; -} - -bool Verifier::copy_logits(int t, float* host) const { - if (next_ != nullptr) return next_->copy_logits(t, host); // a layer split: the head is on the last stage - if (head_logits_ == nullptr || host == nullptr || t < 0 || n_vocab_ <= 0) return false; - return cudaMemcpy(host, head_logits_ + (size_t) t * (size_t) n_vocab_, (size_t) n_vocab_ * sizeof(float), - cudaMemcpyDeviceToHost) == cudaSuccess; -} - -} // namespace strata::core diff --git a/src/core/weights.cpp b/src/core/weights.cpp deleted file mode 100644 index 8b42f84..0000000 --- a/src/core/weights.cpp +++ /dev/null @@ -1,479 +0,0 @@ -// src/core/weights.cpp - the dense-weight loader. See the header for the engine-vs-pack distinction. -#include "strata/core/weights.hpp" - -#include "strata/kernels/f16_bits.hpp" - -#include - -#include -#include -#include -#include -#include - -#if defined(_WIN32) -#include -#else -#include -#endif - -namespace strata::core { -namespace { - -constexpr uint64_t CHUNK = 8ull << 20; // 8 MiB of SOURCE per staging round - -double now_ms() { - using namespace std::chrono; - return duration(steady_clock::now().time_since_epoch()).count(); -} - -struct IndexRow { - std::string name; - int file = 0; - WeightKind kind = WeightKind::Verbatim; - uint64_t src_off = 0, src_bytes = 0, dst_off = 0, dst_bytes = 0; - int64_t ne0 = 0, ne1 = 0; - int code_bits = 0, code_bias = 0, group_elems = 0, codebook = 0, has_offset = 0; - uint64_t codes_bytes = 0, scales_bytes = 0, offset_bytes = 0; - int scales_fp16 = 0; - int act_kind = 0; - bool raw16 = false; ///< plan v0.3 P6: already 16-bit in the file (kinds 4/5) -}; - -/// How a segment's bytes must be transformed on the way from the pack to the arena. -enum class Conv : int { - Copy = 0, ///< the bytes are already the engine form - Bf16High = 1, ///< f32 container holding a bf16 value: take the high 16 bits - ToF16 = 2, ///< f32 container holding an f16 value: a real round-to-nearest-even conversion - WidenF16 = 3, ///< fp16 bits to be held as f32: EXACT, and the reason this path exists at all -}; - -/// One contiguous run of a tensor's source span with a single destination range and one transform. -/// -/// THE SEGMENT LIST IS WHY THIS LOADER CAN CHANGE WIDTHS PLANE BY PLANE. A quantized tensor used to be one -/// verbatim span, which is only correct when every plane is already in engine form - and for 90 of the 303 -/// quantized tensors the scale plane is fp16 in the pack and must be f32 in the arena. -struct Seg { - uint64_t src_off = 0; ///< relative to the row's src_off - uint64_t src_bytes = 0; - uint64_t dst_off = 0; ///< relative to the row's dst_off - uint64_t dst_bytes = 0; - Conv conv = Conv::Copy; -}; - -const char* file_name(int id) { - switch (id) { - case 0: return "dense.bin"; - case 1: return "embd.bin"; - case 2: return "experts.bin"; - case 3: return "extra.bin"; // plan v0.3 P6: a native pack's float tensors that the base pack quantized - default: return nullptr; - } -} - -/// UTF-16 path for CreateFile-free portability: the loader uses `std::fopen`, which on Windows takes an ANSI -/// path. The pack lives beside the executable in practice, but a pack under a user directory with a -/// non-ASCII name would silently fail to open, so the caller gets the errno rather than a null pointer. -bool read_at(std::FILE* f, uint64_t off, void* dst, size_t n, std::string& err, const char* what) { -#if defined(_WIN32) - if (_fseeki64(f, (long long) off, SEEK_SET) != 0) { err = std::string(what) + ": seek failed"; return false; } -#else - if (fseeko(f, (off_t) off, SEEK_SET) != 0) { err = std::string(what) + ": seek failed"; return false; } -#endif - if (std::fread(dst, 1, n, f) != n) { err = std::string(what) + ": short read"; return false; } - return true; -} - -} // namespace - -bool WeightTable::pool_bytes(const std::string& pack_dir, uint64_t& out, std::string& err, - const std::set* skip) { - const std::string path = pack_dir + "/index.txt"; - std::FILE* f = std::fopen(path.c_str(), "rb"); - if (!f) { err = "cannot open " + path; return false; } - char line[1024]; - out = 0; - uint64_t pool = 0, compact = 0; - int align = 0; - while (std::fgets(line, sizeof line, f)) { - if (line[0] == '#') { - unsigned long long p = 0; - int a = 0, tensors = 0; - if (std::sscanf(line, "# align %d pool %llu tensors %d", &a, &p, &tensors) == 3) { pool = p; align = a; } - continue; - } - if (skip == nullptr) continue; - char name[256] = {0}; - unsigned long long dst_bytes = 0, dummy = 0; - int i1 = 0, i2 = 0; - if (std::sscanf(line, "%255s %d %d %llu %llu %llu %llu", name, &i1, &i2, &dummy, &dummy, &dummy, &dst_bytes) != 7) - continue; - if (skip->count(name)) continue; - const uint64_t a = align > 0 ? (uint64_t) align : 256; - compact += (dst_bytes + a - 1) / a * a; - } - std::fclose(f); - if (pool == 0) { err = "no '# align ... pool ...' header in " + path; return false; } - out = skip ? compact : pool; - return true; -} - -bool WeightTable::index_code_bits(const std::string& pack_dir, const std::string& name, int& code_bits, - std::string& err) { - const std::string path = pack_dir + "/index.txt"; - std::FILE* f = std::fopen(path.c_str(), "rb"); - if (!f) { err = "cannot open " + path; return false; } - char line[1024]; - code_bits = -1; - while (std::fgets(line, sizeof line, f)) { - if (line[0] == '#') continue; - char row[256] = {0}; - unsigned long long dummy = 0; - long long ne = 0; - int i1 = 0, i2 = 0, bits = 0; - // the first ten fields of the row `load` parses: name file kind src_off src_bytes dst_off dst_bytes ne0 ne1 code_bits - if (std::sscanf(line, "%255s %d %d %llu %llu %llu %llu %lld %lld %d", row, &i1, &i2, &dummy, &dummy, &dummy, - &dummy, &ne, &ne, &bits) != 10) - continue; - if (name == row) { code_bits = bits; break; } - } - std::fclose(f); - return true; -} - -bool WeightTable::load(const std::string& pack_dir, void* arena_base, uint64_t arena_bytes, std::string& err, - const std::set* skip) { - const std::string path = pack_dir + "/index.txt"; - std::FILE* idx = std::fopen(path.c_str(), "rb"); - if (!idx) { err = "cannot open " + path + " (run tools/pack_index.py)"; return false; } - - uint64_t pool = 0; - int align = 0; - std::vector rows; - char line[1024]; - while (std::fgets(line, sizeof line, idx)) { - if (line[0] == '#') { - unsigned long long p = 0; - int a = 0, t = 0; - if (std::sscanf(line, "# align %d pool %llu tensors %d", &a, &p, &t) == 3) { pool = p; align = a; } - continue; - } - IndexRow r; - char name[256] = {0}; - int kind = 0; - // The format is written by tools/pack_index.py and is space-separated with no quoting; a name with a - // space in it would break the parse, which is why the parser REFUSES rather than taking what it got. - const int n = std::sscanf(line, - "%255s %d %d %llu %llu %llu %llu %lld %lld %d %d %d %d %d %llu %llu %llu %d %d", - name, &r.file, &kind, &r.src_off, &r.src_bytes, &r.dst_off, &r.dst_bytes, - &r.ne0, &r.ne1, &r.code_bits, &r.code_bias, &r.group_elems, &r.codebook, - &r.has_offset, &r.codes_bytes, &r.scales_bytes, &r.offset_bytes, - &r.scales_fp16, &r.act_kind); - if (n != 19) { - // A malformed index line is a WRONG BYTE OFFSET waiting to happen, and a wrong offset decodes to - // a plausible weight. Refuse loudly instead of loading the rows that happened to parse. - err = "index.txt: could not parse a row (" + std::to_string(n) + " of 19 fields)"; - std::fclose(idx); - return false; - } - r.name = name; - // plan v0.3 P6: a standalone native pack (tools/iq_pack.py) stores 16-bit floats as they are in the GGUF: - // index kinds 4 (BF16) and 5 (F16) are copied and take the engine forms of kinds 1 and 3 - if (kind == 4 || kind == 5) { - r.raw16 = true; - kind = kind == 4 ? (int) WeightKind::Bf16InF32 : (int) WeightKind::F16InF32; - } - r.kind = (WeightKind) kind; - rows.push_back(r); - } - std::fclose(idx); - - if (pool == 0 || rows.empty()) { err = "index.txt has no header or no rows"; return false; } - // Plan v0.3 P1: a skip set compacts the arena. Kept rows are re-placed in index order at the index's - // alignment; skipped rows keep their metadata and get no bytes. - std::vector skipped(rows.size(), false); - if (skip != nullptr) { - const uint64_t a = align > 0 ? (uint64_t) align : 256; - uint64_t at = 0; - for (size_t i = 0; i < rows.size(); ++i) { - if (skip->count(rows[i].name)) { skipped[i] = true; continue; } - rows[i].dst_off = at; - at += (rows[i].dst_bytes + a - 1) / a * a; - } - pool = at; - } - if (arena_bytes < pool) { - err = "arena is " + std::to_string(arena_bytes) + " B but the index needs " + std::to_string(pool); - return false; - } - - // Two pinned staging buffers, both reused. Pinned because a 5 GB pageable upload spends its time in the - // driver copying through a bounce buffer, and bounded by CHUNK rather than by the largest tensor. - // - // STAGE_OUT IS NOT OPTIONAL. The first version of this loop converted the values straight into the - // destination pointer - which is DEVICE memory - from host code. A host write to a device address is - // undefined behaviour, and on this driver it does not fault: it corrupts whatever the address maps to in - // the host's own space, which is nothing at all, so the tensor would have loaded as the UNCONVERTED pack - // bytes and every BF16 weight would have been read as 32-bit garbage. Converted data goes to a host - // buffer and crosses the bus once. - // - // STAGE_OUT IS TWICE STAGE_IN because a conversion can now GROW: widening an fp16 scale plane to f32 - // doubles it. Sized at CHUNK it would have written 8 MiB past the end of a pinned allocation for every - // one of the 90 widened tensors - a heap corruption that would have been blamed on whatever ran next. - void* stage_in = nullptr; - void* stage_out = nullptr; - if (cudaHostAlloc(&stage_in, CHUNK, cudaHostAllocDefault) != cudaSuccess || - cudaHostAlloc(&stage_out, CHUNK * 2, cudaHostAllocDefault) != cudaSuccess) { - err = "cudaHostAlloc for the staging buffers failed"; - if (stage_in) cudaFreeHost(stage_in); - if (stage_out) cudaFreeHost(stage_out); - return false; - } - - uint8_t* dst_base = (uint8_t*) arena_base; - std::FILE* cur = nullptr; - int cur_file = -1; - table_.clear(); - report_ = LoadReport{}; - - const double t_read0 = now_ms(); - double upload_ms = 0; - for (size_t row_i = 0; row_i < rows.size(); ++row_i) { - const IndexRow& r = rows[row_i]; - if (skipped[row_i]) { - WeightRef wr; - wr.data = nullptr; - wr.resident = false; - wr.bytes = r.dst_bytes; - wr.ne0 = r.ne0; - wr.ne1 = r.ne1; - wr.elements = r.ne0 * (r.ne1 > 0 ? r.ne1 : 1); - wr.kind = r.kind; - wr.code_bits = r.code_bits; - wr.code_bias = r.code_bias; - wr.group_elems = r.group_elems; - wr.codebook_iq4nl = r.codebook != 0; - wr.has_offset = r.has_offset != 0; - wr.codes_bytes = r.codes_bytes; - wr.scales_bytes = r.scales_bytes; - wr.offset_bytes = r.offset_bytes; - wr.src_off = r.src_off; - wr.src_bytes = r.src_bytes; - wr.file_id = r.file; - wr.scales_fp16 = r.scales_fp16 != 0; - wr.act_kind = r.act_kind; - table_[r.name] = wr; - ++report_.tensors; - continue; - } - if (r.code_bits != 0 && r.dst_bytes == 0) { - // plan v0.3 P6: a native pack's row that carries a shape only - the GGUF form must serve it - err = r.name + ": this pack holds the tensor only in its GGUF form (run with --native SHARD1)"; - cudaFreeHost(stage_in); cudaFreeHost(stage_out); - return false; - } - if (r.file != cur_file) { - if (cur) std::fclose(cur); - const char* fn = file_name(r.file); - const std::string p = pack_dir + "/" + (fn ? fn : "?"); - cur = std::fopen(p.c_str(), "rb"); - if (!cur) { err = "cannot open " + p; cudaFreeHost(stage_in); cudaFreeHost(stage_out); return false; } - cur_file = r.file; - } - - // ---- the segment list: what this tensor's bytes are, plane by plane, in both forms - Seg segs[3]; - int n_segs = 0; - bool bad = false; - uint64_t sum_src = 0, sum_dst = 0; - if (r.codes_bytes != 0) { - // A quantized tensor: codes, then scales, then the optional offset plane, each contiguous in the - // source span in that order (pack_index.py verifies the contiguity and refuses otherwise). - segs[n_segs++] = Seg{0, r.codes_bytes, 0, r.codes_bytes, Conv::Copy}; - if (r.scales_bytes) { - const uint64_t src_scale_bytes = r.scales_fp16 ? r.scales_bytes / 2 : r.scales_bytes; - if (r.scales_fp16 && (r.scales_bytes % 2 || src_scale_bytes * 2 != r.scales_bytes)) { - err = r.name + ": an fp16 scale plane of an odd byte count"; - bad = true; - } - segs[n_segs++] = Seg{r.codes_bytes, src_scale_bytes, r.codes_bytes, r.scales_bytes, - r.scales_fp16 ? Conv::WidenF16 : Conv::Copy}; - } - if (r.offset_bytes) { - const uint64_t after = r.codes_bytes + (r.scales_fp16 ? r.scales_bytes / 2 : r.scales_bytes); - segs[n_segs++] = Seg{after, r.offset_bytes, r.codes_bytes + r.scales_bytes, r.offset_bytes, - Conv::Copy}; - } - } else { - // Everything else is one run whose transform is the row's kind. The two promoted types shrink - // 4 B/elem to 2; the rest are already the engine form. - Conv c = Conv::Copy; - if (r.raw16) c = Conv::Copy; - else if (r.kind == WeightKind::Bf16InF32) c = Conv::Bf16High; - else if (r.kind == WeightKind::F16InF32) c = Conv::ToF16; - const uint64_t elems = (uint64_t) r.ne0 * (uint64_t) (r.ne1 > 0 ? r.ne1 : 1); - if (c != Conv::Copy && (r.src_bytes != elems * 4 || r.dst_bytes != elems * 2)) { - // A promoted type is 4 B/elem in and 2 B/elem out, and nothing else. If those two numbers do - // not say so, the shape and the byte counts disagree and the element count this loop would - // use to walk the source is not the element count the pack wrote. - char buf[320]; - std::snprintf(buf, sizeof buf, - "%s: a promoted tensor of %llu elements is %llu B in and %llu B out, not %llu/%llu", - r.name.c_str(), (unsigned long long) elems, (unsigned long long) r.src_bytes, - (unsigned long long) r.dst_bytes, (unsigned long long) (elems * 4), - (unsigned long long) (elems * 2)); - err = buf; - bad = true; - } - segs[n_segs++] = Seg{0, r.src_bytes, 0, r.dst_bytes, c}; - } - for (int i = 0; i < n_segs; ++i) { sum_src += segs[i].src_bytes; sum_dst += segs[i].dst_bytes; } - // The segment list is this loop's own idea of the layout, and it is the ONLY thing standing between a - // mis-sized plane and a wrong byte offset. It is checked against both recorded totals, not trusted. - if (!bad && (sum_src != r.src_bytes || sum_dst != r.dst_bytes)) { - char buf[360]; - std::snprintf(buf, sizeof buf, - "%s: the segments cover %llu/%llu B but the index says %llu/%llu - the plane layout " - "this loader built is not the one the index describes", - r.name.c_str(), (unsigned long long) sum_src, (unsigned long long) sum_dst, - (unsigned long long) r.src_bytes, (unsigned long long) r.dst_bytes); - err = buf; - bad = true; - } - if (bad) { cudaFreeHost(stage_in); cudaFreeHost(stage_out); return false; } - - for (int si = 0; si < n_segs; ++si) { - const Seg& s = segs[si]; - const bool widening = (s.conv == Conv::WidenF16); - if (widening && (s.src_bytes & 1ull)) { - err = r.name + ": an fp16 plane with an odd source byte count"; - cudaFreeHost(stage_in); cudaFreeHost(stage_out); - return false; - } - uint64_t done = 0; - while (done < s.src_bytes) { - uint64_t n = std::min(CHUNK, s.src_bytes - done); - // WIDENING NEVER SPLITS AN ELEMENT. CHUNK is even, so a full chunk cannot, but the tail of a - // plane whose length is odd would - and half an fp16 is a plausible-looking scale. - if (widening && (n & 1ull)) { - if (n == 1) { err = r.name + ": an fp16 plane ending on a half element"; cudaFreeHost(stage_in); cudaFreeHost(stage_out); return false; } - n -= 1; - } - if (!read_at(cur, r.src_off + s.src_off + done, stage_in, (size_t) n, err, r.name.c_str())) { - cudaFreeHost(stage_in); cudaFreeHost(stage_out); - return false; - } - const uint8_t* src = (const uint8_t*) stage_in; - const void* host_src = src; - uint64_t out_bytes = n; - uint64_t out_at = s.dst_off + done; - - switch (s.conv) { - case Conv::Copy: - break; - case Conv::Bf16High: { - // THE HIGH 16 BITS ARE THE BF16 ENCODING, exactly - not a rounding. A bf16 value is - // the top half of its f32 image, and the pack promoted it without changing it, so - // this is a copy with a stride. - const uint64_t elems = n / 4; - out_bytes = elems * 2; - uint8_t* o = (uint8_t*) stage_out; - for (uint64_t i = 0; i < elems; ++i) { - uint32_t v; - std::memcpy(&v, src + i * 4, 4); - const uint16_t h = (uint16_t) (v >> 16); - std::memcpy(o + i * 2, &h, 2); - } - host_src = stage_out; - out_at = s.dst_off + done / 2; - break; - } - case Conv::ToF16: { - const uint64_t elems = n / 4; - out_bytes = elems * 2; - uint8_t* o = (uint8_t*) stage_out; - for (uint64_t i = 0; i < elems; ++i) { - float v; - std::memcpy(&v, src + i * 4, 4); - const uint16_t h = strata::kernels::f16_from_f32(v); - std::memcpy(o + i * 2, &h, 2); - } - host_src = stage_out; - out_at = s.dst_off + done / 2; - break; - } - case Conv::WidenF16: { - // fp16 bits -> f32. EXACT: every fp16 value is an f32 value, including the - // subnormals, so this cannot change a single weight - which is why the engine may do - // it at all, and why doing it costs 10.88 MiB rather than a second kernel family. - const uint64_t elems = n / 2; - out_bytes = elems * 4; - float* o = (float*) stage_out; - for (uint64_t i = 0; i < elems; ++i) { - uint16_t h; - std::memcpy(&h, src + i * 2, 2); - o[i] = strata::kernels::f32_from_f16(h); - } - host_src = stage_out; - out_at = s.dst_off + done * 2; - break; - } - } - - const double u0 = now_ms(); - if (cudaMemcpy(dst_base + r.dst_off + out_at, host_src, out_bytes, cudaMemcpyHostToDevice) != - cudaSuccess) { - err = "cudaMemcpy failed for " + r.name; - cudaFreeHost(stage_in); cudaFreeHost(stage_out); - return false; - } - upload_ms += now_ms() - u0; - done += n; - } - } - - WeightRef wr; - wr.data = dst_base + r.dst_off; - wr.bytes = r.dst_bytes; - wr.ne0 = r.ne0; - wr.ne1 = r.ne1; - wr.elements = r.ne0 * (r.ne1 > 0 ? r.ne1 : 1); - wr.kind = r.kind; - wr.code_bits = r.code_bits; - wr.code_bias = r.code_bias; - wr.group_elems = r.group_elems; - wr.codebook_iq4nl = r.codebook != 0; - wr.has_offset = r.has_offset != 0; - wr.codes_bytes = r.codes_bytes; - wr.scales_bytes = r.scales_bytes; - wr.offset_bytes = r.offset_bytes; - wr.src_off = r.src_off; - wr.src_bytes = r.src_bytes; - wr.file_id = r.file; - wr.scales_fp16 = r.scales_fp16 != 0; - wr.act_kind = r.act_kind; - table_[r.name] = wr; - - ++report_.tensors; - if ((r.kind == WeightKind::Bf16InF32 || r.kind == WeightKind::F16InF32) && !r.raw16) { - ++report_.re_rounded; - report_.bytes_saved += r.src_bytes - r.dst_bytes; - } - } - if (cur) std::fclose(cur); - cudaFreeHost(stage_in); - cudaFreeHost(stage_out); - - report_.arena_bytes = pool; - report_.read_ms = now_ms() - t_read0 - upload_ms; - report_.upload_ms = upload_ms; - if (cudaDeviceSynchronize() != cudaSuccess) { err = "cudaDeviceSynchronize after the load failed"; return false; } - return true; -} - -const WeightRef* WeightTable::find(const std::string& name) const { - const auto it = table_.find(name); - return it == table_.end() ? nullptr : &it->second; -} - -} // namespace strata::core diff --git a/src/kernels/bf16_bits_test.cpp b/src/kernels/bf16_bits_test.cpp deleted file mode 100644 index f996463..0000000 --- a/src/kernels/bf16_bits_test.cpp +++ /dev/null @@ -1,80 +0,0 @@ -// src/kernels/bf16_bits_test.cpp - `bf16_bits.hpp` against ggml's rule, over EVERY f32 bit pattern (CPU only). -// -// the rounding add `i + 0x7FFF + bit16` carries out of the mantissa for a NaN, so 0x7FFFFFFF came back as -// -0 and 0x7F800001 as +inf - an upstream NaN was masked instead of propagated. `ggml_compute_fp32_to_bf16` -// (ggml-impl.h at the pinned llama.cpp) tests the NaN first and returns `(i >> 16) | 64`. Three checks, all -// exhaustive (2^32 inputs, a few seconds): -// -// 1. the header equals ggml's function, transcribed below, on every input; -// 2. on every NON-NaN input it equals the previous rounding, so the change cannot move a finite value or an -// infinity by a single bit; -// 3. every NaN input gives a quiet NaN of the same sign. -// -// And the round trip over all 65,536 bf16 patterns: a non-NaN bf16 survives f32 and back unchanged. -#include "strata/kernels/bf16_bits.hpp" - -#include -#include -#include - -namespace { - -/// ggml_compute_fp32_to_bf16, ggml/src/ggml-impl.h (MIT, the ggml authors), on raw bits. -uint16_t ggml_bf16(uint32_t u) { - if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64); - return (uint16_t) ((u + (0x7fffu + ((u >> 16) & 1u))) >> 16); -} - -/// The rule before this fix, kept only to prove the change is confined to NaN inputs. -uint16_t previous_bf16(uint32_t u) { - u = (u + ((u >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u; - return (uint16_t) (u >> 16); -} - -bool is_nan_bits(uint32_t u) { return (u & 0x7fffffffu) > 0x7f800000u; } - -} // namespace - -int main() { - unsigned long long vs_ggml = 0, vs_previous = 0, nan_lost = 0, nan_inputs = 0, previous_masked = 0; - uint32_t first_bad = 0; - bool have_bad = false; - for (uint64_t k = 0; k <= 0xFFFFFFFFull; ++k) { - const uint32_t u = (uint32_t) k; - float f; - std::memcpy(&f, &u, 4); - const uint16_t got = strata::kernels::bf16_from_f32(f); - if (got != ggml_bf16(u)) { - ++vs_ggml; - if (!have_bad) { first_bad = u; have_bad = true; } - } - if (is_nan_bits(u)) { - ++nan_inputs; - const uint32_t back = (uint32_t) got << 16; - // a quiet NaN (bit 22 of the f32) with the input's sign - if (!is_nan_bits(back) || (back & 0x00400000u) == 0 || (back >> 31) != (u >> 31)) ++nan_lost; - if (!is_nan_bits((uint32_t) previous_bf16(u) << 16)) ++previous_masked; - } else if (got != previous_bf16(u)) { - ++vs_previous; - if (!have_bad) { first_bad = u; have_bad = true; } - } - } - std::printf(" f32 -> bf16 over 2^32 inputs: %llu differ from ggml, %llu non-NaN differ from the previous rule\n", - vs_ggml, vs_previous); - std::printf(" NaN inputs: %llu, not a quiet same-sign NaN now: %llu (the previous rule masked %llu of them)\n", - nan_inputs, nan_lost, previous_masked); - if (have_bad) std::printf(" first mismatch at input 0x%08x\n", first_bad); - - unsigned long long trip_bad = 0; - for (uint32_t h = 0; h <= 0xFFFFu; ++h) { - const float f = strata::kernels::f32_from_bf16((uint16_t) h); - const uint16_t back = strata::kernels::bf16_from_f32(f); - const bool nan = is_nan_bits(h << 16); - if (back != (nan ? (uint16_t) (h | 64u) : (uint16_t) h)) ++trip_bad; - } - std::printf(" bf16 -> f32 -> bf16 over 65536 patterns: %llu wrong\n", trip_bad); - - const bool ok = vs_ggml == 0 && vs_previous == 0 && nan_lost == 0 && trip_bad == 0 && previous_masked > 0; - std::printf("\nbf16_bits_test %s\n", ok ? "OK" : "FAILED"); - return ok ? 0 : 1; -} diff --git a/src/kernels/bf16_gemv_parity.cpp b/src/kernels/bf16_gemv_parity.cpp deleted file mode 100644 index 435c336..0000000 --- a/src/kernels/bf16_gemv_parity.cpp +++ /dev/null @@ -1,148 +0,0 @@ -// src/kernels/bf16_gemv_parity.cpp - P2.S5's test for the BF16 GEMV. -// -// THREE THINGS ARE CHECKED, and the third is the one the engine's correctness rests on: -// -// 1. both kernels against a host reference that reads the SAME bf16 bits - so what is under test is the -// reduction, not the conversion, and the tolerance is set by summation order and nothing else; -// 2. the naive and the split kernel agree with each other, because the naive one is the reference the -// split one exists to be checked against and a disagreement there means one of them is wrong; -// 3. **THE ACTIVATION CONTRACT IS OBSERVABLE.** A BF16 weight sees a BF16 activation; feeding it fp16 or -// f32 instead is a 2^-9 = 1.95e-03 relative change, which is above any 1e-3 tolerance. An fp16 -// activation is the rival reading, computed and required to differ, because it is what the engine did -// before `docs/activation-contract.md` settled the question and it produces perfectly plausible output. -#include "strata/kernels/bf16_bits.hpp" -#include "strata/kernels/bf16_gemv.hpp" -#include "strata/kernels/f16_bits.hpp" - -#include - -#include -#include -#include -#include -#include -#include - -namespace { - -using strata::kernels::bf16_from_f32; -using strata::kernels::f32_from_bf16; - -void check(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -double rel_l1(const std::vector& a, const std::vector& 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); -} - -/// The host reference, in DOUBLE, over the same bf16 bits. -void reference(const std::vector& x, const std::vector& w, long long n_in, long long n_out, - std::vector& y) { - y.assign((size_t) n_out, 0.0f); - for (long long o = 0; o < n_out; ++o) { - double acc = 0; - for (long long i = 0; i < n_in; ++i) - acc += (double) f32_from_bf16(x[(size_t) i]) * (double) f32_from_bf16(w[(size_t) (o * n_in + i)]); - y[(size_t) o] = (float) acc; - } -} - -} // namespace - -int main(int argc, char** argv) { - bool selftest = false; - for (int i = 1; i < argc; ++i) { - if (std::string(argv[i]) == "--selftest") selftest = true; - else { std::fprintf(stderr, "usage: bf16_gemv_parity [--selftest]\n"); return 2; } - } - int bad = 0; - - // THE REAL SHAPES, because a kernel that only works on a square toy is not a kernel this engine can use. - // `ssm_alpha` is [2560, 48] - a wide reduction and 48 outputs - and `indexer.k_proj` is [2560, 128]. - struct Shape { long long n_in, n_out; const char* what; }; - const Shape shapes[] = { - {2560, 48, "ssm_alpha.weight [2560, 48]"}, - {2560, 128, "indexer.k_proj [2560, 128]"}, - {2560, 512, "indexer.q_proj [2560, 512]"}, - {2560, 2560, "ple_value [2560, 2560]"}, - }; - - for (const Shape& s : shapes) { - std::mt19937 rng(4242); - std::normal_distribution g(0.0f, 1.0f); - std::vector fx((size_t) s.n_in), fw((size_t) (s.n_in * s.n_out)); - for (auto& v : fx) v = g(rng); - // a realistic weight scale: these are projections, not embeddings - for (auto& v : fw) v = g(rng) * 0.05f; - - // THE ACTIVATION IS ROUNDED TO BF16 FIRST, which is the contract, and the WEIGHT is already bf16 in - // the pack - the loaded bytes ARE the high 16 bits of an f32. - std::vector x((size_t) s.n_in), w((size_t) (s.n_in * s.n_out)); - for (size_t i = 0; i < fx.size(); ++i) x[i] = bf16_from_f32(fx[i]); - for (size_t i = 0; i < fw.size(); ++i) w[i] = bf16_from_f32(fw[i]); - - std::vector want; - reference(x, w, s.n_in, s.n_out, want); - - uint16_t *d_x = nullptr, *d_w = nullptr; - float *d_y = nullptr; - check(cudaMalloc(&d_x, x.size() * 2), "x"); - check(cudaMalloc(&d_w, w.size() * 2), "w"); - check(cudaMalloc(&d_y, (size_t) s.n_out * 4), "y"); - check(cudaMemcpy(d_x, x.data(), x.size() * 2, cudaMemcpyHostToDevice), "cx"); - check(cudaMemcpy(d_w, w.data(), w.size() * 2, cudaMemcpyHostToDevice), "cw"); - - std::vector naive((size_t) s.n_out), warp((size_t) s.n_out), split((size_t) s.n_out); - strata::kernels::bf16_gemv(d_x, d_w, d_y, s.n_in, s.n_out, nullptr); - check(cudaMemcpy(naive.data(), d_y, naive.size() * 4, cudaMemcpyDeviceToHost), "cy1"); - strata::kernels::bf16_gemv_split(d_x, d_w, d_y, s.n_in, s.n_out, 32, nullptr); - check(cudaMemcpy(warp.data(), d_y, warp.size() * 4, cudaMemcpyDeviceToHost), "cy2"); - strata::kernels::bf16_gemv_split(d_x, d_w, d_y, s.n_in, s.n_out, 256, nullptr); - check(cudaMemcpy(split.data(), d_y, split.size() * 4, cudaMemcpyDeviceToHost), "cy3"); - - const double rn = rel_l1(want, naive), rw = rel_l1(want, warp), rs = rel_l1(want, split); - std::printf(" %-34s naive %.2e warp %.2e split256 %.2e\n", s.what, rn, rw, rs); - // The products are EXACT - both sides are bf16-valued, so f32 represents each product exactly - and - // the only difference is the order the 2560 terms are added. A tight bound is therefore meaningful. - if (!(rn <= 1e-5 && rw <= 1e-5 && rs <= 1e-5)) { std::printf(" *** over 1e-5 ***\n"); ++bad; } - - // ---- 3. THE ACTIVATION CONTRACT. The rival: an fp16 activation instead of bf16, which is what the - // engine did before the contract was settled. It must be observable, or check 1 above would pass - // against either and the contract would be untested. - { - std::vector fp16_as_f32((size_t) s.n_in); - std::vector x16((size_t) s.n_in); - for (size_t i = 0; i < fx.size(); ++i) { - x16[i] = strata::kernels::f16_from_f32(fx[i]); - fp16_as_f32[i] = strata::kernels::f32_from_f16(x16[i]); - } - // Round the fp16 value to bf16 - i.e. give the kernel a bf16 activation whose VALUES came through - // fp16. That is the whole difference between the two contracts at this call site. - for (size_t i = 0; i < fp16_as_f32.size(); ++i) x[i] = bf16_from_f32(fp16_as_f32[i]); - check(cudaMemcpy(d_x, x.data(), x.size() * 2, cudaMemcpyHostToDevice), "cx2"); - std::vector rival((size_t) s.n_out); - strata::kernels::bf16_gemv(d_x, d_w, d_y, s.n_in, s.n_out, nullptr); - check(cudaMemcpy(rival.data(), d_y, rival.size() * 4, cudaMemcpyDeviceToHost), "cy4"); - const double r = rel_l1(want, rival); - const bool visible = r > 1e-4; - std::printf(" %-30s %s (%.4f%% apart)\n", "bf16 vs fp16 activation", - visible ? "yes" : "*** NO ***", r * 100); - if (!visible) ++bad; - } - cudaFree(d_x); cudaFree(d_w); cudaFree(d_y); - } - - std::printf("\nbf16_gemv: %d failures\n", bad); - if (bad) return 1; - if (selftest) std::printf("bf16_gemv_parity OK\n"); - return 0; -} diff --git a/src/kernels/cpu/expert.cpp b/src/kernels/cpu/expert.cpp deleted file mode 100644 index 045e3d5..0000000 --- a/src/kernels/cpu/expert.cpp +++ /dev/null @@ -1,683 +0,0 @@ -// src/kernels/cpu/expert.cpp - P2.S3: the Q2_0 expert kernel, promoted from bench/micro/cpu_s2.cpp. -// -// The body is the validated kernel, moved rather than rewritten: it carries the P0.T2 parity result -// (rel 1.461e-06 against the ggml formula) and the three performance findings recorded in -// include/strata/kernels/cpu/expert.hpp. Read that header first; it says why each piece is shaped this way. -#include "strata/kernels/cpu/expert.hpp" - -#include -#if defined(_MSC_VER) -#include -#else -#include -#endif - -#include -#include -#include -#include -#include - -namespace strata::kernels::cpu { -namespace { - -std::atomic oracle_q8_0{false}; - -/// fp16 -> fp32, written out rather than using `_cvtsh_ss`, because the F16C intrinsic's behaviour on -/// subnormals is the one place the two can differ and the scales in this artifact are small. -inline float h2f(const uint8_t* p) { - uint16_t h; - std::memcpy(&h, p, 2); - const uint32_t sign = (uint32_t) (h >> 15) & 1u; - uint32_t exp = (h >> 10) & 0x1Fu, man = h & 0x3FFu, f; - if (exp == 0) { - if (man == 0) { - f = sign << 31; - } else { - exp = 127 - 15 + 1; - while (!(man & 0x400u)) { man <<= 1; --exp; } - man &= 0x3FFu; - f = (sign << 31) | (exp << 23) | (man << 13); - } - } else if (exp == 31) { - f = (sign << 31) | 0x7F800000u | (man << 13); - } else { - f = (sign << 31) | ((exp - 15 + 127) << 23) | (man << 13); - } - float out; - std::memcpy(&out, &f, 4); - return out; -} - -// The x86 Q8_0 quantization and generic Q2_0 dot sequences are adapted from llama.cpp -// 3cf03257f219afbe7334045ff7c6a06ac68c627d, -// ggml/src/ggml-cpu/arch/x86/quants.c: quantize_row_q8_0 and -// ggml/src/ggml-cpu/quants.c: ggml_vec_dot_q2_0_q8_0_generic. -// -// MIT License -// Copyright (c) 2023-2026 The ggml authors -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -void quantize_oracle_q8_0(const float* x, int n, ActQ& a) { - a.nchunks = n / QKA; - for (int chunk = 0; chunk < a.nchunks; ++chunk) { - const float* xb = x + chunk * QKA; - __m256 v0 = _mm256_loadu_ps(xb); - __m256 v1 = _mm256_loadu_ps(xb + 8); - __m256 v2 = _mm256_loadu_ps(xb + 16); - __m256 v3 = _mm256_loadu_ps(xb + 24); - const __m256 sign = _mm256_set1_ps(-0.0f); - __m256 maximum = _mm256_andnot_ps(sign, v0); - maximum = _mm256_max_ps(maximum, _mm256_andnot_ps(sign, v1)); - maximum = _mm256_max_ps(maximum, _mm256_andnot_ps(sign, v2)); - maximum = _mm256_max_ps(maximum, _mm256_andnot_ps(sign, v3)); - __m128 max4 = _mm_max_ps(_mm256_extractf128_ps(maximum, 1), _mm256_castps256_ps128(maximum)); - max4 = _mm_max_ps(max4, _mm_movehl_ps(max4, max4)); - max4 = _mm_max_ss(max4, _mm_movehdup_ps(max4)); - const float amax = _mm_cvtss_f32(max4); - const float d = amax / 127.0f; - const uint16_t half_d = (uint16_t) _mm_cvtsi128_si32(_mm_cvtps_ph(_mm_set_ss(d), 0)); - const __m256 inverse = _mm256_set1_ps(amax != 0.0f ? 127.0f / amax : 0.0f); - v0 = _mm256_round_ps(_mm256_mul_ps(v0, inverse), _MM_FROUND_TO_NEAREST_INT); - v1 = _mm256_round_ps(_mm256_mul_ps(v1, inverse), _MM_FROUND_TO_NEAREST_INT); - v2 = _mm256_round_ps(_mm256_mul_ps(v2, inverse), _MM_FROUND_TO_NEAREST_INT); - v3 = _mm256_round_ps(_mm256_mul_ps(v3, inverse), _MM_FROUND_TO_NEAREST_INT); - __m256i i0 = _mm256_packs_epi32(_mm256_cvtps_epi32(v0), _mm256_cvtps_epi32(v1)); - const __m256i i2 = _mm256_packs_epi32(_mm256_cvtps_epi32(v2), _mm256_cvtps_epi32(v3)); - i0 = _mm256_packs_epi16(i0, i2); - i0 = _mm256_permutevar8x32_epi32(i0, _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7)); - int8_t* q = a.q + chunk * QKA; - _mm256_storeu_si256((__m256i*) q, i0); - int32_t sum = 0; - for (int j = 0; j < QKA; ++j) sum += q[j]; - a.scale[chunk] = h2f((const uint8_t*) &half_d); - a.sum[chunk] = sum; - a.hx[chunk] = a.scale[chunk] * float(sum); - } -} - -/// 2-bit unpack via VPMULTISHIFTQB. -/// -/// ARGUMENT ORDER IS (control, data) AND WAS DETERMINED EMPIRICALLY (`bench/micro/probe_multishift.cpp`). -/// The Intel guide states (a=data, b=control); using that produced 43 of 64 wrong codes. `plan.md`'s sketch -/// passes the shift pattern first, which is correct - so a "fix" that swapped it to match the guide was the -/// bug, not the fix. Within each 64-bit lane, output byte i is `(u16 >> 2i) & 0xFF`, so AND 3 yields the -/// eight 2-bit codes in order. -/// -/// The result is the 32 codes of ONE ACTIVATION CHUNK (4 qword lanes), which is the unit the Q8_1 scale is -/// defined on - not the 64-weight block. -inline __m256i unpack_q2_0(const uint8_t* codes) { - const __m128i packed = _mm_loadl_epi64((const __m128i*) codes); // 8 bytes -> 4 u16 in the low half - const __m256i lanes = _mm256_cvtepu16_epi64(packed); // 4 qwords, 8 codes each - const __m256i ctrl = _mm256_set1_epi64x((long long) 0x0E0C0A0806040200ULL); - return _mm256_and_si256(_mm256_multishift_epi64_epi8(ctrl, lanes), _mm256_set1_epi8(3)); -} - -/// 32 codes against 32 int8 activations. Codes 0 contribute nothing to `sum(c*xhat)`, so the zero lanes the -/// narrow load leaves behind are harmless. -inline __m256i block_dot(const uint8_t* codes, const int8_t* xq) { - return _mm256_dpbusd_epi32(_mm256_setzero_si256(), unpack_q2_0(codes), - _mm256_load_si256((const __m256i*) xq)); -} - -inline float hsum_ps(__m256 v) { - const __m128 s = _mm_add_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps(v, 1)); - return _mm_cvtss_f32(_mm_hadd_ps(_mm_hadd_ps(s, s), s)); -} - -// ================================ plan v0.3 P6: the row dot in 512-bit lanes ================================ -// -// The 256-bit row dot below spent ~12 cycles per 64-weight block: two unpacks, two VNNI dots, two converts, two -// scalar scale products broadcast into two FMAs, an fp16 conversion and a scalar correction - compute-bound at -// ~39 GB/s while the machine streams 52. Here a block is ONE unpack (16 code bytes -> 64 codes), ONE VNNI dot -// over 64 activations, ONE convert and ONE FMA whose per-chunk scales come from a permute of a vector of scale -// products built for eight blocks at a time; the weight-independent correction is one FMA per eight blocks. -// The sum order differs from the 256-bit kernel (last-bit differences); the verify window and plain decode both -// use this kernel, so speculative decode still reproduces plain decode exactly. -static const bool kZmm = std::getenv("STRATA_CPU_YMM") == nullptr; - -inline __m512i unpack64_q2_0(const uint8_t* codes) { - const __m128i packed = _mm_loadu_si128((const __m128i*) codes); // 8 u16 = 64 codes - const __m512i lanes = _mm512_cvtepu16_epi64(packed); // 8 qwords, 8 codes each - const __m512i ctrl = _mm512_set1_epi64((long long) 0x0E0C0A0806040200ULL); - return _mm512_and_si512(_mm512_multishift_epi64_epi8(ctrl, lanes), _mm512_set1_epi8(3)); -} - -// For blocks [b0, b0+nb) (nb <= 8): p[2i+h] = d_{b0+i} * xscale[2(b0+i)+h], dd[2i+h] = d_{b0+i}. -inline void scales8(const uint8_t* wscales, const ActQ& a, int b0, int nb, __m512& p, __m512& dd) { - const __mmask8 m8 = nb >= 8 ? (__mmask8) 0xFF : (__mmask8) ((1u << nb) - 1u); - const __m128i h = _mm_maskz_loadu_epi16(m8, wscales + 2 * b0); - const __m512 d8 = _mm512_castps256_ps512(_mm256_cvtph_ps(h)); - const __m512i dup = _mm512_setr_epi32(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7); - dd = _mm512_permutexvar_ps(dup, d8); - const __mmask16 m16 = nb >= 8 ? (__mmask16) 0xFFFF : (__mmask16) ((1u << (2 * nb)) - 1u); - dd = _mm512_maskz_mov_ps(m16, dd); - p = _mm512_mul_ps(dd, _mm512_maskz_loadu_ps(m16, a.scale + 2 * b0)); -} - -inline float row_dot_z(const uint8_t* codes, const uint8_t* scales, const ActQ& a, int nblocks) { - __m512 acc = _mm512_setzero_ps(), corr = _mm512_setzero_ps(); - const __m512i base = _mm512_setr_epi32(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1); - for (int b0 = 0; b0 < nblocks; b0 += 8) { - const int nb = nblocks - b0 < 8 ? nblocks - b0 : 8; - __m512 p, dd; - scales8(scales, a, b0, nb, p, dd); - const __mmask16 m16 = nb >= 8 ? (__mmask16) 0xFFFF : (__mmask16) ((1u << (2 * nb)) - 1u); - corr = _mm512_fmadd_ps(dd, _mm512_maskz_loadu_ps(m16, a.hx + 2 * b0), corr); - for (int i = 0; i < nb; ++i) { - const int b = b0 + i; - const __m512i dot = _mm512_dpbusd_epi32(_mm512_setzero_si512(), unpack64_q2_0(codes + b * 16), - _mm512_load_si512((const void*) (a.q + b * QK))); - const __m512 sv = _mm512_permutexvar_ps(_mm512_add_epi32(base, _mm512_set1_epi32(2 * i)), p); - acc = _mm512_fmadd_ps(sv, _mm512_cvtepi32_ps(dot), acc); - } - } - return _mm512_reduce_add_ps(acc) - _mm512_reduce_add_ps(corr); -} - -template -inline void row_dot_multi_z(const uint8_t* codes, const uint8_t* scales, const ActQ* const* a, int nblocks, - float* res) { - __m512 acc[NT], corr[NT]; - for (int t = 0; t < NT; ++t) { acc[t] = _mm512_setzero_ps(); corr[t] = _mm512_setzero_ps(); } - const __m512i base = _mm512_setr_epi32(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1); - for (int b0 = 0; b0 < nblocks; b0 += 8) { - const int nb = nblocks - b0 < 8 ? nblocks - b0 : 8; - const __mmask16 m16 = nb >= 8 ? (__mmask16) 0xFFFF : (__mmask16) ((1u << (2 * nb)) - 1u); - __m512 p[NT]; - for (int t = 0; t < NT; ++t) { - __m512 dd; - scales8(scales, *a[t], b0, nb, p[t], dd); - corr[t] = _mm512_fmadd_ps(dd, _mm512_maskz_loadu_ps(m16, a[t]->hx + 2 * b0), corr[t]); - } - for (int i = 0; i < nb; ++i) { - const int b = b0 + i; - const __m512i w = unpack64_q2_0(codes + b * 16); - const __m512i idx = _mm512_add_epi32(base, _mm512_set1_epi32(2 * i)); - for (int t = 0; t < NT; ++t) { - const __m512i dot = _mm512_dpbusd_epi32(_mm512_setzero_si512(), w, - _mm512_load_si512((const void*) (a[t]->q + b * QK))); - acc[t] = _mm512_fmadd_ps(_mm512_permutexvar_ps(idx, p[t]), _mm512_cvtepi32_ps(dot), acc[t]); - } - } - } - for (int t = 0; t < NT; ++t) res[t] = _mm512_reduce_add_ps(acc[t]) - _mm512_reduce_add_ps(corr[t]); -} - -/// One weight row against a quantized activation. -/// -/// sum_j (c_j - 1) d_w xhat_j d_x == d_w * ( d_x*sum(c*xhat) - d_x*sum(xhat) ) -/// -/// split per 32-chunk because `d_x` changes at the chunk boundary while `d_w` does not. -/// -/// The accumulator stays a FLOAT VECTOR for the whole row and is reduced once at the end. Reducing per -/// 64-weight block (two 8-lane horizontal sums: a store plus 16 scalar adds) cost far more than the dot -/// products themselves - it made the kernel compute-bound at 21 GB/s instead of DRAM-bound at 32. -inline float row_dot(const uint8_t* codes, const uint8_t* scales, const ActQ& a, int nblocks) { - if (kZmm) return row_dot_z(codes, scales, a, nblocks); - __m256 acc = _mm256_setzero_ps(); - // The -sum(xhat) term is a SCALAR: broadcasting it into all 8 lanes and letting hsum_ps add them would - // apply it eight times per block. - float corr = 0.f; - for (int b = 0; b < nblocks; ++b) { - const float d = h2f(scales + 2 * b); - const __m256 slo = _mm256_cvtepi32_ps(block_dot(codes + b * 16, a.q + b * QK)); - const __m256 shi = _mm256_cvtepi32_ps(block_dot(codes + b * 16 + 8, a.q + b * QK + QKA)); - acc = _mm256_fmadd_ps(_mm256_set1_ps(d * a.scale[2 * b]), slo, acc); - acc = _mm256_fmadd_ps(_mm256_set1_ps(d * a.scale[2 * b + 1]), shi, acc); - corr += d * (a.hx[2 * b] + a.hx[2 * b + 1]); - } - return hsum_ps(acc) - corr; -} - -// VNNI's integer partial sums are exact. Remove the Q2_0 code offset BEFORE -// conversion to float, then follow the pinned generic CPU dot's two-chunk and -// per-64-block reduction. Its x86 type trait selects this generic reduction even -// in the AVX-512 oracle build. The legacy eight-lane FP32 reduction above has a -// different rounding order and remains the default. -inline int chunk_dot_oracle(const uint8_t* codes, const int8_t* q, int sum) { - const __m256i lanes = block_dot(codes, q); - const __m128i halves = _mm_add_epi32(_mm256_castsi256_si128(lanes), _mm256_extracti128_si256(lanes, 1)); - const __m128i pairs = _mm_hadd_epi32(halves, halves); - return _mm_cvtsi128_si32(_mm_hadd_epi32(pairs, pairs)) - sum; -} - -inline float row_dot_oracle(const uint8_t* codes, const uint8_t* scales, const ActQ& a, int nblocks) { - float result = 0.0f; - for (int b = 0; b < nblocks; ++b) { - float block = 0.0f; - for (int half = 0; half < 2; ++half) { - const int chunk = 2 * b + half; - const int dot = chunk_dot_oracle(codes + b * 16 + half * 8, a.q + chunk * QKA, a.sum[chunk]); - block += a.scale[chunk] * float(dot); - } - result += h2f(scales + 2 * b) * block; - } - return result; -} - -/// `row_dot` for NT activations at once: the codes of each block are unpacked once, and each token's -/// accumulator sees exactly the operations `row_dot` would apply to it, in the same order. -template -inline void row_dot_multi(const uint8_t* codes, const uint8_t* scales, const ActQ* const* a, int nblocks, - float* res) { - if (kZmm) { row_dot_multi_z(codes, scales, a, nblocks, res); return; } - __m256 acc[NT]; - float corr[NT]; - for (int t = 0; t < NT; ++t) { acc[t] = _mm256_setzero_ps(); corr[t] = 0.f; } - for (int b = 0; b < nblocks; ++b) { - const float d = h2f(scales + 2 * b); - const __m256i lo = unpack_q2_0(codes + b * 16); - const __m256i hi = unpack_q2_0(codes + b * 16 + 8); - for (int t = 0; t < NT; ++t) { - const __m256 slo = _mm256_cvtepi32_ps( - _mm256_dpbusd_epi32(_mm256_setzero_si256(), lo, _mm256_load_si256((const __m256i*) (a[t]->q + b * QK)))); - const __m256 shi = _mm256_cvtepi32_ps( - _mm256_dpbusd_epi32(_mm256_setzero_si256(), hi, - _mm256_load_si256((const __m256i*) (a[t]->q + b * QK + QKA)))); - acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d * a[t]->scale[2 * b]), slo, acc[t]); - acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d * a[t]->scale[2 * b + 1]), shi, acc[t]); - corr[t] += d * (a[t]->hx[2 * b] + a[t]->hx[2 * b + 1]); - } - } - for (int t = 0; t < NT; ++t) res[t] = hsum_ps(acc[t]) - corr[t]; -} - -template -void expert_multi(const uint8_t* blob, const ActQ* const* a1, float* const* out, ExpertScratchMulti& ws) { - float g[NT], u[NT]; - for (int r = 0; r < FF; ++r) { - row_dot_multi(blob + O_GU_CODES + (size_t) (2 * r) * ROW_GU, - blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2, a1, SC_GU, g); - row_dot_multi(blob + O_GU_CODES + (size_t) (2 * r + 1) * ROW_GU, - blob + O_GU_SCALES + (size_t) (2 * r + 1) * SC_GU * 2, a1, SC_GU, u); - for (int t = 0; t < NT; ++t) ws.ff[t][r] = (g[t] / (1.f + std::exp(-g[t]))) * u[t]; - } - const ActQ* a2[NT]; - for (int t = 0; t < NT; ++t) { - act_quant_q8_1(ws.ff[t], FF, ws.a2[t]); - a2[t] = &ws.a2[t]; - } - float o[NT]; - for (int r = 0; r < H; ++r) { - row_dot_multi(blob + O_D_CODES + (size_t) r * ROW_D, blob + O_D_SCALES + (size_t) r * SC_D * 2, a2, - SC_D, o); - for (int t = 0; t < NT; ++t) out[t][r] = o[t]; - } -} - -void expert_oracle_q8_0(const uint8_t* blob, const ActQ& a1, float* out, ExpertScratch& ws) { - for (int r = 0; r < FF; ++r) { - const float g = row_dot_oracle(blob + O_GU_CODES + size_t(2 * r) * ROW_GU, - blob + O_GU_SCALES + size_t(2 * r) * SC_GU * 2, a1, SC_GU); - const float u = row_dot_oracle(blob + O_GU_CODES + size_t(2 * r + 1) * ROW_GU, - blob + O_GU_SCALES + size_t(2 * r + 1) * SC_GU * 2, a1, SC_GU); - ws.ff[r] = (g / (1.f + std::exp(-g))) * u; - } - quantize_oracle_q8_0(ws.ff, FF, ws.a2); - for (int r = 0; r < H; ++r) - out[r] = row_dot_oracle(blob + O_D_CODES + size_t(r) * ROW_D, - blob + O_D_SCALES + size_t(r) * SC_D * 2, ws.a2, SC_D); -} - -} // namespace - -const char* CpuFeatures::reason() const { - if (usable()) return "ok"; - // Named individually: "AVX-512 not supported" sends a user looking for a new CPU when the machine may have - // AVX-512F and be missing only VNNI, which is a much narrower and more explicable gap. - static char buf[160]; - std::snprintf(buf, sizeof buf, "missing %s%s%s%s%s", avx512f ? "" : "AVX512F ", - avx512bw ? "" : "AVX512BW ", avx512vl ? "" : "AVX512VL ", - avx512_vnni ? "" : "AVX512-VNNI ", avx512_vbmi ? "" : "AVX512-VBMI"); - return buf; -} - -CpuFeatures cpu_features() { - CpuFeatures f; - int reg[4] = {0, 0, 0, 0}; -#if defined(_MSC_VER) - __cpuid(reg, 0); - if (reg[0] < 7) return f; - __cpuidex(reg, 7, 0); -#else - unsigned r[4] = {0, 0, 0, 0}; - __cpuid_count(0, 0, r[0], r[1], r[2], r[3]); - if (r[0] < 7) return f; - __cpuid_count(7, 0, r[0], r[1], r[2], r[3]); - for (int i = 0; i < 4; ++i) reg[i] = (int) r[i]; -#endif - const unsigned ebx = (unsigned) reg[1], ecx = (unsigned) reg[2]; - f.avx512f = (ebx >> 16) & 1u; - f.avx512bw = (ebx >> 30) & 1u; - f.avx512vl = (ebx >> 31) & 1u; - f.avx512_vnni = (ecx >> 11) & 1u; - f.avx512_vbmi = (ecx >> 1) & 1u; - return f; -} - -void cpu_require_expert_support() { - const CpuFeatures f = cpu_features(); - if (f.usable()) return; - std::fprintf(stderr, - "strata: this CPU cannot run the expert kernel: %s.\n" - " The engine needs AVX512-VNNI and AVX512-VBMI (Intel Ice Lake / AMD Zen 4 or newer).\n" - " The scalar fallback exists for tests only and is far too slow to decode with.\n", - f.reason()); - std::exit(1); -} - -void act_quant_q8_1(const float* x, int n, ActQ& a) { - if (oracle_q8_0.load(std::memory_order_relaxed)) { - quantize_oracle_q8_0(x, n, a); - return; - } - a.nchunks = n / QKA; - // Plan v0.3 P6: AVX-512, the same operations per element as the scalar loop below (max of |x|, one multiply, - // +-0.5 away from zero, truncation, clamp), so the result is bitwise the scalar one. The scalar loop took - // ~22 us per 2560 values - 3.2 ms of every speculative round. - { - const __m512 half = _mm512_set1_ps(0.5f), mhalf = _mm512_set1_ps(-0.5f), zero = _mm512_setzero_ps(); - const __m512i lo = _mm512_set1_epi32(-127), hi = _mm512_set1_epi32(127); - const __m512 absmask = _mm512_castsi512_ps(_mm512_set1_epi32(0x7fffffff)); - for (int k = 0; k < a.nchunks; ++k) { - const float* xb = x + k * QKA; - const __m512 x0 = _mm512_loadu_ps(xb), x1 = _mm512_loadu_ps(xb + 16); - const float amax = _mm512_reduce_max_ps(_mm512_max_ps(_mm512_and_ps(x0, absmask), _mm512_and_ps(x1, absmask))); - const float s = amax > 0.f ? amax / 127.f : 0.f; - const float inv = s > 0.f ? 1.f / s : 0.f; - const __m512 vinv = _mm512_set1_ps(inv); - const __m512 t0 = _mm512_mul_ps(x0, vinv), t1 = _mm512_mul_ps(x1, vinv); - const __m512 r0 = _mm512_add_ps(t0, _mm512_mask_blend_ps(_mm512_cmp_ps_mask(t0, zero, _CMP_GE_OQ), mhalf, half)); - const __m512 r1 = _mm512_add_ps(t1, _mm512_mask_blend_ps(_mm512_cmp_ps_mask(t1, zero, _CMP_GE_OQ), mhalf, half)); - __m512i v0 = _mm512_cvttps_epi32(r0), v1 = _mm512_cvttps_epi32(r1); - v0 = _mm512_min_epi32(_mm512_max_epi32(v0, lo), hi); - v1 = _mm512_min_epi32(_mm512_max_epi32(v1, lo), hi); - _mm_storeu_si128((__m128i*) (a.q + k * QKA), _mm512_cvtepi32_epi8(v0)); - _mm_storeu_si128((__m128i*) (a.q + k * QKA + 16), _mm512_cvtepi32_epi8(v1)); - const int32_t sum = _mm512_reduce_add_epi32(_mm512_add_epi32(v0, v1)); - a.scale[k] = s; - a.sum[k] = sum; - a.hx[k] = s * (float) sum; - } - return; - } - for (int k = 0; k < a.nchunks; ++k) { - const float* xb = x + k * QKA; - float amax = 0.f; - for (int j = 0; j < QKA; ++j) amax = std::fmax(amax, std::fabs(xb[j])); - const float s = amax > 0.f ? amax / 127.f : 0.f; - const float inv = s > 0.f ? 1.f / s : 0.f; - int32_t sum = 0; - int8_t* q = a.q + k * QKA; - for (int j = 0; j < QKA; ++j) { - // **`std::lround` IS A FUNCTION CALL AND IT COST 51 us PER LAYER.** Measured: quantizing 2560 - // floats took 51.3 us - 20 ns per element, about 60 cycles for a fabs, a multiply and a round. - // `lround` respects the current rounding mode, so MSVC cannot inline it to a single instruction - // and emits a call per element. 48 layers x 51.3 us = 2.46 ms/token, which is 8.6% of the whole - // CPU expert term and is pure overhead. - // - // `t + copysign(0.5, t)` is EXACTLY `lround`'s rule - round half AWAY FROM ZERO - and it is - // branchless and vectorizable. It is NOT `_mm256_round_ps`, which rounds half to EVEN and would - // quietly change the activation on the ties. The cast is safe because `|t| <= 127` by construction - // (`s = amax/127`, so `|x_j|/s <= 127`), well inside int32. - const float t = xb[j] * inv; - const float r = t + (t >= 0.f ? 0.5f : -0.5f); - int v = (int) r; - v = v < -127 ? -127 : (v > 127 ? 127 : v); - q[j] = (int8_t) v; - sum += v; - } - a.scale[k] = s; - a.sum[k] = sum; - a.hx[k] = s * (float) sum; - } -} - -void expert_set_oracle_q8_0(bool enabled) { - oracle_q8_0.store(enabled, std::memory_order_relaxed); -} - -void s2_expert_vnni(const uint8_t* blob, const float* x, float* out, ExpertScratch& ws) { - act_quant_q8_1(x, H, ws.a1); - s2_expert_vnni_q(blob, ws.a1, out, ws); -} - -void s2_expert_vnni_q(const uint8_t* blob, const ActQ& a1, float* out, ExpertScratch& ws) { - if (oracle_q8_0.load(std::memory_order_relaxed)) { - expert_oracle_q8_0(blob, a1, out, ws); - return; - } - for (int r = 0; r < FF; ++r) { - const float g = row_dot(blob + O_GU_CODES + (size_t) (2 * r) * ROW_GU, - blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2, a1, SC_GU); - const float u = row_dot(blob + O_GU_CODES + (size_t) (2 * r + 1) * ROW_GU, - blob + O_GU_SCALES + (size_t) (2 * r + 1) * SC_GU * 2, a1, SC_GU); - // SiLU on the GATE, multiplied by up - the same reading `docs/semantics.md` records for the shared - // expert, and the one that is wrong the other way round in a way that still produces a number. - ws.ff[r] = (g / (1.f + std::exp(-g))) * u; - } - act_quant_q8_1(ws.ff, FF, ws.a2); - for (int r = 0; r < H; ++r) - out[r] = row_dot(blob + O_D_CODES + (size_t) r * ROW_D, - blob + O_D_SCALES + (size_t) r * SC_D * 2, ws.a2, SC_D); -} - -bool expert_oracle_q8_0_enabled() { return oracle_q8_0.load(std::memory_order_relaxed); } - -void s2_expert_gu_rows(const uint8_t* blob, const ActQ& a1, float* ff, int r0, int r1) { - for (int r = r0; r < r1; ++r) { - const float g = row_dot(blob + O_GU_CODES + (size_t) (2 * r) * ROW_GU, - blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2, a1, SC_GU); - const float u = row_dot(blob + O_GU_CODES + (size_t) (2 * r + 1) * ROW_GU, - blob + O_GU_SCALES + (size_t) (2 * r + 1) * SC_GU * 2, a1, SC_GU); - ff[r] = (g / (1.f + std::exp(-g))) * u; - } -} - -void s2_expert_down_rows(const uint8_t* blob, const ActQ& a2, float* out, int r0, int r1) { - for (int r = r0; r < r1; ++r) - out[r] = row_dot(blob + O_D_CODES + (size_t) r * ROW_D, blob + O_D_SCALES + (size_t) r * SC_D * 2, a2, SC_D); -} - -namespace { -template -void gu_rows_multi(const uint8_t* blob, const ActQ* const* a1, float* const* ff, int r0, int r1) { - float g[NT], u[NT]; - for (int r = r0; r < r1; ++r) { - row_dot_multi(blob + O_GU_CODES + (size_t) (2 * r) * ROW_GU, - blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2, a1, SC_GU, g); - row_dot_multi(blob + O_GU_CODES + (size_t) (2 * r + 1) * ROW_GU, - blob + O_GU_SCALES + (size_t) (2 * r + 1) * SC_GU * 2, a1, SC_GU, u); - for (int t = 0; t < NT; ++t) ff[t][r] = (g[t] / (1.f + std::exp(-g[t]))) * u[t]; - } -} -template -void down_rows_multi(const uint8_t* blob, const ActQ* const* a2, float* const* out, int r0, int r1) { - float o[NT]; - for (int r = r0; r < r1; ++r) { - row_dot_multi(blob + O_D_CODES + (size_t) r * ROW_D, blob + O_D_SCALES + (size_t) r * SC_D * 2, a2, - SC_D, o); - for (int t = 0; t < NT; ++t) out[t][r] = o[t]; - } -} -} // namespace - -void s2_expert_gu_rows_multi(const uint8_t* blob, const ActQ* const* a1, int n_tokens, float* const* ff, int r0, - int r1) { - switch (n_tokens) { - case 1: gu_rows_multi<1>(blob, a1, ff, r0, r1); break; - case 2: gu_rows_multi<2>(blob, a1, ff, r0, r1); break; - case 3: gu_rows_multi<3>(blob, a1, ff, r0, r1); break; - case 4: gu_rows_multi<4>(blob, a1, ff, r0, r1); break; - case 5: gu_rows_multi<5>(blob, a1, ff, r0, r1); break; - case 6: gu_rows_multi<6>(blob, a1, ff, r0, r1); break; - case 7: gu_rows_multi<7>(blob, a1, ff, r0, r1); break; - default: gu_rows_multi<8>(blob, a1, ff, r0, r1); break; - } -} - -void s2_expert_down_rows_multi(const uint8_t* blob, const ActQ* const* a2, int n_tokens, float* const* out, int r0, - int r1) { - switch (n_tokens) { - case 1: down_rows_multi<1>(blob, a2, out, r0, r1); break; - case 2: down_rows_multi<2>(blob, a2, out, r0, r1); break; - case 3: down_rows_multi<3>(blob, a2, out, r0, r1); break; - case 4: down_rows_multi<4>(blob, a2, out, r0, r1); break; - case 5: down_rows_multi<5>(blob, a2, out, r0, r1); break; - case 6: down_rows_multi<6>(blob, a2, out, r0, r1); break; - case 7: down_rows_multi<7>(blob, a2, out, r0, r1); break; - default: down_rows_multi<8>(blob, a2, out, r0, r1); break; - } -} - -// ================================ plan v0.3 P6: Q2_0 rows in the GGUF block layout ================================ -// -// The IQ model files keep their down projections in Q2_0 GGUF blocks (fp16 d, then 16 code bytes: 18 bytes per -// 64 weights, interleaved), which ggml-cpu computes with a scalar loop on x86. This is `row_dot_multi_z` with -// the block stride of the GGUF layout: the same unpack, the same VNNI dot, the same correction. -namespace { -template -inline void q2g_row_multi(const uint8_t* row, const ActQ* const* a, int nblocks, float* res) { - __m512 acc[NT], corr[NT]; - for (int t = 0; t < NT; ++t) { acc[t] = _mm512_setzero_ps(); corr[t] = _mm512_setzero_ps(); } - const __m512i base = _mm512_setr_epi32(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1); - const __m512i dup = _mm512_setr_epi32(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7); - for (int b0 = 0; b0 < nblocks; b0 += 8) { - const int nb = nblocks - b0 < 8 ? nblocks - b0 : 8; - const __mmask16 m16 = nb >= 8 ? (__mmask16) 0xFFFF : (__mmask16) ((1u << (2 * nb)) - 1u); - alignas(16) uint16_t sc[8] = {0, 0, 0, 0, 0, 0, 0, 0}; - for (int i = 0; i < nb; ++i) std::memcpy(&sc[i], row + (size_t) (b0 + i) * 18, 2); - const __m512 d8 = _mm512_castps256_ps512(_mm256_cvtph_ps(_mm_load_si128((const __m128i*) sc))); - const __m512 dd = _mm512_maskz_mov_ps(m16, _mm512_permutexvar_ps(dup, d8)); - __m512 p[NT]; - for (int t = 0; t < NT; ++t) { - p[t] = _mm512_mul_ps(dd, _mm512_maskz_loadu_ps(m16, a[t]->scale + 2 * b0)); - corr[t] = _mm512_fmadd_ps(dd, _mm512_maskz_loadu_ps(m16, a[t]->hx + 2 * b0), corr[t]); - } - for (int i = 0; i < nb; ++i) { - const int b = b0 + i; - const __m512i w = unpack64_q2_0(row + (size_t) b * 18 + 2); - const __m512i idx = _mm512_add_epi32(base, _mm512_set1_epi32(2 * i)); - for (int t = 0; t < NT; ++t) { - const __m512i dot = _mm512_dpbusd_epi32(_mm512_setzero_si512(), w, - _mm512_load_si512((const void*) (a[t]->q + b * QK))); - acc[t] = _mm512_fmadd_ps(_mm512_permutexvar_ps(idx, p[t]), _mm512_cvtepi32_ps(dot), acc[t]); - } - } - } - for (int t = 0; t < NT; ++t) res[t] = _mm512_reduce_add_ps(acc[t]) - _mm512_reduce_add_ps(corr[t]); -} -template -void q2g_rows(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, float* const* out, int r0, int r1) { - float res[NT]; - for (int r = r0; r < r1; ++r) { - q2g_row_multi(w + (size_t) r * row_bytes, a, nblocks, res); - for (int t = 0; t < NT; ++t) out[t][r] = res[t]; - } -} -} // namespace - -void q2_0_gguf_rows_multi(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, - float* const* out, int r0, int r1) { - switch (nt) { - case 1: q2g_rows<1>(w, row_bytes, nblocks, a, out, r0, r1); break; - case 2: q2g_rows<2>(w, row_bytes, nblocks, a, out, r0, r1); break; - case 3: q2g_rows<3>(w, row_bytes, nblocks, a, out, r0, r1); break; - case 4: q2g_rows<4>(w, row_bytes, nblocks, a, out, r0, r1); break; - case 5: q2g_rows<5>(w, row_bytes, nblocks, a, out, r0, r1); break; - case 6: q2g_rows<6>(w, row_bytes, nblocks, a, out, r0, r1); break; - case 7: q2g_rows<7>(w, row_bytes, nblocks, a, out, r0, r1); break; - default: q2g_rows<8>(w, row_bytes, nblocks, a, out, r0, r1); break; - } -} - -void s2_expert_vnni_multi(const uint8_t* blob, const ActQ* const* a1, int n_tokens, float* const* out, - ExpertScratchMulti& ws) { - if (oracle_q8_0.load(std::memory_order_relaxed) || n_tokens < 1 || n_tokens > MAXT) { - for (int t = 0; t < n_tokens; ++t) s2_expert_vnni_q(blob, *a1[t], out[t], ws.single); - return; - } - switch (n_tokens) { - case 1: expert_multi<1>(blob, a1, out, ws); break; - case 2: expert_multi<2>(blob, a1, out, ws); break; - case 3: expert_multi<3>(blob, a1, out, ws); break; - case 4: expert_multi<4>(blob, a1, out, ws); break; - case 5: expert_multi<5>(blob, a1, out, ws); break; - case 6: expert_multi<6>(blob, a1, out, ws); break; - case 7: expert_multi<7>(blob, a1, out, ws); break; - default: expert_multi<8>(blob, a1, out, ws); break; - } -} - -void s2_expert_scalar(const uint8_t* blob, const float* x_in, float* out, bool quant_acts) { - // BOTH STAGES, which is what `quant_acts` promises and what `bench/micro/cpu_s2.cpp` does NOT do. - // - // The original's comment says the oracle "consume[s] the SAME INT8 activation values the VNNI path uses, - // at both stages", but its code quantizes only the INTERMEDIATE - the gate/up projections still see raw - // f32 `x`. Feeding it an already-quantized input (which is what the engine does) makes the two coincide - // and hides the discrepancy entirely; feeding it a raw f32 input makes the comparison one between two - // DIFFERENT computations, and the gap measured here was 1.19e-02 - three times P2.S3's tolerance, and - // read as a kernel bug when it was a fixture bug. - float xq[H]; - const float* x = x_in; - if (quant_acts) { - ActQ a1; - act_quant_q8_1(x_in, H, a1); - for (int i = 0; i < H; ++i) xq[i] = a1.scale[i / QKA] * (float) a1.q[i]; - x = xq; - } - float ff[FF]; - for (int r = 0; r < FF; ++r) { - const uint8_t* gc = blob + O_GU_CODES + (size_t) (2 * r) * ROW_GU; - const uint8_t* gs = blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2; - const uint8_t* uc = blob + O_GU_CODES + (size_t) (2 * r + 1) * ROW_GU; - const uint8_t* us = blob + O_GU_SCALES + (size_t) (2 * r + 1) * SC_GU * 2; - float sg = 0.f, su = 0.f; - for (int b = 0; b < SC_GU; ++b) { - const float dg = h2f(gs + 2 * b), du = h2f(us + 2 * b); - for (int j = 0; j < QK; ++j) { - const int o = b * QK + j; - sg += (float) (((gc[b * 16 + (j >> 2)] >> (2 * (j & 3))) & 3) - 1) * dg * x[o]; - su += (float) (((uc[b * 16 + (j >> 2)] >> (2 * (j & 3))) & 3) - 1) * du * x[o]; - } - } - ff[r] = (sg / (1.f + std::exp(-sg))) * su; - } - if (quant_acts) { - // Replace the exact intermediate with the INT8 values the VNNI path actually sees, so the two differ - // only by FP32 evaluation order. - ActQ a2; - act_quant_q8_1(ff, FF, a2); - for (int i = 0; i < FF; ++i) ff[i] = a2.scale[i / QKA] * (float) a2.q[i]; - } - for (int r = 0; r < H; ++r) { - const uint8_t* dc = blob + O_D_CODES + (size_t) r * ROW_D; - const uint8_t* ds = blob + O_D_SCALES + (size_t) r * SC_D * 2; - float acc = 0.f; - for (int b = 0; b < SC_D; ++b) { - const float d = h2f(ds + 2 * b); - for (int j = 0; j < QK; ++j) - acc += (float) (((dc[b * 16 + (j >> 2)] >> (2 * (j & 3))) & 3) - 1) * d * ff[b * QK + j]; - } - out[r] = acc; - } -} - -} // namespace strata::kernels::cpu diff --git a/src/kernels/cpu/expert_layout.cpp b/src/kernels/cpu/expert_layout.cpp deleted file mode 100644 index e28a3f8..0000000 --- a/src/kernels/cpu/expert_layout.cpp +++ /dev/null @@ -1,349 +0,0 @@ -// src/kernels/cpu/expert_layout.cpp - plan v0.3 P6: the per-layer expert table. See the header. -#include "strata/kernels/cpu/expert_layout.hpp" - -#include -#include -#include -#include -#if defined(_MSC_VER) -#include -#include -#else -#include -#endif -#include -#include - -namespace strata::kernels::cpu { -namespace { -ExpertLayout g_layout; -} - -const ExpertLayout& expert_layout() { return g_layout; } - -int cpu_isa_cap() { - // STRATA_FORCE_ISA (tests, the experimental older-CPU builds): the engine's own dispatch acts as if this CPU - // stopped at that level. ggml-cpu is not affected: it runs what the build compiled it for. - static const int cap = [] { - const char* f = std::getenv("STRATA_FORCE_ISA"); - if (f == nullptr || f[0] == '\0') return 3; - const std::string v(f); - if (v == "avx2") return 2; - if (v == "avx") return 1; - if (v == "sse" || v == "sse4.2" || v == "none") return 0; - std::fprintf(stderr, "strata: STRATA_FORCE_ISA=%s is not avx2, avx or sse; ignored\n", f); - return 3; - }(); - return cap; -} - -bool cpu_avx512_ok() { - static const bool ok = [] { - if (const char* f = std::getenv("STRATA_FORCE_AVX2"); f != nullptr && f[0] == '1') return false; - if (cpu_isa_cap() < 3) return false; - unsigned r[4] = {0, 0, 0, 0}; - auto cpuid = [&](unsigned leaf, unsigned sub) { -#if defined(_MSC_VER) - int x[4]; - __cpuidex(x, (int) leaf, (int) sub); - for (int i = 0; i < 4; ++i) r[i] = (unsigned) x[i]; -#else - __cpuid_count(leaf, sub, r[0], r[1], r[2], r[3]); -#endif - }; - cpuid(0, 0); - if (r[0] < 7) return false; - cpuid(1, 0); - if (!((r[2] >> 27) & 1u)) return false; // OSXSAVE -#if defined(_MSC_VER) - const unsigned long long xcr0 = _xgetbv(0); -#else - unsigned lo = 0, hi = 0; - __asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0)); - const unsigned long long xcr0 = ((unsigned long long) hi << 32) | lo; -#endif - if ((xcr0 & 0xE6) != 0xE6) return false; // the OS saves the AVX-512 state - cpuid(7, 0); - const unsigned ebx = r[1], ecx = r[2]; - return ((ebx >> 16) & 1u) && ((ebx >> 30) & 1u) && ((ebx >> 31) & 1u) && ((ecx >> 11) & 1u) && ((ecx >> 1) & 1u); - }(); - return ok; -} - -bool cpu_avx512bw_ok() { - static const bool ok = [] { - if (const char* f = std::getenv("STRATA_FORCE_AVX2"); f != nullptr && f[0] == '1') return false; - unsigned r[4] = {0, 0, 0, 0}; - auto cpuid = [&](unsigned leaf, unsigned sub) { -#if defined(_MSC_VER) - int x[4]; - __cpuidex(x, (int) leaf, (int) sub); - for (int i = 0; i < 4; ++i) r[i] = (unsigned) x[i]; -#else - __cpuid_count(leaf, sub, r[0], r[1], r[2], r[3]); -#endif - }; - cpuid(0, 0); - if (r[0] < 7) return false; - cpuid(1, 0); - if (!((r[2] >> 27) & 1u)) return false; // OSXSAVE -#if defined(_MSC_VER) - const unsigned long long xcr0 = _xgetbv(0); -#else - unsigned lo = 0, hi = 0; - __asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0)); - const unsigned long long xcr0 = ((unsigned long long) hi << 32) | lo; -#endif - if ((xcr0 & 0xE6) != 0xE6) return false; // the OS saves the AVX-512 state - cpuid(7, 0); - const unsigned ebx = r[1]; - return ((ebx >> 16) & 1u) && ((ebx >> 17) & 1u) && ((ebx >> 30) & 1u) && ((ebx >> 31) & 1u); - }(); - return ok; -} - -bool cpu_avx2_ok() { - static const bool ok = [] { - if (cpu_isa_cap() < 2) return false; - unsigned r[4] = {0, 0, 0, 0}; - auto cpuid = [&](unsigned leaf, unsigned sub) { -#if defined(_MSC_VER) - int x[4]; - __cpuidex(x, (int) leaf, (int) sub); - for (int i = 0; i < 4; ++i) r[i] = (unsigned) x[i]; -#else - __cpuid_count(leaf, sub, r[0], r[1], r[2], r[3]); -#endif - }; - cpuid(0, 0); - if (r[0] < 7) return false; - cpuid(1, 0); - const unsigned ecx1 = r[2]; - // FMA (12), OSXSAVE (27), AVX (28), F16C (29) - if (!((ecx1 >> 12) & 1u) || !((ecx1 >> 27) & 1u) || !((ecx1 >> 28) & 1u) || !((ecx1 >> 29) & 1u)) return false; -#if defined(_MSC_VER) - const unsigned long long xcr0 = _xgetbv(0); -#else - unsigned lo = 0, hi = 0; - __asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0)); - const unsigned long long xcr0 = ((unsigned long long) hi << 32) | lo; -#endif - if ((xcr0 & 0x6) != 0x6) return false; // the OS saves the SSE and AVX state - cpuid(7, 0); - return ((r[1] >> 5) & 1u) != 0; // AVX2 - }(); - return ok; -} - -bool cpu_avx1_ok() { - // AVX (Sandy Bridge, 2011): AVX + OSXSAVE with the OS saving the YMM state; FMA, F16C and AVX2 not needed. - // From the Strata_Dirigo fork (rwkeyes). - static const bool ok = [] { - if (cpu_isa_cap() < 1) return false; - unsigned r[4] = {0, 0, 0, 0}; -#if defined(_MSC_VER) - int x[4]; - __cpuidex(x, 1, 0); - for (int i = 0; i < 4; ++i) r[i] = (unsigned) x[i]; -#else - __cpuid_count(1, 0, r[0], r[1], r[2], r[3]); -#endif - if (!((r[2] >> 27) & 1u) || !((r[2] >> 28) & 1u)) return false; // OSXSAVE, AVX -#if defined(_MSC_VER) - const unsigned long long xcr0 = _xgetbv(0); -#else - unsigned lo = 0, hi = 0; - __asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0)); - const unsigned long long xcr0 = ((unsigned long long) hi << 32) | lo; -#endif - return (xcr0 & 0x6) == 0x6; - }(); - return ok; -} - -bool cpu_sse42_ok() { - static const bool ok = [] { - unsigned r[4] = {0, 0, 0, 0}; -#if defined(_MSC_VER) - int x[4]; - __cpuidex(x, 1, 0); - for (int i = 0; i < 4; ++i) r[i] = (unsigned) x[i]; -#else - __cpuid_count(1, 0, r[0], r[1], r[2], r[3]); -#endif - return ((r[2] >> 20) & 1u) && ((r[2] >> 23) & 1u); // SSE4.2, POPCNT - }(); - return ok; -} - -const char* isa_floor_build() { -#if defined(STRATA_ISA_FLOOR_AVX) - return "avx"; -#elif defined(STRATA_ISA_FLOOR_NONE) - return "sse4.2"; -#else - return ""; -#endif -} - -std::string cpu_name() { - unsigned r[12] = {}; -#if defined(_MSC_VER) - int x[4]; - __cpuid(x, (int) 0x80000000u); - if ((unsigned) x[0] < 0x80000004u) return "unknown"; - for (unsigned i = 0; i < 3; ++i) { - __cpuid(x, (int) (0x80000002u + i)); - for (int j = 0; j < 4; ++j) r[i * 4 + j] = (unsigned) x[j]; - } -#else - unsigned a = 0, b = 0, c = 0, d = 0; - __cpuid(0x80000000u, a, b, c, d); - if (a < 0x80000004u) return "unknown"; - for (unsigned i = 0; i < 3; ++i) __cpuid(0x80000002u + i, r[i * 4], r[i * 4 + 1], r[i * 4 + 2], r[i * 4 + 3]); -#endif - char s[49] = {}; - std::memcpy(s, r, 48); - std::string name(s); - const size_t b0 = name.find_first_not_of(' '), b1 = name.find_last_not_of(' '); - return b0 == std::string::npos ? std::string("unknown") : name.substr(b0, b1 - b0 + 1); -} - -void q2_rows_any(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, float* const* out, - int r0, int r1) { - if (cpu_avx512_ok()) q2_0_gguf_rows_multi(w, row_bytes, nblocks, a, nt, out, r0, r1); - else q2_0_gguf_rows_multi_avx2(w, row_bytes, nblocks, a, nt, out, r0, r1); -} - -void act_quant_any(const float* x, int n, ActQ& a) { - if (cpu_avx512_ok()) act_quant_q8_1(x, n, a); - else act_quant_q8_1_avx2(x, n, a); -} - -#if !defined(STRATA_NATIVE_EXPERTS) -// Without ggml-cpu no native pack loads (expert_layout_load refuses), so these are never reached. -bool native_experts_available() noexcept { return false; } -bool native_fmt(int, int, int64_t, int64_t, NativeFmt&, std::string& err) { err = "built without native experts"; return false; } -void native_quant_act(const NativeFmt&, const float*, void*) { std::abort(); } -void native_quant_h(const NativeFmt&, const float*, void*) { std::abort(); } -void native_gu_rows(const NativeFmt&, const uint8_t*, const void* const*, int, float* const*, int, int) { std::abort(); } -void native_down_rows(const NativeFmt&, const uint8_t*, const void* const*, int, float* const*, int, int) { std::abort(); } -#endif - -bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int64_t n_embd, int64_t n_ff, - std::string& err) { - 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; - } -#if !defined(STRATA_NATIVE_EXPERTS) - err = "this pack has native (IQ) experts but the engine was built without STRATA_NATIVE_EXPERTS"; - return false; -#else - L.native = true; - L.fmt.resize((size_t) n_layers); - L.offset.assign((size_t) n_layers, ~0ull); - L.bytes.assign((size_t) n_layers, 0); - L.max_blob = 0; - std::string line; - while (std::getline(in, line)) { - if (line.empty() || line[0] == '#') { - if (!line.empty() && line[0] == '#') { - // "# strata native experts vN: ...". A version this engine does not know may mean columns it - // would misread, so it is refused rather than parsed as far as the known columns go. - static const char tag[] = "# strata native experts v"; - if (line.compare(0, sizeof tag - 1, tag) == 0) { - L.version = std::atoi(line.c_str() + sizeof tag - 1); - if (L.version > kExpertLayoutVersion) { - err = "native_experts.txt is v" + std::to_string(L.version) + "; this engine reads up to v" + - std::to_string(kExpertLayoutVersion) + " (the pack was written by a newer tools/" - "iq_pack.py: update the engine, or repack with this one)"; - return false; - } - } - // v3 packs record their expert count in the header; a pruned model (GSQ-RCO Coder) ships - // fewer experts than the canonical geometry the caller passes, which is a compile-time - // default, so the header wins. - const size_t at = line.find("(n_expert "); - if (at != std::string::npos) L.n_expert = std::atoll(line.c_str() + at + 10); - } - continue; - } - std::istringstream ss(line); - long long l = -1, gt = -1, dt = -1; - unsigned long long off = 0, blob = 0, go = 0, uo = 0, dox = 0; - if (!(ss >> l >> gt >> dt >> off >> blob) || l < 0 || l >= n_layers) { - err = "native_experts.txt: a malformed line: " + line; - return false; - } - NativeFmt f; - 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) + " 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 - if (L.gguf_off.empty()) L.gguf_off.assign((size_t) (3 * n_layers), 0); - L.gguf_off[(size_t) (3 * l)] = go; - L.gguf_off[(size_t) (3 * l + 1)] = uo; - L.gguf_off[(size_t) (3 * l + 2)] = dox; - std::string file; // v3: the shard that holds this layer (a file name beside --native) - if (ss >> file) { - if (L.gguf_file.empty()) L.gguf_file.assign((size_t) (3 * n_layers), std::string()); - // One name covers all three roles. When a shard boundary falls inside a layer the packer writes - // "gate,up,down" instead (v4), an empty field meaning the --native shard. A GGUF file name has no - // comma, so the split is unambiguous; an engine older than v4 fails to open such a "file" loudly. - // The comma form is from #255 (gopinath87607). - std::vector parts; - for (size_t from = 0;;) { - const size_t comma = file.find(',', from); - parts.push_back(file.substr(from, comma == std::string::npos ? comma : comma - from)); - if (comma == std::string::npos) break; - from = comma + 1; - } - if (parts.size() == 1) { - const std::string one = parts[0]; // not parts.assign(3, parts[0]): that aliases the element - parts.assign(3, one); // the assignment is about to overwrite - } - std::string extra; - if (parts.size() != 3 || (ss >> extra)) { - err = "native_experts.txt: layer " + std::to_string(l) + ": the shard column is one name or " - "gate,up,down, not: " + line; - return false; - } - for (size_t r = 0; r < 3; ++r) L.gguf_file[(size_t) (3 * l) + r] = parts[r]; - } - } - L.fmt[(size_t) l] = f; - L.offset[(size_t) l] = off; - L.bytes[(size_t) l] = blob; - if (blob > L.max_blob) L.max_blob = blob; - } - uint64_t at = 0; - for (int64_t l = 0; l < n_layers; ++l) { - if (L.offset[(size_t) l] != at) { - err = "native_experts.txt: layer " + std::to_string(l) + " is missing or not contiguous"; - return false; - } - at += L.bytes[(size_t) l] * (uint64_t) L.n_expert; - } - L.total = at; - g_layout = L; - return true; -#endif -} - -} // namespace strata::kernels::cpu diff --git a/src/kernels/cpu/expert_multi_test.cpp b/src/kernels/cpu/expert_multi_test.cpp deleted file mode 100644 index 446c95f..0000000 --- a/src/kernels/cpu/expert_multi_test.cpp +++ /dev/null @@ -1,87 +0,0 @@ -// src/kernels/cpu/expert_multi_test.cpp - plan v0.3 P6: one expert, several tokens (CPU only, synthetic data). -// -// expert_multi_test bitwise check: s2_expert_vnni_multi vs s2_expert_vnni_q per token, n = 1..8 -// expert_multi_test --bench [E] time per expert for n = 1..5 over E synthetic experts (default 256 = 354 MB, -// far beyond L3, so the blob comes from DRAM as it does in the engine); 1 thread -// -// The bench measures the speculation model's `extra_use_cost`: the CPU time of each extra token routed to an -// expert, as a fraction of reading the expert once (tools/spec_economics.py assumes 0.2). -#include "strata/kernels/cpu/expert.hpp" - -#include -#include -#include -#include -#include -#include - -namespace c = strata::kernels::cpu; - -namespace { -void make_blob(uint8_t* b, std::mt19937& rng) { - for (size_t i = 0; i < c::O_GU_SCALES; ++i) b[i] = (uint8_t) rng(); // codes - for (size_t i = c::O_GU_SCALES; i < c::BLOB; i += 2) { // fp16 scales ~0.004-0.016 - const uint16_t h = (uint16_t) (0x1C00 + rng() % 0x0800); - std::memcpy(b + i, &h, 2); - } -} - -double now_ms() { - return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); -} -} // namespace - -int main(int argc, char** argv) { - c::cpu_require_expert_support(); - std::mt19937 rng(9); - const bool bench = argc > 1 && std::strcmp(argv[1], "--bench") == 0; - const int E = bench ? (argc > 2 ? std::atoi(argv[2]) : 256) : 4; - std::vector blobs((size_t) E * c::BLOB); - for (int e = 0; e < E; ++e) make_blob(&blobs[(size_t) e * c::BLOB], rng); - std::normal_distribution nd(0.f, 1.f); - static c::ActQ acts[c::MAXT]; - static float xs[c::MAXT][c::H]; - for (int t = 0; t < c::MAXT; ++t) { - for (float& v : xs[t]) v = nd(rng); - c::act_quant_q8_1(xs[t], c::H, acts[t]); - } - const c::ActQ* a1[c::MAXT]; - for (int t = 0; t < c::MAXT; ++t) a1[t] = &acts[t]; - static float out_multi[c::MAXT][c::H], out_single[c::H]; - float* outs[c::MAXT]; - for (int t = 0; t < c::MAXT; ++t) outs[t] = out_multi[t]; - static c::ExpertScratchMulti wsm; - static c::ExpertScratch ws; - - if (!bench) { - int fail = 0; - for (int e = 0; e < E; ++e) { - const uint8_t* blob = &blobs[(size_t) e * c::BLOB]; - for (int n = 1; n <= c::MAXT; ++n) { - c::s2_expert_vnni_multi(blob, a1, n, outs, wsm); - for (int t = 0; t < n; ++t) { - c::s2_expert_vnni_q(blob, acts[t], out_single, ws); - if (std::memcmp(out_single, out_multi[t], sizeof out_single) != 0) { - std::fprintf(stderr, "FAIL expert %d n=%d token %d differs\n", e, n, t); - ++fail; - } - } - } - } - std::printf("expert_multi_test: %s\n", fail ? "FAILED" : "OK (every token bitwise equal to the single-token kernel)"); - return fail ? 1 : 0; - } - - std::printf("%d experts x %.2f MB, one thread\n", E, c::BLOB / 1e6); - double base = 0; - for (int n = 1; n <= 5; ++n) { - c::s2_expert_vnni_multi(&blobs[0], a1, n, outs, wsm); // warm the code path - const double t0 = now_ms(); - for (int e = 0; e < E; ++e) c::s2_expert_vnni_multi(&blobs[(size_t) e * c::BLOB], a1, n, outs, wsm); - const double us = 1000.0 * (now_ms() - t0) / E; - if (n == 1) base = us; - std::printf("tokens per expert %d: %7.1f us per expert (%.2fx one token; extra token = %.2f of one read), %.1f GB/s\n", - n, us, us / base, n > 1 ? (us / base - 1.0) / (n - 1) : 0.0, c::BLOB / (us * 1e3)); - } - return 0; -} diff --git a/src/kernels/cpu/expert_parity.cpp b/src/kernels/cpu/expert_parity.cpp deleted file mode 100644 index 39f24a1..0000000 --- a/src/kernels/cpu/expert_parity.cpp +++ /dev/null @@ -1,184 +0,0 @@ -// src/kernels/cpu/expert_parity.cpp - P2.S3's test for the CPU expert path. -// -// WHAT IS BEING CHECKED, and the two tolerances are different questions: -// -// 1. VNNI vs the scalar oracle with `quant_acts = true`. Both sides consume the SAME INT8 activation -// values, so the only difference is FP32 evaluation ORDER. This is the check that proves the KERNEL - -// the VNNI unpack, the 32-element chunk split, the scalar correction term - and P2.S3 asks for 3e-3. -// 2. VNNI vs the oracle with `quant_acts = false`. Now the oracle uses exact FP32 activations, so the gap -// IS the activation contract (`docs/activation-contract.md`). It is REPORTED, not asserted tightly, -// because it is a property of the model's quantisation and not of this code. -// -// The activation contract is asserted OBSERVABLE between the two: if rounding the activation to Q8_1 made no -// difference, then one of the two paths is not doing what it claims and check 1 would be vacuous. -// -// A SELF-CONSISTENT TEST CANNOT CATCH A WRONG FILE OFFSET. Both sides read the same blob, so pointing at the -// wrong expert would still agree perfectly. What is checked instead is structural: the blob must decode to -// finite, non-zero scales, and the blob at a DIFFERENT layer must be different data - which is what a wrong -// stride would break. -#include "strata/kernels/cpu/expert.hpp" - -#include -#include -#include -#include -#include -#include -#include - -namespace cpu = strata::kernels::cpu; - -namespace { - -/// Normalised L1 difference, with the reference magnitude returned for reporting. -double rel_l1(const float* a, const float* b, int n, double* mag_out = nullptr) { - double d = 0, mag = 0; - for (int i = 0; i < n; ++i) { - d += std::fabs((double) a[i] - (double) b[i]); - mag += std::fabs((double) a[i]); - } - if (mag_out) *mag_out = mag / n; - return d / (mag > 1e-30 ? mag : 1e-30); -} - -bool read_blob(const char* path, long long index, std::vector& out) { - out.assign(cpu::BLOB, 0); - std::FILE* f = std::fopen(path, "rb"); - if (!f) return false; -#if defined(_MSC_VER) - if (_fseeki64(f, (long long) index * (long long) cpu::BLOB, SEEK_SET) != 0) { std::fclose(f); return false; } -#else - if (fseeko(f, (off_t) index * (off_t) cpu::BLOB, SEEK_SET) != 0) { std::fclose(f); return false; } -#endif - const size_t got = std::fread(out.data(), 1, out.size(), f); - std::fclose(f); - return got == out.size(); -} - -/// The fp16 scale at a byte offset, decoded by the SAME rule the kernel uses. Used only for the structural -/// sanity check, so it is deliberately a second, independent transcription of the three lines in question. -float f16_at(const std::vector& b, size_t off) { - uint16_t h; - std::memcpy(&h, b.data() + off, 2); - const uint32_t sign = (uint32_t) (h >> 15) & 1u; - uint32_t exp = (h >> 10) & 0x1Fu, man = h & 0x3FFu, f; - if (exp == 0) { - if (man == 0) f = sign << 31; - else { exp = 127 - 15 + 1; while (!(man & 0x400u)) { man <<= 1; --exp; } man &= 0x3FFu; - f = (sign << 31) | (exp << 23) | (man << 13); } - } else if (exp == 31) { - f = (sign << 31) | 0x7F800000u | (man << 13); - } else { - f = (sign << 31) | ((exp - 15 + 127) << 23) | (man << 13); - } - float o; - std::memcpy(&o, &f, 4); - return o; -} - -} // namespace - -int main(int argc, char** argv) { - bool selftest = false; - const char* path = "pack/full/experts.bin"; - long long layer = 0, expert = 0; - for (int i = 1; i < argc; ++i) { - const std::string a = argv[i]; - if (a == "--selftest") selftest = true; - else if (a == "--file" && i + 1 < argc) path = argv[++i]; - else if (a == "--layer" && i + 1 < argc) layer = std::atoll(argv[++i]); - else if (a == "--expert" && i + 1 < argc) expert = std::atoll(argv[++i]); - else { std::fprintf(stderr, "usage: expert_parity [--selftest] [--file P] [--layer N] [--expert N]\n"); - return 2; } - } - - int bad = 0; - - // ---- the CPU must be able to run the kernel, and the report must say WHICH feature is missing - const cpu::CpuFeatures feat = cpu::cpu_features(); - std::printf(" %-44s %s\n", "AVX512 F/BW/VL/VNNI/VBMI", - feat.usable() ? "all present" : feat.reason()); - if (!feat.usable()) { - std::printf(" the VNNI path cannot run here; only the scalar oracle can be exercised.\n"); - std::printf(" P2.S3's kernel check is SKIPPED, not passed.\n"); - std::printf("\nexpert_parity: 0 failures, 1 SKIPPED\n"); - return 0; - } - - // ---- a real blob out of the pack: layer stride is 512 experts - const long long idx = layer * 512 + expert; - std::vector blob; - if (!read_blob(path, idx, blob)) { - std::fprintf(stderr, "cannot read expert %lld (layer %lld) from %s\n", expert, layer, path); - return 2; - } - - // ---- structural sanity, because the agreement checks below are self-consistent and would pass on the - // wrong blob. A mis-strided read lands on a different expert's data, which is still plausible Q2_0, - // so the check that has teeth is the DIFFERENCE between layers. - { - int nonzero = 0; - float smin = 1e30f, smax = -1e30f; - for (int b = 0; b < cpu::SC_GU; ++b) { - const float s = f16_at(blob, cpu::O_GU_SCALES + (size_t) b * 2); - if (s != 0.f) ++nonzero; - smin = std::fmin(smin, std::fabs(s)); - smax = std::fmax(smax, std::fabs(s)); - } - const bool ok = nonzero > cpu::SC_GU / 2 && std::isfinite(smin) && std::isfinite(smax) && smax > 0.f; - std::printf(" %-44s %s (%d/%d non-zero, |s| in [%.4g, %.4g])\n", "blob decodes to live scales", - ok ? "yes" : "*** NO ***", nonzero, cpu::SC_GU, (double) smin, (double) smax); - if (!ok) ++bad; - } - { - std::vector other; - if (read_blob(path, (layer * 512 + expert) + 1, other)) { - long long diff = 0; - for (size_t i = 0; i < blob.size(); ++i) if (blob[i] != other[i]) ++diff; - const double frac = (double) diff / (double) blob.size(); - const bool ok = frac > 0.1; - std::printf(" %-44s %s (%.1f%% of bytes differ)\n", "the next expert is different data", - ok ? "yes" : "*** NO ***", frac * 100); - if (!ok) ++bad; - } - } - - // ---- a realistic activation - std::mt19937 rng(4242); - std::normal_distribution gauss(0.0f, 1.0f); - std::vector x(cpu::H); - for (auto& v : x) v = gauss(rng); - - cpu::ExpertScratch ws; - std::vector vnni(cpu::H), scalar_q(cpu::H), scalar_fp(cpu::H); - cpu::s2_expert_vnni(blob.data(), x.data(), vnni.data(), ws); - cpu::s2_expert_scalar(blob.data(), x.data(), scalar_q.data(), true); - cpu::s2_expert_scalar(blob.data(), x.data(), scalar_fp.data(), false); - - double mag = 0; - const double rel_kernel = rel_l1(scalar_q.data(), vnni.data(), cpu::H, &mag); - const double rel_contract = rel_l1(scalar_fp.data(), vnni.data(), cpu::H); - const double trap_contract = rel_l1(scalar_fp.data(), scalar_q.data(), cpu::H); - - // ---- the activation contract must be OBSERVABLE, or check 1 is vacuous - { - const bool visible = trap_contract > 1e-4; - std::printf(" %-44s %s (%.4f%% apart)\n", "the Q8_1 activation contract is observable", - visible ? "yes" : "*** NO ***", trap_contract * 100); - if (!visible) ++bad; - } - - // ---- 1. the kernel, against an oracle fed the SAME activations - std::printf(" %-44s rel %.3e (P2.S3 asks <= 3e-3, mean |ref| %.4f)\n", "VNNI vs scalar (INT8 acts)", - rel_kernel, mag); - if (!(rel_kernel <= 3e-3)) { std::printf(" *** over P2.S3's 3e-3 ***\n"); ++bad; } - - // ---- 2. the activation contract's own cost, reported rather than asserted - std::printf(" %-44s rel %.3e (the cost of the contract, REPORTED)\n", - "VNNI vs scalar (FP32 acts)", rel_contract); - - std::printf("\nexpert_parity: %d failures (layer %lld expert %lld of %s)\n", bad, layer, expert, path); - if (bad) return 1; - if (selftest) std::printf("expert_parity OK\n"); - return 0; -} diff --git a/src/kernels/cpu/iq_avx2.cpp b/src/kernels/cpu/iq_avx2.cpp deleted file mode 100644 index bb8849b..0000000 --- a/src/kernels/cpu/iq_avx2.cpp +++ /dev/null @@ -1,493 +0,0 @@ -// src/kernels/cpu/iq_avx2.cpp - the i-quant expert rows in 256-bit lanes, several tokens at once. -// -// The AVX-512 kernels' (iq_avx512.cpp) multi-token scheme on the CPUs without AVX-512 (AMD Zen 2/3, Intel -// Core 12th-14th gen and Core Ultra): each 32-value chunk is decoded once - grid lookups, one sign vector, -// one scale vector - and every token of the verify window applies them with a load, a `sign`, a `maddubs`, -// a `madd` and an `add`. ggml-cpu's own AVX2 dot products for these formats are single-token: every token -// re-does the codebook lookups and the sign expansion. The sign vector is ggml's bit_selector pattern -// (ggml-cpu/arch/x86/quants.c): pshufb-broadcast of each sign byte, AND with the bit selector, CMPEQ, OR -// with one, `vpsignb`. The arithmetic is ggml's (ggml-cpu/quants.c, the `_generic` references) - only the -// order of the float additions differs. -// -// Formats: IQ2_XXS (16), IQ2_XS (17), IQ3_XXS (18), IQ3_S (21), IQ2_S (22), IQ4_XS (23). IQ1_M stays on ggml-cpu. -#include "strata/kernels/cpu/iq_avx2.hpp" - -#define GGML_COMMON_DECL_CPP -#define GGML_COMMON_IMPL_CPP -#include "ggml-common.h" - -#include - -#include -#include -#include - -namespace strata::kernels::cpu { -namespace { - -inline float h2f(uint16_t h) { return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128((int) h))); } -inline uint32_t u32(const uint8_t* p) { uint32_t v; std::memcpy(&v, p, 4); return v; } -inline uint16_t u16(const uint8_t* p) { uint16_t v; std::memcpy(&v, p, 2); return v; } -inline uint64_t u64(const uint8_t* p) { uint64_t v; std::memcpy(&v, p, 8); return v; } - -// 32 sign bits -> 32 bytes of -1 (bit set) / +1: ggml's bit_selector pattern, shared by all tokens. -inline __m256i sgn_vec(uint32_t m) { - const __m128i bm = _mm_set1_epi32((int) m); - const __m128i lo = _mm_shuffle_epi8(bm, _mm_setr_epi8(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1)); - const __m128i hi = _mm_shuffle_epi8(bm, _mm_setr_epi8(2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3)); - const __m256i bits = _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1); - const __m256i sel = _mm256_setr_epi8(1, 2, 4, 8, 16, 32, 64, (char) 0x80, - 1, 2, 4, 8, 16, 32, 64, (char) 0x80, - 1, 2, 4, 8, 16, 32, 64, (char) 0x80, - 1, 2, 4, 8, 16, 32, 64, (char) 0x80); - const __m256i nz = _mm256_cmpeq_epi8(_mm256_and_si256(bits, sel), sel); - return _mm256_or_si256(nz, _mm256_set1_epi8(1)); -} - -// The two 16-value scales of one 32-value half (IQ2_XS, IQ2_S): int16 lanes 0-7 = a (values 0-15), -// 8-15 = b (values 16-31). NOT a broadcast dword [a,b] - that would alternate the scales lane by lane. -inline __m256i sc16(int a, int b) { - return _mm256_inserti128_si256(_mm256_castsi128_si256(_mm_set1_epi16((short) a)), - _mm_set1_epi16((short) b), 1); -} -// One scale for the whole 32-value half (IQ2_XXS, IQ3_XXS, IQ3_S). -inline __m256i sc32(int s) { return _mm256_set1_epi16(s); } - -// keven_signs_q2xs (ggml keeps it static in arch/x86/quants.c): one u64 per 7-bit sign index, byte k -// = 0xFF when bit k of ksigns_iq2xs[i] is set, 0x01 otherwise. With this a whole 32-value sign vector -// is four scalar loads and a set_epi64x - no ksigns byte packing chain and no bit_selector expansion. -// -// Computed at COMPILE time (constexpr), so this file has no static constructor at all. This TU is compiled -// for AVX2, and a runtime constructor here runs before main() on every CPU: MSVC turned its variable shift -// into BMI2 `shlx` (#391, demetree: strata.exe exited 0xC000001D before printing anything on a Sandy Bridge -// Xeon) and GCC vectorised the loop into AVX2 (`vpbroadcastb`, found on an AVX-only Xeon E5 by the -// Strata_Dirigo fork). ksigns_iq2xs[i] is i's 7 bits plus an even-parity bit 7 (ggml-common.h); a const -// array is not usable in a constant expression, so the byte is derived the same way here, and -// native_expert_parity checks these kernels against ggml-cpu's. -struct EvenSigns { - uint64_t v[128]; - constexpr EvenSigns() : v{} { - for (int i = 0; i < 128; ++i) { - int par = 0; - for (int k = 0; k < 7; ++k) par ^= (i >> k) & 1; - const int s = i | (par << 7); // == ksigns_iq2xs[i] - uint64_t r = 0; - for (int k = 0; k < 8; ++k) r |= (uint64_t) (((s >> k) & 1) ? 0xFF : 0x01) << (8 * k); - v[i] = r; - } - } -}; -static constexpr EvenSigns even_signs{}; -static_assert(even_signs.v[0] == 0x0101010101010101ull && even_signs.v[1] == 0xFF010101010101FFull, - "keven_signs_q2xs: byte k = 0xFF when bit k of ksigns_iq2xs[i] is set"); - -inline float hsum8(__m256 v) { - const __m128 lo = _mm256_castps256_ps128(v), hi = _mm256_extractf128_ps(v, 1); - __m128 s = _mm_add_ps(lo, hi); - s = _mm_hadd_ps(s, s); - s = _mm_hadd_ps(s, s); - return _mm_cvtss_f32(s); -} - -// E-2 (iq_avx512.cpp) on the AVX-2 path: the pool streams the expert rows from DRAM at ~25 GB/s (4 KB pages -// when large pages are refused), so ask for the bytes a few blocks before the decode needs them - 2048 B is -// two gate/up rows ahead, a row is ~1 KB. Same switch as the AVX-512 kernels: STRATA_IQ_PREFETCH is the -// distance in bytes, 0 = off, default 2048. Measured on a Zen 3 5700X3D (no AVX-512) on IQ3_S decode: -4% on -// the gate/up phase, +1.0 GB/s over the rows, -1.3% ms/round end to end. The non-temporal hint measured -// worse than T0 at the same distance, so this keeps T0. -const int prefetch_ahead = [] { - const char* v = std::getenv("STRATA_IQ_PREFETCH"); - return v ? std::atoi(v) : 2048; -}(); - -inline void rows_ahead(const uint8_t* p) { - if (prefetch_ahead <= 0) return; - _mm_prefetch((const char*) p, _MM_HINT_T0); - _mm_prefetch((const char*) p + 64, _MM_HINT_T0); -} - -// E-2 on the AVX-2 path (the AVX-512 kernels' STRATA_IQ_GATHER): the IQ3 grids by one AVX2 gather instead of eight -// scalar loads assembled with set_epi32. AVX2 gather is a different instruction with worse throughput on some cores -// (opt-in, as on AVX-512); on the i7-12850HX it measures ~1.3x on the two 32-bit-grid formats, bit-exact. -static const bool gather = [] { const char* v = std::getenv("STRATA_IQ256_GATHER"); return v != nullptr && std::atoi(v) != 0; }(); - -// ---- per format: one 32-value half (values 64*j + 32*half .. +31) -> grid magnitudes, sign vector, scales -template struct Fmt32; - -template <> struct Fmt32<16> { // IQ2_XXS: d, qs[32] u16 - static constexpr int bytes = 66; - static constexpr float K = 0.125f; - static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) { - const uint8_t* q = b + 2 + 16 * j + 8 * half; - const uint32_t w0 = u32(q), w1 = u32(q + 4); - g = _mm256_set_epi64x((long long) iq2xxs_grid[w0 >> 24], (long long) iq2xxs_grid[(w0 >> 16) & 255], - (long long) iq2xxs_grid[(w0 >> 8) & 255], (long long) iq2xxs_grid[w0 & 255]); - sgn = _mm256_set_epi64x((long long) even_signs.v[(w1 >> 21) & 127], (long long) even_signs.v[(w1 >> 14) & 127], - (long long) even_signs.v[(w1 >> 7) & 127], (long long) even_signs.v[w1 & 127]); - sc = sc32(2 * (int) (w1 >> 28) + 1); - } -}; - -template <> struct Fmt32<17> { // IQ2_XS: d, qs[32] u16 (9-bit grid index + 7-bit sign index), scales[8] - static constexpr int bytes = 74; - static constexpr float K = 0.125f; - static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) { - uint16_t v[8]; - std::memcpy(v, b + 2 + 16 * j, 16); - const int o = 4 * half; - g = _mm256_set_epi64x((long long) iq2xs_grid[v[o + 3] & 511], (long long) iq2xs_grid[v[o + 2] & 511], - (long long) iq2xs_grid[v[o + 1] & 511], (long long) iq2xs_grid[v[o] & 511]); - uint32_t s = 0; - for (int l = 0; l < 4; ++l) s |= (uint32_t) ksigns_iq2xs[v[o + l] >> 9] << (8 * l); - sgn = sgn_vec(s); - const uint8_t sb = b[66 + 2 * j + half]; - sc = sc16(2 * (sb & 15) + 1, 2 * (sb >> 4) + 1); - } -}; - -template <> struct Fmt32<22> { // IQ2_S: d, qs[64] (32 grid bytes, 32 sign bytes), qh[8], scales[8] - static constexpr int bytes = 82; - static constexpr float K = 0.125f; - static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) { - const uint8_t* qs = b + 2 + 8 * j; - const uint8_t h = b[66 + 2 * j + half]; - const int o = 4 * half; - g = _mm256_set_epi64x((long long) iq2s_grid[qs[o + 3] | ((h << 2) & 0x300)], - (long long) iq2s_grid[qs[o + 2] | ((h << 4) & 0x300)], - (long long) iq2s_grid[qs[o + 1] | ((h << 6) & 0x300)], - (long long) iq2s_grid[qs[o] | ((h << 8) & 0x300)]); - const uint64_t m = u64(b + 2 + 32 + 8 * j); - sgn = sgn_vec(half ? (uint32_t) (m >> 32) : (uint32_t) m); - const uint8_t sb = b[74 + 2 * j + half]; - sc = sc16(2 * (sb & 15) + 1, 2 * (sb >> 4) + 1); - } -}; - -template <> struct Fmt32<18> { // IQ3_XXS: d, qs[64] grid bytes, 8 x u32 (4 x 7-bit sign index + 4-bit scale) - static constexpr int bytes = 98; - static constexpr float K = 0.25f; - static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) { - const uint8_t* q = b + 2 + 16 * j + 8 * half; - if (gather) { - const __m256i idx = _mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*) q)); - g = _mm256_i32gather_epi32((const int*) iq3xxs_grid, idx, 4); - } else { - g = _mm256_set_epi32((int) iq3xxs_grid[q[7]], (int) iq3xxs_grid[q[6]], (int) iq3xxs_grid[q[5]], (int) iq3xxs_grid[q[4]], - (int) iq3xxs_grid[q[3]], (int) iq3xxs_grid[q[2]], (int) iq3xxs_grid[q[1]], (int) iq3xxs_grid[q[0]]); - } - const uint32_t w = u32(b + 2 + 64 + 8 * j + 4 * half); - sgn = _mm256_set_epi64x((long long) even_signs.v[(w >> 21) & 127], (long long) even_signs.v[(w >> 14) & 127], - (long long) even_signs.v[(w >> 7) & 127], (long long) even_signs.v[w & 127]); - sc = sc32(2 * (int) (w >> 28) + 1); - } -}; - -template <> struct Fmt32<21> { // IQ3_S: d, qs[64], qh[8], signs[32], scales[4] - static constexpr int bytes = 110; - static constexpr float K = 1.0f; - static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) { - const uint8_t* q = b + 2 + 16 * j + 8 * half; - const uint32_t h = b[66 + 2 * j + half]; - if (gather) { - const __m256i bits = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7); - __m256i idx = _mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*) q)); - idx = _mm256_add_epi32(idx, _mm256_slli_epi32( - _mm256_and_si256(_mm256_srlv_epi32(_mm256_set1_epi32((int) h), bits), _mm256_set1_epi32(1)), 8)); - g = _mm256_i32gather_epi32((const int*) iq3s_grid, idx, 4); - } else { -#define G3(k) (int) iq3s_grid[q[k] | (((h >> k) & 1u) << 8)] - g = _mm256_set_epi32(G3(7), G3(6), G3(5), G3(4), G3(3), G3(2), G3(1), G3(0)); -#undef G3 - } - const uint64_t m = u64(b + 74 + 8 * j); - sgn = sgn_vec(half ? (uint32_t) (m >> 32) : (uint32_t) m); - const uint8_t s = b[106 + j]; - sc = sc32(half ? 2 * (s >> 4) + 1 : 2 * (s & 15) + 1); - } -}; - -template <> struct Fmt32<23> { // IQ4_XS: d, scales_h, scales_l[4], qs[128] - 136 B, 8 signed sub-scales - // ggml's ggml_vec_dot_iq4_xs_q8_K: the same 16-value codebook as IQ4_NL, but each of the eight 32-value - // sub-blocks carries its own 6-bit scale, read as two nibbles of scales_l[p] plus two bits of scales_h, and - // used SIGNED as (ls - 32). The scale therefore folds into the int16 operand of madd_epi16 instead of - // becoming a float multiply per sub-block, and the codebook sign is carried the way iq4nl_rows does it. - static constexpr int bytes = 136; - static constexpr float K = 1.0f; - static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) { - const int H = 2 * j + half; // the eight 32-value sub-blocks, in the order the activation bytes come - const __m128i values = _mm_loadu_si128((const __m128i*) kvalues_iq4nl); - const __m128i bits = _mm_loadu_si128((const __m128i*) (b + 8 + 16 * H)); - const __m128i m4 = _mm_set1_epi8(0x0f); - const __m256i q4 = _mm256_inserti128_si256( - _mm256_castsi128_si256(_mm_shuffle_epi8(values, _mm_and_si128(bits, m4))), - _mm_shuffle_epi8(values, _mm_and_si128(_mm_srli_epi16(bits, 4), m4)), 1); - g = _mm256_sign_epi8(q4, q4); // |w|, the unsigned operand of maddubs - sgn = _mm256_sign_epi8(_mm256_set1_epi8(1), q4); // w's sign, applied to the activation - const int ls = ((b[4 + (H >> 1)] >> (4 * (H & 1))) & 0xf) | (((u16(b + 2) >> (2 * H)) & 3) << 4); - sc = _mm256_set1_epi16((short) (ls - 32)); - } -}; - -template -inline void row_dot(const uint8_t* row, int nblocks, const block_q8_K* const* y, float* res) { - __m256 accf[NT]; - for (int t = 0; t < NT; ++t) accf[t] = _mm256_setzero_ps(); - for (int i = 0; i < nblocks; ++i) { - const uint8_t* blk = row + (size_t) i * Fmt32::bytes; - rows_ahead(blk + prefetch_ahead); - __m256i acci[NT]; - for (int t = 0; t < NT; ++t) acci[t] = _mm256_setzero_si256(); - for (int j = 0; j < 4; ++j) { - for (int half = 0; half < 2; ++half) { - __m256i g, sgn, sc; - Fmt32::decode(blk, j, half, g, sgn, sc); - const int off = 64 * j + 32 * half; - for (int t = 0; t < NT; ++t) { - const __m256i yv = _mm256_loadu_si256((const __m256i*) (y[t][i].qs + off)); - const __m256i ys = _mm256_sign_epi8(yv, sgn); - acci[t] = _mm256_add_epi32(acci[t], _mm256_madd_epi16(_mm256_maddubs_epi16(g, ys), sc)); - } - } - } - const float dx = h2f(u16(blk)) * Fmt32::K; - for (int t = 0; t < NT; ++t) - accf[t] = _mm256_fmadd_ps(_mm256_set1_ps(dx * y[t][i].d), _mm256_cvtepi32_ps(acci[t]), accf[t]); - } - for (int t = 0; t < NT; ++t) res[t] = hsum8(accf[t]); -} - -// ---- IQ2_XS (17) with ggml's vectorized sign decode (arch/x86/quants.c, ggml_vec_dot_iq2_xs_q8_K): -// the 7-bit sign indices never touch ksigns_iq2xs - the 8th sign bit is reconstructed by parity (two -// shifts, a xor and ggml's bit_helper pshufb) and the per-half sign vectors come out of shuffles of one -// 32-byte load. The 8 scale bytes become all 16 half-scales with ggml's unpack trick. The grid lookups -// stay scalar loads into set_epi64x (ggml does the same). Every token still only pays a load, a sign, -// a maddubs, a madd and an add per half, into alternating accumulators. -template -inline void row_dot_iq2xs(const uint8_t* row, int nblocks, const block_q8_K* const* y, float* res) { - static const uint8_t bit_sel[32] = { - 1, 2, 4, 8, 16, 32, 64, (uint8_t) 0x80, 1, 2, 4, 8, 16, 32, 64, (uint8_t) 0x80, - 1, 2, 4, 8, 16, 32, 64, (uint8_t) 0x80, 1, 2, 4, 8, 16, 32, 64, (uint8_t) 0x80 }; - static const char shuf_even[32] = { // sign bits of u16 0,1,2,3 (even bytes of the sign register) - 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, - 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 6, 6 }; - static const char shuf_odd[32] = { // sign bits of u16 4,5,6,7 - 8, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, - 12, 12, 12, 12, 12, 12, 12, 12, 14, 14, 14, 14, 14, 14, 14, 14 }; - static const uint8_t bit_help[32] = { // 0x80 when the 4-bit index has odd popcount (parity bit 7) - 0x00, (uint8_t) 0x80, (uint8_t) 0x80, 0x00, (uint8_t) 0x80, 0x00, 0x00, (uint8_t) 0x80, - (uint8_t) 0x80, 0x00, 0x00, (uint8_t) 0x80, 0x00, (uint8_t) 0x80, (uint8_t) 0x80, 0x00, - 0x00, (uint8_t) 0x80, (uint8_t) 0x80, 0x00, (uint8_t) 0x80, 0x00, 0x00, (uint8_t) 0x80, - (uint8_t) 0x80, 0x00, 0x00, (uint8_t) 0x80, 0x00, (uint8_t) 0x80, (uint8_t) 0x80, 0x00 }; - static const uint8_t k_sc_shuffle[128] = { // half h -> scale bytes 2h (lanes 0-7), 2h+1 (lanes 8-15) - 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, - 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, - 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, - 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, - 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, - 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, - 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, - 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15 }; - const __m256i bsel = _mm256_loadu_si256((const __m256i*) bit_sel); - const __m256i shev = _mm256_loadu_si256((const __m256i*) shuf_even); - const __m256i shod = _mm256_loadu_si256((const __m256i*) shuf_odd); - const __m256i bhelp = _mm256_loadu_si256((const __m256i*) bit_help); - const __m256i m511 = _mm256_set1_epi16(511); - const __m128i m4 = _mm_set1_epi8(0xf), m1 = _mm_set1_epi8(1); - const __m256i one8 = _mm256_set1_epi8(1); - - __m256 accf[NT]; - for (int t = 0; t < NT; ++t) accf[t] = _mm256_setzero_ps(); - for (int i = 0; i < nblocks; ++i) { - const uint8_t* blk = row + (size_t) i * 74; - rows_ahead(blk + prefetch_ahead); - // the 8 scale bytes -> 16 half-scales of 2*s+1, interleaved [a0, b0, a1, b1, ...] (ggml's unpack) - __m128i st = _mm_set1_epi64x((long long) u64(blk + 66)); - st = _mm_unpacklo_epi8(_mm_and_si128(st, m4), _mm_and_si128(_mm_srli_epi16(st, 4), m4)); - const __m128i scales = _mm_add_epi8(_mm_slli_epi16(st, 1), m1); - __m256i acc[NT][2]; - for (int t = 0; t < NT; ++t) acc[t][0] = acc[t][1] = _mm256_setzero_si256(); - for (int jj = 0; jj < 2; ++jj) { // 128 values (16 u16) per step - const __m256i q2 = _mm256_loadu_si256((const __m256i*) (blk + 2 + 32 * jj)); - const __m256i p7 = _mm256_srli_epi16(q2, 9); // 7 sign bits per u16, even bytes - const __m256i p3 = _mm256_srli_epi16(q2, 13); // sign index bits 4-6 - const __m256i fsb = _mm256_or_si256(p7, - _mm256_shuffle_epi8(bhelp, _mm256_xor_si256(p7, p3))); // + the parity sign bit 7 - const __m256i s01 = _mm256_broadcastsi128_si256(_mm256_castsi256_si128(fsb)); // u16 0-7 - const __m256i s23 = _mm256_broadcastsi128_si256(_mm256_extracti128_si256(fsb, 1)); // u16 8-15 - alignas(32) uint16_t gi[16]; - _mm256_store_si256((__m256i*) gi, _mm256_and_si256(q2, m511)); - for (int h = 0; h < 4; ++h) { // the four 32-value halves of this group - const int H = 4 * jj + h; // global half index -> scales byte pair - const __m256i g = _mm256_set_epi64x((long long) iq2xs_grid[gi[4 * h + 3]], - (long long) iq2xs_grid[gi[4 * h + 2]], - (long long) iq2xs_grid[gi[4 * h + 1]], - (long long) iq2xs_grid[gi[4 * h]]); - const __m256i sb = _mm256_shuffle_epi8(h < 2 ? s01 : s23, (h & 1) ? shod : shev); - const __m256i sgn = _mm256_or_si256( - _mm256_cmpeq_epi8(_mm256_and_si256(sb, bsel), bsel), one8); - const __m256i sc = _mm256_cvtepi8_epi16( - _mm_shuffle_epi8(scales, _mm_loadu_si128((const __m128i*) k_sc_shuffle + H))); - const int off = 128 * jj + 32 * h; - for (int t = 0; t < NT; ++t) { - const __m256i yv = _mm256_loadu_si256((const __m256i*) (y[t][i].qs + off)); - const __m256i ys = _mm256_sign_epi8(yv, sgn); - acc[t][h & 1] = _mm256_add_epi32(acc[t][h & 1], - _mm256_madd_epi16(_mm256_maddubs_epi16(g, ys), sc)); - } - } - } - const float dx = h2f(u16(blk)) * 0.125f; - for (int t = 0; t < NT; ++t) - accf[t] = _mm256_fmadd_ps(_mm256_set1_ps(dx * y[t][i].d), - _mm256_cvtepi32_ps(_mm256_add_epi32(acc[t][0], acc[t][1])), accf[t]); - } - for (int t = 0; t < NT; ++t) res[t] = hsum8(accf[t]); -} - -template -inline void row_dot_any(const uint8_t* row, int nblocks, const block_q8_K* const* y, float* res) { - if constexpr (TY == 17) row_dot_iq2xs(row, nblocks, y, res); - else row_dot(row, nblocks, y, res); -} - -template -void gu_rows(const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, float* const* ff, - int r0, int r1) { - const block_q8_K* y[NT]; - for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t]; - const int nb = n / QK_K; - float g[NT], u[NT]; - for (int r = r0; r < r1; ++r) { - row_dot_any(blob + (size_t) r * gu_row, nb, y, g); - row_dot_any(blob + up_off + (size_t) r * gu_row, nb, y, u); - for (int t = 0; t < NT; ++t) ff[t][r] = (g[t] / (1.f + std::exp(-g[t]))) * u[t]; - } -} - -template -void dot_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out, int r0, int r1) { - const block_q8_K* y[NT]; - for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t]; - float res[NT]; - for (int r = r0; r < r1; ++r) { - row_dot_any(w + (size_t) r * row_bytes, n / QK_K, y, res); - for (int t = 0; t < NT; ++t) out[t][r] = res[t]; - } -} - -template -void gu_rows_nt(int nt, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, - float* const* ff, int r0, int r1) { - switch (nt) { - case 1: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 2: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 3: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 4: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 5: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 6: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 7: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; - default: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; - } -} - -template -void dot_rows_nt(int nt, const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out, int r0, - int r1) { - switch (nt) { - case 1: dot_rows(w, row_bytes, n, act, out, r0, r1); break; - case 2: dot_rows(w, row_bytes, n, act, out, r0, r1); break; - case 3: dot_rows(w, row_bytes, n, act, out, r0, r1); break; - case 4: dot_rows(w, row_bytes, n, act, out, r0, r1); break; - default: for (int t0 = 0; t0 < nt; t0 += 4) { - const int k = nt - t0 < 4 ? nt - t0 : 4; - dot_rows_nt(k, w, row_bytes, n, act + t0, out + t0, r0, r1); - } - } -} - -} // namespace - -bool iq256_supported(int type) noexcept { - return type == 16 || type == 17 || type == 18 || type == 21 || type == 22 || type == 23; -} - -void iq256_gu_rows(int type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt, - float* const* ff, int r0, int r1) { - switch (type) { - case 16: gu_rows_nt<16>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 17: gu_rows_nt<17>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 18: gu_rows_nt<18>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 21: gu_rows_nt<21>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 22: gu_rows_nt<22>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 23: gu_rows_nt<23>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; - default: break; - } -} - -void iq256_rows(int type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out, - int r0, int r1) { - switch (type) { - case 16: dot_rows_nt<16>(nt, w, row_bytes, n, act, out, r0, r1); break; - case 17: dot_rows_nt<17>(nt, w, row_bytes, n, act, out, r0, r1); break; - case 18: dot_rows_nt<18>(nt, w, row_bytes, n, act, out, r0, r1); break; - case 21: dot_rows_nt<21>(nt, w, row_bytes, n, act, out, r0, r1); break; - case 22: dot_rows_nt<22>(nt, w, row_bytes, n, act, out, r0, r1); break; - case 23: dot_rows_nt<23>(nt, w, row_bytes, n, act, out, r0, r1); break; - default: break; - } -} - -// ---- IQ4_NL (type 20): 32-value blocks of 18 bytes (f16 d + 16 nibble bytes) against Q8_0 activations. -// ggml-cpu's own AVX-2 dot (ggml_vec_dot_iq4_nl_q8_0) is single-token: every token redoes the nibble -> -// kvalues_iq4nl pshufb decode and the |w| half of the signed x signed product. Here both are computed once -// per block; every token then costs a sign, a maddubs, a madd and an fmadd. The arithmetic is ggml's - only -// the order of the float additions differs. -template -void iq4nl_rows(const uint8_t* w, size_t row_bytes, int n, const block_q8_0* const* y, float* const* out, - int r0, int r1) { - const __m128i values = _mm_loadu_si128((const __m128i*) kvalues_iq4nl); - const __m128i m4b = _mm_set1_epi8(0x0f); - const __m256i ones = _mm256_set1_epi16(1); - const int nb = n / QK4_NL; - for (int r = r0; r < r1; ++r) { - const uint8_t* row = w + (size_t) r * row_bytes; - __m256 accf[NT]; - for (int t = 0; t < NT; ++t) accf[t] = _mm256_setzero_ps(); - for (int ib = 0; ib < nb; ++ib) { - const uint8_t* blk = row + (size_t) ib * sizeof(block_iq4_nl); - rows_ahead(blk + prefetch_ahead); - const __m128i bits = _mm_loadu_si128((const __m128i*) (blk + 2)); - const __m128i lo = _mm_and_si128(bits, m4b); // values 0..15 - const __m128i hi = _mm_and_si128(_mm_srli_epi16(bits, 4), m4b); // values 16..31 - const __m256i q4 = _mm256_inserti128_si256(_mm256_castsi128_si256(_mm_shuffle_epi8(values, lo)), - _mm_shuffle_epi8(values, hi), 1); - const __m256i aq = _mm256_sign_epi8(q4, q4); // |w|: the unsigned operand of maddubs - const float dx = h2f(u16(blk)); - for (int t = 0; t < NT; ++t) { - const block_q8_0& b = y[t][ib]; - const __m256i q8 = _mm256_loadu_si256((const __m256i*) b.qs); - const __m256i p = _mm256_madd_epi16(_mm256_maddubs_epi16(aq, _mm256_sign_epi8(q8, q4)), ones); - accf[t] = _mm256_fmadd_ps(_mm256_set1_ps(dx * h2f(b.d)), _mm256_cvtepi32_ps(p), accf[t]); - } - } - for (int t = 0; t < NT; ++t) out[t][r] = hsum8(accf[t]); - } -} - -void iq4nl256_down_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* hq, int nt, float* const* out, - int r0, int r1) { - const block_q8_0* y[8]; - for (int t = 0; t < nt; ++t) y[t] = (const block_q8_0*) hq[t]; - switch (nt) { - case 1: iq4nl_rows<1>(w, row_bytes, n, y, out, r0, r1); break; - case 2: iq4nl_rows<2>(w, row_bytes, n, y, out, r0, r1); break; - case 3: iq4nl_rows<3>(w, row_bytes, n, y, out, r0, r1); break; - case 4: iq4nl_rows<4>(w, row_bytes, n, y, out, r0, r1); break; - default: for (int t0 = 0; t0 < nt; t0 += 4) { - const int k = nt - t0 < 4 ? nt - t0 : 4; - iq4nl256_down_rows(w, row_bytes, n, hq + t0, k, out + t0, r0, r1); - } - } -} - -} // namespace strata::kernels::cpu diff --git a/src/kernels/cpu/iq_avx512.cpp b/src/kernels/cpu/iq_avx512.cpp deleted file mode 100644 index 26d2c5a..0000000 --- a/src/kernels/cpu/iq_avx512.cpp +++ /dev/null @@ -1,273 +0,0 @@ -// src/kernels/cpu/iq_avx512.cpp - plan v0.3 P6: the i-quant expert rows in 512-bit lanes, several tokens at once. -// -// ggml-cpu's x86 dot products for these formats are AVX2 and single-token: every token re-decodes the weights -// and a sign is applied with five instructions per 32 values. Here 64 values are decoded once (8 or 16 grid -// lookups, one 64-bit sign mask, one vector of scales) and every token applies them with a masked subtract, a -// `maddubs` and a `madd`. The arithmetic is ggml's (ggml-cpu/quants.c, the `_generic` references): integer sums -// per block, times d_x * d_y * the format's constant - only the order of the float additions differs. -// -// Formats: IQ2_XXS (16), IQ2_XS (17), IQ3_XXS (18), IQ3_S (21), IQ2_S (22). IQ1_M stays on ggml-cpu (no shipped -// model has IQ1_M expert rows: the 'Coder IQ1_M' pack's gate/up are IQ2_S / IQ3_XXS / IQ3_S). -#include "strata/kernels/cpu/iq_avx512.hpp" - -#define GGML_COMMON_DECL_CPP -#define GGML_COMMON_IMPL_CPP -#include "ggml-common.h" - -#include - -#include -#include -#include - -namespace strata::kernels::cpu { -namespace { - -inline float h2f(uint16_t h) { return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128((int) h))); } -inline uint32_t u32(const uint8_t* p) { uint32_t v; std::memcpy(&v, p, 4); return v; } -inline uint16_t u16(const uint8_t* p) { uint16_t v; std::memcpy(&v, p, 2); return v; } -inline uint64_t u64(const uint8_t* p) { uint64_t v; std::memcpy(&v, p, 8); return v; } - -// E-2: the IQ3 grids by one AVX-512 gather (the same words, the same results) - measured 3-5% SLOWER than the scalar -// lookups on a Ryzen 5 7600 (Zen 4 gathers are microcoded), so opt-in: STRATA_IQ_GATHER=1 -const bool gather = std::getenv("STRATA_IQ_GATHER") != nullptr; -// E-2: software prefetch distance in bytes (STRATA_IQ_PREFETCH; 0 = off): -2-3% gate/up time on IQ3_S decode -// (the rows are read at ~30 GB/s by 6 cores, near what DDR5 with 4 KB pages gives: the pool is memory-bound) -const int prefetch_ahead = [] { - const char* v = std::getenv("STRATA_IQ_PREFETCH"); - return v ? std::atoi(v) : 2048; -}(); - -// lanes 0-7 -> s0, 8-15 -> s1, 16-23 -> s2, 24-31 -> s3 (int16 lanes of a maddubs result: two values each) -inline __m512i scales4(int s0, int s1, int s2, int s3) { - const __m512i idx = _mm512_set_epi16(3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, - 0, 0, 0, 0, 0, 0, 0, 0); - const uint64_t packed = (uint64_t) (uint16_t) s0 | ((uint64_t) (uint16_t) s1 << 16) | - ((uint64_t) (uint16_t) s2 << 32) | ((uint64_t) (uint16_t) s3 << 48); - return _mm512_permutexvar_epi16(idx, _mm512_set1_epi64((long long) packed)); -} - -// ---- per format: 64 values (chunk j of a 256-value block) -> grid magnitudes, sign mask, scales -template struct Fmt; - -template <> struct Fmt<16> { // IQ2_XXS: d, qs[32] u16 - static constexpr int bytes = 66; - static constexpr float K = 0.125f; - static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) { - const uint8_t* q = b + 2 + 16 * j; - const uint32_t a0 = u32(q), a1 = u32(q + 4), b0 = u32(q + 8), b1 = u32(q + 12); - g = _mm512_set_epi64((long long) iq2xxs_grid[b0 >> 24], (long long) iq2xxs_grid[(b0 >> 16) & 255], - (long long) iq2xxs_grid[(b0 >> 8) & 255], (long long) iq2xxs_grid[b0 & 255], - (long long) iq2xxs_grid[a0 >> 24], (long long) iq2xxs_grid[(a0 >> 16) & 255], - (long long) iq2xxs_grid[(a0 >> 8) & 255], (long long) iq2xxs_grid[a0 & 255]); - const uint64_t s = (uint64_t) ksigns_iq2xs[a1 & 127] | ((uint64_t) ksigns_iq2xs[(a1 >> 7) & 127] << 8) | - ((uint64_t) ksigns_iq2xs[(a1 >> 14) & 127] << 16) | ((uint64_t) ksigns_iq2xs[(a1 >> 21) & 127] << 24) | - ((uint64_t) ksigns_iq2xs[b1 & 127] << 32) | ((uint64_t) ksigns_iq2xs[(b1 >> 7) & 127] << 40) | - ((uint64_t) ksigns_iq2xs[(b1 >> 14) & 127] << 48) | ((uint64_t) ksigns_iq2xs[(b1 >> 21) & 127] << 56); - m = _cvtu64_mask64(s); - const int sa = 2 * (int) (a1 >> 28) + 1, sb = 2 * (int) (b1 >> 28) + 1; - sc = scales4(sa, sa, sb, sb); - } -}; - -template <> struct Fmt<17> { // IQ2_XS: d, qs[32] u16 (9-bit grid index + 7-bit sign index), scales[8] - static constexpr int bytes = 74; - static constexpr float K = 0.125f; - static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) { - const uint8_t* q = b + 2 + 16 * j; - uint16_t v[8]; - std::memcpy(v, q, 16); - g = _mm512_set_epi64((long long) iq2xs_grid[v[7] & 511], (long long) iq2xs_grid[v[6] & 511], - (long long) iq2xs_grid[v[5] & 511], (long long) iq2xs_grid[v[4] & 511], - (long long) iq2xs_grid[v[3] & 511], (long long) iq2xs_grid[v[2] & 511], - (long long) iq2xs_grid[v[1] & 511], (long long) iq2xs_grid[v[0] & 511]); - uint64_t s = 0; - for (int l = 0; l < 8; ++l) s |= (uint64_t) ksigns_iq2xs[v[l] >> 9] << (8 * l); - m = _cvtu64_mask64(s); - const uint8_t s0 = b[66 + 2 * j], s1 = b[66 + 2 * j + 1]; - sc = scales4(2 * (s0 & 15) + 1, 2 * (s0 >> 4) + 1, 2 * (s1 & 15) + 1, 2 * (s1 >> 4) + 1); - } -}; - -template <> struct Fmt<22> { // IQ2_S: d, qs[64] (32 grid bytes, 32 sign bytes), qh[8], scales[8] - static constexpr int bytes = 82; - static constexpr float K = 0.125f; - static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) { - const uint8_t* qs = b + 2 + 8 * j; - const uint8_t h0 = b[66 + 2 * j], h1 = b[66 + 2 * j + 1]; - g = _mm512_set_epi64((long long) iq2s_grid[qs[7] | ((h1 << 2) & 0x300)], (long long) iq2s_grid[qs[6] | ((h1 << 4) & 0x300)], - (long long) iq2s_grid[qs[5] | ((h1 << 6) & 0x300)], (long long) iq2s_grid[qs[4] | ((h1 << 8) & 0x300)], - (long long) iq2s_grid[qs[3] | ((h0 << 2) & 0x300)], (long long) iq2s_grid[qs[2] | ((h0 << 4) & 0x300)], - (long long) iq2s_grid[qs[1] | ((h0 << 6) & 0x300)], (long long) iq2s_grid[qs[0] | ((h0 << 8) & 0x300)]); - m = _cvtu64_mask64(u64(b + 2 + 32 + 8 * j)); - const uint8_t s0 = b[74 + 2 * j], s1 = b[74 + 2 * j + 1]; - sc = scales4(2 * (s0 & 15) + 1, 2 * (s0 >> 4) + 1, 2 * (s1 & 15) + 1, 2 * (s1 >> 4) + 1); - } -}; - -template <> struct Fmt<18> { // IQ3_XXS: d, qs[64] grid bytes, 8 x u32 (4 x 7-bit sign index + 4-bit scale) - static constexpr int bytes = 98; - static constexpr float K = 0.25f; - static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) { - const uint8_t* q = b + 2 + 16 * j; - // E-2: one gather of the 16 grid words (the scalar lookups assembled with set_epi32 cost ~30 uops) - g = gather ? _mm512_i32gather_epi32(_mm512_cvtepu8_epi32(_mm_loadu_si128((const __m128i*) q)), iq3xxs_grid, 4) - : _mm512_set_epi32((int) iq3xxs_grid[q[15]], (int) iq3xxs_grid[q[14]], (int) iq3xxs_grid[q[13]], (int) iq3xxs_grid[q[12]], - (int) iq3xxs_grid[q[11]], (int) iq3xxs_grid[q[10]], (int) iq3xxs_grid[q[9]], (int) iq3xxs_grid[q[8]], - (int) iq3xxs_grid[q[7]], (int) iq3xxs_grid[q[6]], (int) iq3xxs_grid[q[5]], (int) iq3xxs_grid[q[4]], - (int) iq3xxs_grid[q[3]], (int) iq3xxs_grid[q[2]], (int) iq3xxs_grid[q[1]], (int) iq3xxs_grid[q[0]]); - const uint32_t a = u32(b + 2 + 64 + 8 * j), c = u32(b + 2 + 64 + 8 * j + 4); - const uint64_t s = (uint64_t) ksigns_iq2xs[a & 127] | ((uint64_t) ksigns_iq2xs[(a >> 7) & 127] << 8) | - ((uint64_t) ksigns_iq2xs[(a >> 14) & 127] << 16) | ((uint64_t) ksigns_iq2xs[(a >> 21) & 127] << 24) | - ((uint64_t) ksigns_iq2xs[c & 127] << 32) | ((uint64_t) ksigns_iq2xs[(c >> 7) & 127] << 40) | - ((uint64_t) ksigns_iq2xs[(c >> 14) & 127] << 48) | ((uint64_t) ksigns_iq2xs[(c >> 21) & 127] << 56); - m = _cvtu64_mask64(s); - const int sa = 2 * (int) (a >> 28) + 1, sb = 2 * (int) (c >> 28) + 1; - sc = scales4(sa, sa, sb, sb); - } -}; - -template <> struct Fmt<21> { // IQ3_S: d, qs[64], qh[8], signs[32], scales[4] - static constexpr int bytes = 110; - static constexpr float K = 1.0f; - static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) { - const uint8_t* q = b + 2 + 16 * j; - const uint32_t h0 = b[66 + 2 * j], h1 = b[66 + 2 * j + 1]; - if (gather) { // E-2: the 9-bit indices (the high bit from qh under a mask), one gather - __m512i idx = _mm512_cvtepu8_epi32(_mm_loadu_si128((const __m128i*) q)); - idx = _mm512_mask_add_epi32(idx, (__mmask16) (h0 | (h1 << 8)), idx, _mm512_set1_epi32(256)); - g = _mm512_i32gather_epi32(idx, iq3s_grid, 4); - } else { -#define G3(k, h, kk) (int) iq3s_grid[q[k] | (((h >> kk) & 1) << 8)] - g = _mm512_set_epi32(G3(15, h1, 7), G3(14, h1, 6), G3(13, h1, 5), G3(12, h1, 4), - G3(11, h1, 3), G3(10, h1, 2), G3(9, h1, 1), G3(8, h1, 0), - G3(7, h0, 7), G3(6, h0, 6), G3(5, h0, 5), G3(4, h0, 4), - G3(3, h0, 3), G3(2, h0, 2), G3(1, h0, 1), G3(0, h0, 0)); -#undef G3 - } - m = _cvtu64_mask64(u64(b + 74 + 8 * j)); - const uint8_t s = b[106 + j]; - const int sa = 2 * (s & 15) + 1, sb = 2 * (s >> 4) + 1; - sc = scales4(sa, sa, sb, sb); - } -}; - -template -inline void row_dot(const uint8_t* row, int nblocks, const block_q8_K* const* y, float* res) { - __m512 accf[NT]; - for (int t = 0; t < NT; ++t) accf[t] = _mm512_setzero_ps(); - const __m512i zero = _mm512_setzero_si512(); - for (int i = 0; i < nblocks; ++i) { - const uint8_t* blk = row + (size_t) i * Fmt::bytes; - // E-2: the weight rows stream from DRAM (4 KB pages when large pages are refused): ask for the bytes a few - // blocks ahead (the next row's start included) before the decode needs them - if (prefetch_ahead > 0) { - const uint8_t* ahead = blk + (size_t) prefetch_ahead; - _mm_prefetch((const char*) ahead, _MM_HINT_T0); - _mm_prefetch((const char*) ahead + 64, _MM_HINT_T0); - } - __m512i acci[NT]; - for (int t = 0; t < NT; ++t) acci[t] = _mm512_setzero_si512(); - for (int j = 0; j < 4; ++j) { - __m512i g, sc; - __mmask64 m; - Fmt::decode(blk, j, g, m, sc); - for (int t = 0; t < NT; ++t) { - const __m512i yv = _mm512_loadu_si512((const void*) (y[t][i].qs + 64 * j)); - const __m512i ys = _mm512_mask_sub_epi8(yv, m, zero, yv); - acci[t] = _mm512_add_epi32(acci[t], _mm512_madd_epi16(_mm512_maddubs_epi16(g, ys), sc)); - } - } - const float dx = h2f(u16(blk)) * Fmt::K; - for (int t = 0; t < NT; ++t) - accf[t] = _mm512_fmadd_ps(_mm512_set1_ps(dx * y[t][i].d), _mm512_cvtepi32_ps(acci[t]), accf[t]); - } - for (int t = 0; t < NT; ++t) res[t] = _mm512_reduce_add_ps(accf[t]); -} - -template -void gu_rows(const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, float* const* ff, - int r0, int r1) { - const block_q8_K* y[NT]; - for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t]; - const int nb = n / QK_K; - float g[NT], u[NT]; - for (int r = r0; r < r1; ++r) { - row_dot(blob + (size_t) r * gu_row, nb, y, g); - row_dot(blob + up_off + (size_t) r * gu_row, nb, y, u); - for (int t = 0; t < NT; ++t) ff[t][r] = (g[t] / (1.f + std::exp(-g[t]))) * u[t]; - } -} - -template -void dot_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out, int r0, int r1) { - const block_q8_K* y[NT]; - for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t]; - float res[NT]; - for (int r = r0; r < r1; ++r) { - row_dot(w + (size_t) r * row_bytes, n / QK_K, y, res); - for (int t = 0; t < NT; ++t) out[t][r] = res[t]; - } -} - -template -void gu_rows_nt(int nt, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, - float* const* ff, int r0, int r1) { - switch (nt) { - case 1: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 2: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 3: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 4: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 5: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 6: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 7: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; - default: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; - } -} - -template -void dot_rows_nt(int nt, const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out, int r0, - int r1) { - switch (nt) { - case 1: dot_rows(w, row_bytes, n, act, out, r0, r1); break; - case 2: dot_rows(w, row_bytes, n, act, out, r0, r1); break; - case 3: dot_rows(w, row_bytes, n, act, out, r0, r1); break; - case 4: dot_rows(w, row_bytes, n, act, out, r0, r1); break; - default: for (int t0 = 0; t0 < nt; t0 += 4) { - const int k = nt - t0 < 4 ? nt - t0 : 4; - dot_rows_nt(k, w, row_bytes, n, act + t0, out + t0, r0, r1); - } - } -} - -} // namespace - -bool iq512_supported(int type) noexcept { - return type == 16 || type == 17 || type == 18 || type == 21 || type == 22; -} - -void iq512_gu_rows(int type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt, - float* const* ff, int r0, int r1) { - switch (type) { - case 16: gu_rows_nt<16>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 17: gu_rows_nt<17>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 18: gu_rows_nt<18>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 21: gu_rows_nt<21>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; - case 22: gu_rows_nt<22>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; - default: break; - } -} - -void iq512_rows(int type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out, - int r0, int r1) { - switch (type) { - case 16: dot_rows_nt<16>(nt, w, row_bytes, n, act, out, r0, r1); break; - case 17: dot_rows_nt<17>(nt, w, row_bytes, n, act, out, r0, r1); break; - case 18: dot_rows_nt<18>(nt, w, row_bytes, n, act, out, r0, r1); break; - case 21: dot_rows_nt<21>(nt, w, row_bytes, n, act, out, r0, r1); break; - case 22: dot_rows_nt<22>(nt, w, row_bytes, n, act, out, r0, r1); break; - default: break; - } -} - -} // namespace strata::kernels::cpu diff --git a/src/kernels/cpu/kq_avx1.cpp b/src/kernels/cpu/kq_avx1.cpp deleted file mode 100644 index fbdf73f..0000000 --- a/src/kernels/cpu/kq_avx1.cpp +++ /dev/null @@ -1,71 +0,0 @@ -// src/kernels/cpu/kq_avx1.cpp - the AVX1 router dot for older CPUs (see kq_avx1.hpp). From rwkeyes' Strata_Dirigo -// fork (MIT), its AVX1 floor. -// -// Measured on the hardware this exists for (Xeon E5-2665, 2x8 cores, AVX only) for one layer's router -// [512 experts x 5120 embeddings]: the scalar std::fma fallback it replaces took 362 ms/layer, a scalar -// mul+add 4.9 ms, and this kernel 2.6 ms - 137x, with no extra memory (the weights stay bf16). -// -// Compiled for AVX (/arch:AVX, -mavx; CMakeLists.txt sets that per source); it is only ever called behind -// cpu_avx1_ok(), so no CPU that lacks AVX can reach it. -#include "strata/kernels/cpu/kq_avx1.hpp" - -#include - -#include - -#if !defined(__AVX__) -#error "kq_avx1.cpp must be compiled with AVX enabled (see the per-source flags in CMakeLists.txt)" -#endif - -namespace strata::kernels::cpu { -namespace { - -// 8 floats -> one float, the same reduction order the AVX2 kernel's hsum_float_8 uses. -inline float hsum_float_8_avx1(__m256 v) { - __m128 lo = _mm256_castps256_ps128(v); - __m128 hi = _mm256_extractf128_ps(v, 1); - lo = _mm_add_ps(lo, hi); - lo = _mm_add_ps(lo, _mm_movehl_ps(lo, lo)); - lo = _mm_add_ss(lo, _mm_shuffle_ps(lo, lo, 0x55)); - return _mm_cvtss_f32(lo); -} - -// 8 bf16 -> 8 f32: a bf16 is the top half of its f32, so widen in 128-bit halves (AVX1 has no -// 256-bit integer ops) and shift each 32-bit lane into the high half. -inline __m256 bf16x8_to_f32x8_avx1(const uint16_t* p) { - const __m128i v = _mm_loadu_si128((const __m128i*) p); - const __m128i z = _mm_setzero_si128(); - const __m128 lo = _mm_castsi128_ps(_mm_slli_epi32(_mm_unpacklo_epi16(v, z), 16)); - const __m128 hi = _mm_castsi128_ps(_mm_slli_epi32(_mm_unpackhi_epi16(v, z), 16)); - return _mm256_insertf128_ps(_mm256_castps128_ps256(lo), hi, 1); -} - -} // namespace - -void bf16_rows_dot_multi_avx1(const uint16_t* w, int rows, int cols, const float* x, int nt, float* out) { - // each row is read once for all `nt` (<= 8) tokens, exactly as the AVX2 kernel does - for (int r = 0; r < rows; ++r) { - const uint16_t* wr = w + (size_t) r * (size_t) cols; - __m256 acc[8]; - for (int t = 0; t < nt; ++t) acc[t] = _mm256_setzero_ps(); - int c = 0; - for (; c + 8 <= cols; c += 8) { - const __m256 wf = bf16x8_to_f32x8_avx1(wr + c); - for (int t = 0; t < nt; ++t) { - const __m256 xv = _mm256_loadu_ps(x + (size_t) t * (size_t) cols + c); - acc[t] = _mm256_add_ps(acc[t], _mm256_mul_ps(wf, xv)); // no FMA on AVX1: mul, then add - } - } - for (int t = 0; t < nt; ++t) { - float s = hsum_float_8_avx1(acc[t]); - for (; c < cols; ++c) { // cols % 8 != 0 tail (cols % 8 == 0 today) - const uint32_t bits = (uint32_t) wr[c] << 16; - float wf; std::memcpy(&wf, &bits, sizeof wf); - s += wf * x[(size_t) t * (size_t) cols + c]; - } - out[(size_t) t * (size_t) rows + r] = s; - } - } -} - -} // namespace strata::kernels::cpu diff --git a/src/kernels/cpu/kq_avx2.cpp b/src/kernels/cpu/kq_avx2.cpp deleted file mode 100644 index a347311..0000000 --- a/src/kernels/cpu/kq_avx2.cpp +++ /dev/null @@ -1,265 +0,0 @@ -// src/kernels/cpu/kq_avx2.cpp - Unsloth UD-Q4_K_XL's expert rows (Q4_K gate/up, Q5_1 and Q8_0 down) for several -// tokens at once, BIT-EXACT against ggml-cpu's own dot products. -// -// ggml-cpu is built for AVX2 here (STRATA_PORTABLE: GGML_AVX2=ON, GGML_AVX512=OFF), so its vec_dot for these formats -// is the __AVX2__ branch of ggml-cpu/arch/x86/quants.c: ggml_vec_dot_q4_K_q8_K, ggml_vec_dot_q5_1_q8_1, -// ggml_vec_dot_q8_0_q8_0. The functions below are those branches with the loop over tokens moved inside the loop -// over blocks: everything that depends only on the weights (the 4-bit unpacking, the 6-bit scales and mins, the -// fifth bits, the absolute values of the Q8_0 weights, the fp16 scales) is done once per block, and every token then -// runs exactly ggml's integer chain and ggml's float operations in ggml's order - so each token's result is ggml's -// to the bit (native_expert_parity checks it), whatever the number of tokens. Unlike the i-quant kernels (#152) -// the group size therefore never changes an answer. -// -// The gain is the weight-side work and the weight bytes, read once per verify window instead of once per token. -#include "strata/kernels/cpu/kq_avx2.hpp" - -#define GGML_COMMON_DECL_CPP -#define GGML_COMMON_IMPL_CPP -#include "ggml-common.h" - -#include - -#include -#include - -namespace strata::kernels::cpu { -namespace { - -constexpr int MAXT = 8; // the verify window's tokens per group (kVerifyMaxT) - -inline float h2f(ggml_half h) { - uint16_t u; - std::memcpy(&u, &h, 2); - return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128((int) u))); -} -// the fp16 pair {d, dmin} / {d, m} / {d, s} a block starts with (a union in ggml-common.h's C++ declarations) -inline float half_at(const void* block, int i) { - ggml_half h; - std::memcpy(&h, (const uint8_t*) block + 2 * i, 2); - return h2f(h); -} - -// ---- ggml's helpers (ggml-cpu/arch/x86/quants.c, the AVX2 / non-VNNI forms), verbatim -inline float hsum_float_8(const __m256 x) { - __m128 res = _mm256_extractf128_ps(x, 1); - res = _mm_add_ps(res, _mm256_castps256_ps128(x)); - res = _mm_add_ps(res, _mm_movehl_ps(res, res)); - res = _mm_add_ss(res, _mm_movehdup_ps(res)); - return _mm_cvtss_f32(res); -} -inline __m256i bytes_from_bits_32(const uint8_t* x) { - uint32_t x32; - std::memcpy(&x32, x, sizeof(uint32_t)); - const __m256i shuf_mask = _mm256_set_epi64x(0x0303030303030303, 0x0202020202020202, 0x0101010101010101, - 0x0000000000000000); - __m256i bytes = _mm256_shuffle_epi8(_mm256_set1_epi32((int) x32), shuf_mask); - const __m256i bit_mask = _mm256_set1_epi64x(0x7fbfdfeff7fbfdfe); - bytes = _mm256_or_si256(bytes, bit_mask); - return _mm256_cmpeq_epi8(bytes, _mm256_set1_epi64x(-1)); -} -inline __m256i bytes_from_nibbles_32(const uint8_t* rsi) { - const __m128i tmp = _mm_loadu_si128((const __m128i*) rsi); - const __m256i bytes = _mm256_insertf128_si256(_mm256_castsi128_si256(tmp), _mm_srli_epi16(tmp, 4), 1); - const __m256i lowMask = _mm256_set1_epi8(0xF); - return _mm256_and_si256(lowMask, bytes); -} -inline __m256 sum_i16_pairs_float(const __m256i x) { - const __m256i ones = _mm256_set1_epi16(1); - return _mm256_cvtepi32_ps(_mm256_madd_epi16(ones, x)); -} -inline __m256 mul_sum_us8_pairs_float(const __m256i ax, const __m256i sy) { - return sum_i16_pairs_float(_mm256_maddubs_epi16(ax, sy)); -} -alignas(32) const uint8_t k_shuffle[256] = { - 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, - 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, - 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, - 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, - 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, - 10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11, - 12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13, - 14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15}; -inline __m256i get_scale_shuffle_k4(int i) { return _mm256_loadu_si256((const __m256i*) k_shuffle + i); } - -// ---- Q4_K x Q8_K (ggml_vec_dot_q4_K_q8_K, __AVX2__) -void q4k_dot(const block_q4_K* x, int nb, const void* const* act, int nt, float* res) { - static const uint32_t kmask1 = 0x3f3f3f3f, kmask2 = 0x0f0f0f0f, kmask3 = 0x03030303; - const __m256i m4 = _mm256_set1_epi8(0xF); - __m256 acc[MAXT]; - __m128 acc_m[MAXT]; - for (int t = 0; t < nt; ++t) { acc[t] = _mm256_setzero_ps(); acc_m[t] = _mm_setzero_ps(); } - for (int i = 0; i < nb; ++i) { - const float xd = half_at(&x[i], 0), xdmin = half_at(&x[i], 1); - uint32_t utmp[4]; - std::memcpy(utmp, x[i].scales, 12); - utmp[3] = ((utmp[2] >> 4) & kmask2) | (((utmp[1] >> 6) & kmask3) << 4); - const uint32_t uaux = utmp[1] & kmask1; - utmp[1] = (utmp[2] & kmask2) | (((utmp[0] >> 6) & kmask3) << 4); - utmp[2] = uaux; - utmp[0] &= kmask1; - const __m256i mins_and_scales = _mm256_cvtepu8_epi16(_mm_set_epi32((int) utmp[3], (int) utmp[2], - (int) utmp[1], (int) utmp[0])); - const __m128i mins = _mm256_extracti128_si256(mins_and_scales, 1); - const __m128i sc128 = _mm256_extracti128_si256(mins_and_scales, 0); - const __m256i scales = _mm256_insertf128_si256(_mm256_castsi128_si256(sc128), sc128, 1); - __m256i scale_l[4], scale_h[4], q4l[4], q4h[4]; - const uint8_t* q4 = x[i].qs; - for (int j = 0; j < QK_K / 64; ++j) { - scale_l[j] = _mm256_shuffle_epi8(scales, get_scale_shuffle_k4(2 * j + 0)); - scale_h[j] = _mm256_shuffle_epi8(scales, get_scale_shuffle_k4(2 * j + 1)); - const __m256i q4bits = _mm256_loadu_si256((const __m256i*) q4); - q4 += 32; - q4l[j] = _mm256_and_si256(q4bits, m4); - q4h[j] = _mm256_and_si256(_mm256_srli_epi16(q4bits, 4), m4); - } - for (int t = 0; t < nt; ++t) { - const block_q8_K* y = (const block_q8_K*) act[t] + i; - const float d = y->d * xd; - const float dmin = -y->d * xdmin; - const int8_t* q8 = y->qs; - const __m256i q8sums = _mm256_loadu_si256((const __m256i*) y->bsums); - const __m128i q8s = _mm_hadd_epi16(_mm256_extracti128_si256(q8sums, 0), _mm256_extracti128_si256(q8sums, 1)); - const __m128i prod = _mm_madd_epi16(mins, q8s); - acc_m[t] = _mm_fmadd_ps(_mm_set1_ps(dmin), _mm_cvtepi32_ps(prod), acc_m[t]); - __m256i sumi = _mm256_setzero_si256(); - for (int j = 0; j < QK_K / 64; ++j) { - const __m256i q8l = _mm256_loadu_si256((const __m256i*) q8); - q8 += 32; - __m256i p16l = _mm256_maddubs_epi16(q4l[j], q8l); - p16l = _mm256_madd_epi16(scale_l[j], p16l); - const __m256i q8h = _mm256_loadu_si256((const __m256i*) q8); - q8 += 32; - __m256i p16h = _mm256_maddubs_epi16(q4h[j], q8h); - p16h = _mm256_madd_epi16(scale_h[j], p16h); - sumi = _mm256_add_epi32(sumi, _mm256_add_epi32(p16l, p16h)); - } - acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(sumi), acc[t]); - } - } - for (int t = 0; t < nt; ++t) { - __m128 m = acc_m[t]; - m = _mm_add_ps(m, _mm_movehl_ps(m, m)); - m = _mm_add_ss(m, _mm_movehdup_ps(m)); - res[t] = hsum_float_8(acc[t]) + _mm_cvtss_f32(m); - } -} - -// ---- Q5_1 x Q8_1 (ggml_vec_dot_q5_1_q8_1, __AVX2__) -void q5_1_dot(const block_q5_1* x, int nb, const void* const* act, int nt, float* res) { - __m256 acc[MAXT]; - float summs[MAXT]; - for (int t = 0; t < nt; ++t) { acc[t] = _mm256_setzero_ps(); summs[t] = 0.0f; } - for (int ib = 0; ib < nb; ++ib) { - const __m256 dx = _mm256_set1_ps(half_at(&x[ib], 0)); - const float xm = half_at(&x[ib], 1); - __m256i qx = bytes_from_nibbles_32(x[ib].qs); - __m256i bxhi = bytes_from_bits_32(x[ib].qh); - bxhi = _mm256_and_si256(bxhi, _mm256_set1_epi8(0x10)); - qx = _mm256_or_si256(qx, bxhi); - for (int t = 0; t < nt; ++t) { - const block_q8_1* y = (const block_q8_1*) act[t] + ib; - summs[t] += xm * half_at(y, 1); - const __m256 dy = _mm256_set1_ps(half_at(y, 0)); - const __m256i qy = _mm256_loadu_si256((const __m256i*) y->qs); - const __m256 q = mul_sum_us8_pairs_float(qx, qy); - acc[t] = _mm256_fmadd_ps(q, _mm256_mul_ps(dx, dy), acc[t]); - } - } - for (int t = 0; t < nt; ++t) res[t] = hsum_float_8(acc[t]) + summs[t]; -} - -// ---- Q8_0 x Q8_0 (ggml_vec_dot_q8_0_q8_0, __AVX2__; mul_sum_i8_pairs_float without AVX-VNNI-INT8) -void q8_0_dot(const block_q8_0* x, int nb, const void* const* act, int nt, float* res) { - __m256 acc[MAXT]; - for (int t = 0; t < nt; ++t) acc[t] = _mm256_setzero_ps(); - for (int ib = 0; ib < nb; ++ib) { - const float xd = h2f(x[ib].d); - const __m256i qx = _mm256_loadu_si256((const __m256i*) x[ib].qs); - const __m256i ax = _mm256_sign_epi8(qx, qx); - for (int t = 0; t < nt; ++t) { - const block_q8_0* y = (const block_q8_0*) act[t] + ib; - const __m256 d = _mm256_set1_ps(xd * h2f(y->d)); - const __m256i qy = _mm256_loadu_si256((const __m256i*) y->qs); - const __m256i sy = _mm256_sign_epi8(qy, qx); - const __m256 q = mul_sum_us8_pairs_float(ax, sy); - acc[t] = _mm256_fmadd_ps(d, q, acc[t]); - } - } - for (int t = 0; t < nt; ++t) res[t] = hsum_float_8(acc[t]); -} - -void dot_rows(int type, const uint8_t* row, int n, const void* const* act, int nt, float* res) { - switch (type) { - case 12: q4k_dot((const block_q4_K*) row, n / QK_K, act, nt, res); break; - case 7: q5_1_dot((const block_q5_1*) row, n / QK5_1, act, nt, res); break; - case 8: q8_0_dot((const block_q8_0*) row, n / QK8_0, act, nt, res); break; - default: break; - } -} - -} // namespace - -bool kq256_supported(int type) noexcept { return type == 12 || type == 7 || type == 8; } - -void bf16_rows_dot_multi(const uint16_t* w, int rows, int cols, const float* x, int nt, float* out) { - // each row is read once for all `nt` (<= 8) tokens: the router (2.6 MB per layer) streams once per prediction - for (int r = 0; r < rows; ++r) { - const uint16_t* wr = w + (size_t) r * (size_t) cols; - __m256 acc[8]; - for (int t = 0; t < nt; ++t) acc[t] = _mm256_setzero_ps(); - for (int c = 0; c + 8 <= cols; c += 8) { - const __m256 wf = _mm256_castsi256_ps( - _mm256_slli_epi32(_mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*) (wr + c))), 16)); - for (int t = 0; t < nt; ++t) acc[t] = _mm256_fmadd_ps(wf, _mm256_loadu_ps(x + (size_t) t * cols + c), acc[t]); - } - for (int t = 0; t < nt; ++t) out[(size_t) t * rows + r] = hsum_float_8(acc[t]); // cols % 8 == 0 (2560) - } -} - -void bf16_rows_dot(const uint16_t* w, int rows, int cols, const float* x, float* out) { - for (int r = 0; r < rows; ++r) { - const uint16_t* wr = w + (size_t) r * (size_t) cols; - __m256 acc = _mm256_setzero_ps(); - int c = 0; - for (; c + 8 <= cols; c += 8) { - const __m256i h = _mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*) (wr + c))); - acc = _mm256_fmadd_ps(_mm256_castsi256_ps(_mm256_slli_epi32(h, 16)), _mm256_loadu_ps(x + c), acc); - } - float s = hsum_float_8(acc); - for (; c < cols; ++c) { - const uint32_t b = (uint32_t) wr[c] << 16; - float f; - std::memcpy(&f, &b, 4); - s += f * x[c]; - } - out[r] = s; - } -} - -void kq256_gu_rows(int type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt, - float* const* ff, int r0, int r1) { - for (int t0 = 0; t0 < nt; t0 += MAXT) { - const int m = nt - t0 < MAXT ? nt - t0 : MAXT; - float g[MAXT], u[MAXT]; - for (int r = r0; r < r1; ++r) { - dot_rows(type, blob + (size_t) r * gu_row, n, act + t0, m, g); - dot_rows(type, blob + up_off + (size_t) r * gu_row, n, act + t0, m, u); - // native_gu_rows' own SwiGLU expression: the same bits as the per-token ggml path - for (int t = 0; t < m; ++t) ff[t0 + t][r] = (g[t] / (1.f + std::exp(-g[t]))) * u[t]; - } - } -} - -void kq256_rows(int type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out, - int r0, int r1) { - for (int t0 = 0; t0 < nt; t0 += MAXT) { - const int m = nt - t0 < MAXT ? nt - t0 : MAXT; - float s[MAXT]; - for (int r = r0; r < r1; ++r) { - dot_rows(type, w + (size_t) r * row_bytes, n, act + t0, m, s); - for (int t = 0; t < m; ++t) out[t0 + t][r] = s[t]; - } - } -} - -} // namespace strata::kernels::cpu diff --git a/src/kernels/cpu/native_expert.cpp b/src/kernels/cpu/native_expert.cpp deleted file mode 100644 index 13bae52..0000000 --- a/src/kernels/cpu/native_expert.cpp +++ /dev/null @@ -1,171 +0,0 @@ -// src/kernels/cpu/native_expert.cpp - plan v0.3 P6: native (GGUF-form) experts on the CPU through ggml-cpu. -// See the header. Nothing here is Strata arithmetic: the activation quantizers and the row dot products are -// ggml-cpu's, so an IQ expert computes what llama.cpp's CPU backend computes for it. -#include "strata/kernels/cpu/native_expert.hpp" -#include "strata/kernels/cpu/expert.hpp" -#include "strata/kernels/cpu/iq_avx512.hpp" -#include "strata/kernels/cpu/iq_avx2.hpp" -#include "strata/kernels/cpu/kq_avx2.hpp" -#include "strata/kernels/cpu/expert_layout.hpp" - -#include "ggml.h" -#include "ggml-cpu.h" - -#include -#include -#include - -namespace strata::kernels::cpu { -namespace { - -const ggml_type_traits_cpu* traits(int type) { return ggml_get_type_traits_cpu((ggml_type) type); } - -void init_once() { - static std::once_flag once; - std::call_once(once, [] { ggml_cpu_init(); }); -} - -} // namespace - -bool native_experts_available() noexcept { return true; } - -bool native_fmt(int gu_type, int d_type, int64_t n_embd, int64_t n_ff, NativeFmt& f, std::string& err) { - init_once(); - const ggml_type_traits_cpu* tg = traits(gu_type); - const ggml_type_traits_cpu* td = traits(d_type); - if (tg == nullptr || tg->vec_dot == nullptr || td == nullptr || td->vec_dot == nullptr) { - err = "native experts: ggml-cpu has no dot product for type " + std::to_string(tg && tg->vec_dot ? d_type : gu_type); - return false; - } - const ggml_type_traits_cpu* ag = traits(tg->vec_dot_type); - const ggml_type_traits_cpu* ad = traits(td->vec_dot_type); - if (ag == nullptr || ag->from_float == nullptr || ad == nullptr || ad->from_float == nullptr) { - 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"; - return false; - } - f.gu_type = gu_type; - f.d_type = d_type; - f.gu_act = (int) tg->vec_dot_type; - f.d_act = (int) td->vec_dot_type; - f.n_embd = n_embd; - f.n_ff = n_ff; - f.gu_row = ggml_row_size((ggml_type) gu_type, n_embd); - f.d_row = ggml_row_size((ggml_type) d_type, n_ff); - f.up_off = f.gu_row * (size_t) n_ff; - f.down_off = 2 * f.up_off; - f.bytes = f.down_off + f.d_row * (size_t) n_embd; - f.act_bytes = ggml_row_size(tg->vec_dot_type, n_embd); - f.h_bytes = ggml_row_size(td->vec_dot_type, n_ff); - if (f.act_bytes > kNativeActBytes || f.h_bytes > kNativeHBytes) { - err = "native experts: activation larger than the pool's buffers"; - return false; - } - return true; -} - -void native_quant_act(const NativeFmt& f, const float* x, void* dst) { - traits(f.gu_act)->from_float(x, dst, f.n_embd); -} - -void native_quant_h(const NativeFmt& f, const float* h, void* dst) { - traits(f.d_act)->from_float(h, dst, f.n_ff); -} - -void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const* act, int nt, float* const* ff, - int r0, int r1) { - // the multi-token kernels decode the weights once for all tokens: 2.0-2.4x ggml-cpu at three tokens, no faster - // at one (all are bound by the codebook lookups, ~5 GB/s per core), measured by native_expert_parity. AVX-512 - // first, then the AVX-2 one (Zen 2/3, Intel 12th-14th gen). STRATA_NO_IQ512 drops an AVX-512 CPU to the - // AVX-2 kernel, STRATA_NO_IQ256 drops the AVX-2 kernel; ggml-cpu's single-token vec_dot is reached only with - // both set (and on a CPU without AVX-512, STRATA_NO_IQ512 changes nothing). - static const bool avx512 = cpu_avx512_ok() && std::getenv("STRATA_NO_IQ512") == nullptr; - // STRATA_NO_IQ256 drops the AVX-2 kernel. cpu_avx2_ok() is ALSO required: iq_avx2.cpp and kq_avx2.cpp - // are compiled /arch:AVX2 and use AVX2 and FMA3, so calling them on a CPU without either is an - // illegal instruction, not a slow path. The gate sat next to `avx512` above, which does test - // cpu_avx512_ok(), and that asymmetry is what let a pre-Haswell CPU reach iq256_gu_rows. - // Without it this falls through to ggml-cpu's vec_dot below, which is compiled for whatever - // baseline the build selected (AVX1 here) and covers the same types - IQ2_XXS and IQ2_S among - // them. That path loops over tokens itself, so it is correct for any `nt`, not just one. - static const bool avx2 = cpu_avx2_ok() && std::getenv("STRATA_NO_IQ256") == nullptr; - // #152: from how many tokens the multi-token kernels run (ggml's vec_dot below that). The default 2 is the - // measured-fastest rule, but a token's expert rows then round differently alone than in a group, so greedy output - // can depend on how many drafts a verify window held. STRATA_IQ_MT_MIN=1 (opt-in, 0.1.30) uses the multi-token - // kernels for every group: output independent of the drafting, at a measured -1..-3% decode on IQ3_S (AVX-512). - static const int mt_min = [] { const char* e = std::getenv("STRATA_IQ_MT_MIN"); return e ? std::atoi(e) : 2; }(); - // Unsloth UD-Q4_K_XL's Q4_K gate/up: the multi-token kernel is bit-exact against ggml's per-token dot (any group - // size, no #152 rule). Opt-in, STRATA_KQ256=1: measured no faster in the engine (a window's expert groups hold - // ~1.4 tokens and the weights stay in L1 across ggml's per-token calls; 1.01-1.13x in native_expert_parity). - static const bool kq = [] { const char* v = std::getenv("STRATA_KQ256"); return cpu_avx2_ok() && v != nullptr && std::atoi(v) != 0; }(); - if (kq && f.gu_type == 12 && nt >= 2) { // one token: ggml's own dot below (the same bits, less overhead) - kq256_gu_rows(f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act, nt, ff, r0, r1); - return; - } - // A format with only an AVX-2 kernel (IQ4_XS, #415) takes it on AVX-2 CPUs only: an AVX-512 CPU keeps ggml-cpu for - // it, as before (its rows would round differently). Each kernel only for the formats it implements: falling - // through an empty switch would leave ff unwritten instead of falling back to ggml-cpu. - static const bool cpu512 = cpu_avx512_ok(); - if (nt >= mt_min && (iq512_supported(f.gu_type) || (!cpu512 && iq256_supported(f.gu_type)))) { - if (avx512 && iq512_supported(f.gu_type)) { - iq512_gu_rows(f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act, nt, ff, r0, r1); - return; - } - if (avx2 && iq256_supported(f.gu_type)) { - iq256_gu_rows(f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act, nt, ff, r0, r1); - return; - } - } - const ggml_vec_dot_t dot = traits(f.gu_type)->vec_dot; - const int n = (int) f.n_embd; - for (int r = r0; r < r1; ++r) { - const uint8_t* gr = blob + (size_t) r * f.gu_row; - const uint8_t* ur = blob + f.up_off + (size_t) r * f.gu_row; - for (int t = 0; t < nt; ++t) { - float g = 0.f, u = 0.f; - dot(n, &g, 0, gr, 0, act[t], 0, 1); - dot(n, &u, 0, ur, 0, act[t], 0, 1); - ff[t][r] = (g / (1.f + std::exp(-g))) * u; - } - } -} - -void native_down_rows(const NativeFmt& f, const uint8_t* blob, const void* const* hq, int nt, float* const* out, - int r0, int r1) { - // IQ4_NL down rows: the AVX-2 multi-token kernel decodes the nibbles and absolutises the weights once per - // block instead of once per token; ggml-cpu's dot is single-token. STRATA_NO_IQ4NL falls back to it. - static const bool iq4nl_mt = std::getenv("STRATA_NO_IQ4NL") == nullptr; - static const int mt_min = [] { const char* e = std::getenv("STRATA_IQ_MT_MIN"); return e ? std::atoi(e) : 2; }(); - static const bool kq = [] { const char* v = std::getenv("STRATA_KQ256"); return v != nullptr && std::atoi(v) != 0; }(); - // Both multi-token kernels below are /arch:AVX2 translation units (kq_avx2.cpp and iq_avx2.cpp), - // so a CPU without AVX2 has to reach ggml-cpu's vec_dot instead - same reasoning as the gate/up - // rows above, where `avx512` tested cpu_avx512_ok() and `avx2` did not. - if (cpu_avx2_ok() && kq && nt >= 2 && (f.d_type == 7 || f.d_type == 8)) { // Q5_1 / Q8_0 down: bit-exact, any group size - kq256_rows(f.d_type, blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1); - return; - } - if (cpu_avx2_ok() && nt >= mt_min && f.d_type == 20 && iq4nl_mt) { // #152: the same rule as the gate/up rows - iq4nl256_down_rows(blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1); - return; - } - const ggml_vec_dot_t dot = traits(f.d_type)->vec_dot; - const int n = (int) f.n_ff; - for (int r = r0; r < r1; ++r) { - const uint8_t* dr = blob + f.down_off + (size_t) r * f.d_row; - for (int t = 0; t < nt; ++t) { - float s = 0.f; - dot(n, &s, 0, dr, 0, hq[t], 0, 1); - out[t][r] = s; - } - } -} - -} // namespace strata::kernels::cpu diff --git a/src/kernels/cpu/pool.cpp b/src/kernels/cpu/pool.cpp deleted file mode 100644 index 3d6460d..0000000 --- a/src/kernels/cpu/pool.cpp +++ /dev/null @@ -1,783 +0,0 @@ -// src/kernels/cpu/pool.cpp - P2.S3: the CPU expert pool. Read pool.hpp first; it explains the protocol. -#include "strata/kernels/cpu/pool.hpp" -#include "strata/core/progress.hpp" -#include "strata/kernels/cpu/expert_layout.hpp" - -#include -#include -#include -#include - -#include -#include - -#if defined(_WIN32) -#define WIN32_LEAN_AND_MEAN -#include -#include "pool_affinity_win.hpp" -#else -#include -#include -#include "pool_affinity_linux.hpp" -#endif - -namespace strata::kernels::cpu { - -namespace { -constexpr uint64_t pack_head(uint32_t epoch, uint32_t n, uint32_t i) { - return ((uint64_t) epoch << 32) | ((uint64_t) n << 16) | (uint64_t) i; -} -} // namespace - -CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity) { - CpuTopology topo; -#if defined(_WIN32) - // Ask the OS rather than assuming a layout. `hardware_concurrency()` returns LOGICAL processors, and on - // every SMT machine half of them are siblings - pinning one worker to each of the first N would put two - // workers on each physical core and halve the bandwidth the expert kernel is bound by. - DWORD len = 0; - GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &len); - if (len == 0) { - // Preserve group identity even when detailed core topology is unavailable. - const WORD groups = GetActiveProcessorGroupCount(); - for (WORD group = 0; group < groups; ++group) { - const DWORD count = GetActiveProcessorCount(group); - if (count == 0 || count == (DWORD) -1 || count > 64) continue; - for (DWORD i = 0; i < count; ++i) topo.worker_cores.push_back((int) group * 64 + (int) i); - } - if (skip_first && !topo.worker_cores.empty()) { - topo.host_core = topo.worker_cores.front(); - topo.worker_cores.erase(topo.worker_cores.begin()); - } - return topo; - } - std::vector buf(len); - if (GetLogicalProcessorInformationEx(RelationProcessorCore, - (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) buf.data(), &len)) { - const char* p = buf.data(); - const char* end = p + len; - struct CoreDesc { - uint8_t efficiency = 0; - bool has_smt = false; - std::vector lps; - }; - std::vector descs; - while (p < end) { - const auto* e = (const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) p; - if (e->Relationship == RelationProcessorCore) { - CoreDesc cd; - cd.efficiency = e->Processor.EfficiencyClass; - cd.has_smt = (e->Processor.Flags & LTP_PC_SMT) != 0; - for (WORD group = 0; group < e->Processor.GroupCount; ++group) { - const GROUP_AFFINITY& g = e->Processor.GroupMask[group]; - for (int bit = 0; bit < 64; ++bit) { - if (g.Mask & (KAFFINITY(1) << bit)) { - cd.lps.push_back((int) (g.Group * 64 + bit)); - } - } - } - if (!cd.lps.empty()) { - descs.push_back(std::move(cd)); - } - } - p += e->Size; - } - - uint8_t min_eff = 255, max_eff = 0; - for (const auto& c : descs) { - min_eff = (std::min)(min_eff, c.efficiency); - max_eff = (std::max)(max_eff, c.efficiency); - } - - topo.is_hybrid = (max_eff > min_eff); - if (topo.is_hybrid) { - for (const auto& c : descs) { - if (c.efficiency == max_eff) { - topo.p_cores++; - topo.p_threads += (int) c.lps.size(); - } else { - topo.e_cores++; - } - } - } else { - topo.p_cores = (int) descs.size(); - for (const auto& c : descs) topo.p_threads += (int) c.lps.size(); - } - - if (affinity == PoolAffinity::All || !topo.is_hybrid) { - // #642 (from Hardin22's fork): on a hybrid CPU the P-cores first (the host takes the first of them), so a - // pool smaller than the core count (setup's --pool-workers for a hybrid CPU) runs on the P-cores and the - // first E-cores rather than on whatever the OS numbered first. All cores alike: the order is unchanged. - if (topo.is_hybrid) - std::stable_sort(descs.begin(), descs.end(), - [](const CoreDesc& x, const CoreDesc& y) { return x.efficiency > y.efficiency; }); - for (const auto& c : descs) topo.worker_cores.push_back(c.lps[0]); - if (skip_first && !topo.worker_cores.empty()) { - topo.host_core = topo.worker_cores.front(); - topo.worker_cores.erase(topo.worker_cores.begin()); - } - return topo; - } - - // Hybrid CPU with Auto or PCores affinity: - // Prioritize Performance cores: - // 1. Primary logical processor of each P-core (avoids SMT resource contention) - // 2. SMT sibling logical processors of P-cores - // 3. E-cores (only as overflow in Auto mode) - std::vector p_primaries; - std::vector p_siblings; - std::vector e_cores; - - for (const auto& c : descs) { - if (c.efficiency == max_eff) { - p_primaries.push_back(c.lps[0]); - for (size_t s = 1; s < c.lps.size(); ++s) { - p_siblings.push_back(c.lps[s]); - } - } else { - for (int lp : c.lps) e_cores.push_back(lp); - } - } - - if (skip_first && !p_primaries.empty()) { - topo.host_core = p_primaries.front(); - p_primaries.erase(p_primaries.begin()); - } - - for (int cpu : p_primaries) topo.worker_cores.push_back(cpu); - for (int cpu : p_siblings) topo.worker_cores.push_back(cpu); - if (affinity != PoolAffinity::PCores) { - for (int cpu : e_cores) topo.worker_cores.push_back(cpu); - } - return topo; - } -#else - // The logical CPUs this process may run on, ONE PER PHYSICAL CORE (issue #40): SMT siblings share a core's - // load/store bandwidth, so a worker on each would put two workers on one core, as the Windows branch above - // explains. sysfs names each CPU's (package, core); the first allowed CPU of each pair is kept, so a taskset - // that leaves out the first sibling still gets its core. Without sysfs every allowed CPU counts, as before. - auto topo_read = [](int cpu, const char* what) -> long { - char path[96]; - std::snprintf(path, sizeof path, "/sys/devices/system/cpu/cpu%d/topology/%s", cpu, what); - long v = -1; - if (std::FILE* f = std::fopen(path, "r")) { - if (std::fscanf(f, "%ld", &v) != 1) v = -1; - std::fclose(f); - } - return v; - }; - auto cap_read = [](int cpu) -> long { - char path[96]; - std::snprintf(path, sizeof path, "/sys/devices/system/cpu/cpu%d/cpu_capacity", cpu); - long v = -1; - if (std::FILE* f = std::fopen(path, "r")) { - if (std::fscanf(f, "%ld", &v) != 1) v = -1; - std::fclose(f); - } - return v; - }; - - std::vector allowed; - std::vector allowed_mask; - if (detail::get_thread_affinity(allowed_mask, &allowed) != 0) { - for (unsigned i = 0; i < std::thread::hardware_concurrency(); ++i) allowed.push_back((int) i); - } - - struct CoreLinux { - int cpu = -1; - long pkg = -1; - long core = -1; - long cap = -1; - bool is_sibling = false; - }; - std::vector all_cpus; - std::vector> seen_phys; - long max_cap = 0, min_cap = 1000000; - - for (int cpu : allowed) { - CoreLinux cl; - cl.cpu = cpu; - cl.pkg = topo_read(cpu, "physical_package_id"); - cl.core = topo_read(cpu, "core_id"); - cl.cap = cap_read(cpu); - if (cl.cap > 0) { - max_cap = (std::max)(max_cap, cl.cap); - min_cap = (std::min)(min_cap, cl.cap); - } - if (cl.pkg >= 0 && cl.core >= 0) { - const std::pair key{cl.pkg, cl.core}; - if (std::find(seen_phys.begin(), seen_phys.end(), key) != seen_phys.end()) { - cl.is_sibling = true; - } else { - seen_phys.push_back(key); - } - } - all_cpus.push_back(cl); - } - - topo.is_hybrid = (max_cap > 0 && max_cap > min_cap); - if (topo.is_hybrid) { - for (const auto& cl : all_cpus) { - if (cl.cap == max_cap) { - if (!cl.is_sibling) topo.p_cores++; - topo.p_threads++; - } else { - if (!cl.is_sibling) topo.e_cores++; - } - } - } else { - topo.p_cores = (int) seen_phys.size(); - topo.p_threads = (int) all_cpus.size(); - } - - if (affinity == PoolAffinity::All || !topo.is_hybrid) { - if (topo.is_hybrid) // #642: the P-cores first (see the Windows branch) - std::stable_sort(all_cpus.begin(), all_cpus.end(), - [](const CoreLinux& x, const CoreLinux& y) { return x.cap > y.cap; }); - for (const auto& cl : all_cpus) { - if (!cl.is_sibling) topo.worker_cores.push_back(cl.cpu); - } - if (skip_first && !topo.worker_cores.empty()) { - topo.host_core = topo.worker_cores.front(); - topo.worker_cores.erase(topo.worker_cores.begin()); - } - return topo; - } - - // Hybrid CPU on Linux: - std::vector p_primaries; - std::vector p_siblings; - std::vector e_cores; - - for (const auto& cl : all_cpus) { - if (cl.cap == max_cap) { - if (!cl.is_sibling) p_primaries.push_back(cl.cpu); - else p_siblings.push_back(cl.cpu); - } else { - e_cores.push_back(cl.cpu); - } - } - - if (skip_first && !p_primaries.empty()) { - topo.host_core = p_primaries.front(); - p_primaries.erase(p_primaries.begin()); - } - - for (int cpu : p_primaries) topo.worker_cores.push_back(cpu); - for (int cpu : p_siblings) topo.worker_cores.push_back(cpu); - if (affinity != PoolAffinity::PCores) { - for (int cpu : e_cores) topo.worker_cores.push_back(cpu); - } - return topo; -#endif - return topo; -} - -std::vector physical_cores(bool skip_first, PoolAffinity affinity) { - return detect_cpu_topology(skip_first, affinity).worker_cores; -} - -namespace { - -bool pin_this_thread(int core, [[maybe_unused]] int worker = -1) { - if (core < 0) return false; -#if defined(_WIN32) - return detail::set_thread_group_affinity(core, worker); -#else - const int error = detail::pin_thread_to_cpu(core); - if (error != 0) - std::fprintf(stderr, "strata cpu pool: affinity for worker %d (CPU %d) failed: %d; previous affinity kept\n", - worker, core, error); - return error == 0; -#endif -} - -} // namespace - -ThreadAffinity pin_current_thread(int core) { - if (core < 0) return {}; -#if defined(_WIN32) - ThreadAffinity previous; - ULONG target = 0; - if (!detail::get_thread_cpu_sets(previous.cpu_sets) || !detail::cpu_set_for_core(core, target) || - !SetThreadSelectedCpuSets(GetCurrentThread(), &target, 1)) { - std::fprintf(stderr, "strata cpu pool: host CPU Set selection for processor %d failed: %lu; previous placement kept\n", - core, (unsigned long) GetLastError()); - return {}; - } - previous.valid = true; - return previous; -#else - ThreadAffinity previous; - int error = detail::get_thread_affinity(previous.mask); - if (error == 0) error = detail::pin_thread_to_cpu(core); - if (error != 0) { - std::fprintf(stderr, "strata cpu pool: host affinity for CPU %d failed: %d; previous affinity kept\n", core, error); - return {}; - } - previous.valid = true; - return previous; -#endif -} - -void restore_thread_affinity(const ThreadAffinity& previous) { - if (!previous.valid) return; -#if defined(_WIN32) - // Clearing an originally empty selection restores process-default/all-group eligibility without - // turning the caller's implicit Windows 11 affinity into an explicit single-group hard mask. - if (!SetThreadSelectedCpuSets(GetCurrentThread(), previous.cpu_sets.empty() ? nullptr : previous.cpu_sets.data(), - (ULONG) previous.cpu_sets.size())) - std::fprintf(stderr, "strata cpu pool: host CPU Set restoration failed: %lu\n", - (unsigned long) GetLastError()); -#else - const int error = detail::set_thread_affinity(previous.mask); - if (error != 0) - std::fprintf(stderr, "strata cpu pool: host affinity restoration failed: %d\n", error); -#endif -} - -namespace { -std::atomic g_diag_pool{nullptr}; -void diag_active_pool(std::FILE* f) { - if (const ExpertPool* p = g_diag_pool.load()) p->diag(f); -} -int64_t now_ms() { - return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()) - .count(); -} -} // namespace - -void ExpertPool::diag(std::FILE* f) const { - const uint64_t h = head_.load(); - std::fprintf(f, " expert pool: epoch %u, batch epoch %u: %u of %u jobs claimed, %u done; %u of %d workers parked, " - "%u sleeping; mode %d\n", epoch_.load(), (uint32_t) (h >> 32), (uint32_t) h & 0xffffu, - (uint32_t) (h >> 16) & 0xffffu, done_.load(), parked_.load(), n_, sleepers_.load(), mode_); - std::fprintf(f, " expert pool threads:"); - for (int i = 0; i < n_; ++i) { - const int32_t s = wstate_[(size_t) i].load(); - if (s == kParked) std::fprintf(f, " w%d=parked", i); - else if (s == kSleeping) std::fprintf(f, " w%d=sleeping", i); - else if (s == kBetween) std::fprintf(f, " w%d=draining", i); - else std::fprintf(f, " w%d=job%d", i, s); - } - const int32_t hs = hstate_.load(); - const char* hn = hs == kIdle ? "idle" : hs == kWaitParked ? "waiting for the workers to park" - : hs == kWaitDone ? "waiting for the jobs to finish" : "running a job"; - std::fprintf(f, "; host %s", hn); - if (hs >= 0) std::fprintf(f, " %d", hs); - std::fprintf(f, " for %lld ms\n", (long long) (now_ms() - hstate_ms_.load())); -} - -ExpertPool::ExpertPool(int n_workers, bool pin, bool host_works, PoolAffinity affinity) - : host_works_(host_works), affinity_(affinity), topo_(detect_cpu_topology(true, affinity)) { - if (const char* e = std::getenv("STRATA_POOL_SPIN_US")) // a test knob; see kSpinBeforeSleep - spin_before_sleep_ = std::chrono::microseconds((std::max)(0, std::atoi(e))); - if (n_workers > 0) { - n_ = n_workers; - } else if (topo_.is_hybrid && affinity_ != PoolAffinity::All) { - n_ = (std::max)(1, topo_.p_cores - 1); - } else { - n_ = (int) topo_.worker_cores.size(); - } - if (n_ < 1) n_ = 1; - scratch_.resize((size_t) n_); - wstate_.reset(new std::atomic[(size_t) n_]); - for (int i = 0; i < n_; ++i) wstate_[(size_t) i].store(kParked); - hstate_ms_.store(now_ms()); - g_diag_pool.store(this); - strata::core::diag_pool_fn().store(&diag_active_pool); - split_.resize((size_t) kMaxSplit); - split_multi_.resize((size_t) kMaxSplitMulti); - threads_.reserve((size_t) n_); - for (int i = 0; i < n_; ++i) { - const int core = pin ? (i < (int) topo_.worker_cores.size() ? topo_.worker_cores[(size_t) i] : -1) : -1; - threads_.emplace_back([this, i, core] { - pin_this_thread(core, i); - worker(i); - }); - } -} - -ExpertPool::~ExpertPool() { - const ExpertPool* self = this; - g_diag_pool.compare_exchange_strong(self, nullptr); - stop_.store(true, std::memory_order_release); - // Bump the epoch so a PARKED worker notices the stop flag rather than sleeping through it. - publish(); - for (auto& t : threads_) t.join(); -} - -void ExpertPool::publish() { - // Both sides are seq_cst, and that is the whole lost-wakeup argument: a worker going to sleep does - // `sleepers_++` and then reads `epoch_`, the host does `epoch_++` and then reads `sleepers_`. In one total - // order at least one of them sees the other's write - the worker sees the new epoch and does not sleep, or - // the host sees the sleeper and notifies under the mutex the worker holds until it is inside `wait`. - // On x86 the fetch_add is a locked xadd either way, so this costs the token path nothing. - epoch_.fetch_add(1, std::memory_order_seq_cst); - if (sleepers_.load(std::memory_order_seq_cst) != 0) { - std::lock_guard lk(sleep_mu_); - sleep_cv_.notify_all(); - } -} - -void ExpertPool::worker(int id) { - uint32_t seen = 0; - // ARRIVE at the park before the first wait, so `parked_ == n_` is true from construction. Counting only - // on the RETURN from a drain leaves `parked_` at 0 until each worker has finished one batch, and the first - // `run()` - which waits for `parked_ == n_` before publishing - then deadlocks. It deadlocks on the very - // first call, which is the good case; a version that deadlocked on the second would be far worse. - parked_.fetch_add(1, std::memory_order_acq_rel); - for (;;) { - // Park: wait for work. `_mm_pause` rather than a bare spin because it yields the pipeline to the - // sibling hyperthread; `epoch_` is bumped once per LAYER, not once per expert, so most of these - // iterations are spent here with nothing to do. - // - // **AND NOTHING ELSE HAPPENS IN HERE.** This loop used to do `pauses_.fetch_add(1)` on every iteration - // - a locked read-modify-write, five workers against one cache line - so the workers spent their wait - // invalidating each other's caches and the very line the host writes to publish work. The counter was - // diagnostic and nothing branched on it. See the note on the atomics in pool.hpp. - // - // After `kSpinBeforeSleep` with no work the worker sleeps instead (issue #4). The clock is read once - // every 1024 pauses, so the spin itself is unchanged. - const auto parked_at = std::chrono::steady_clock::now(); - uint32_t spins = 0; - while (epoch_.load(std::memory_order_acquire) == seen) { - if (stop_.load(std::memory_order_relaxed)) return; - _mm_pause(); - if ((++spins & 1023u) != 0) continue; - if (std::chrono::steady_clock::now() - parked_at < spin_before_sleep_) continue; - std::unique_lock lk(sleep_mu_); - wstate_[(size_t) id].store(kSleeping, std::memory_order_relaxed); - sleepers_.fetch_add(1, std::memory_order_seq_cst); - sleep_cv_.wait(lk, [&] { - return epoch_.load(std::memory_order_seq_cst) != seen || stop_.load(std::memory_order_relaxed); - }); - sleepers_.fetch_sub(1, std::memory_order_relaxed); - wstate_[(size_t) id].store(kParked, std::memory_order_relaxed); - } - if (stop_.load(std::memory_order_acquire)) return; - // acquire: the batch this epoch published (`head`, and the description before it) is visible from here - seen = epoch_.load(std::memory_order_acquire); - parked_.fetch_sub(1, std::memory_order_acq_rel); // leaving the park - - // Drain: one claim per iteration, so a slow worker takes fewer experts and a fast one takes more. - // Every job is the same size (all experts are 1,382,400 bytes), so there is nothing to schedule. Only - // this epoch's jobs: if the host has already moved on, the claims fail and the worker parks again. - wstate_[(size_t) id].store(kBetween, std::memory_order_relaxed); - drain(id, scratch_[(size_t) id], seen); - wstate_[(size_t) id].store(kParked, std::memory_order_relaxed); - parked_.fetch_add(1, std::memory_order_acq_rel); // back at the park - } -} - -int ExpertPool::claim(uint32_t epoch) { - uint64_t h = head_.load(std::memory_order_acquire); - for (;;) { - if ((uint32_t) (h >> 32) != epoch) return -1; // not the batch this thread woke for - const uint32_t n = (uint32_t) (h >> 16) & 0xffffu, i = (uint32_t) h & 0xffffu; - if (i >= n) return -1; // exhausted - if (head_.compare_exchange_weak(h, h + 1, std::memory_order_acq_rel, std::memory_order_acquire)) - return (int) i; - } -} - -uint32_t ExpertPool::begin_batch(int n) { - if (n < 0 || n > 0xffff) { - std::fprintf(stderr, "strata: expert pool batch of %d jobs is out of range\n", n); - std::abort(); - } - // Every job of the previous batch has completed (`wait_done`), and a claim of it can no longer succeed, so - // nothing adds to `done` until this batch's first claim - which the release below orders after the reset. - done_.store(0, std::memory_order_relaxed); - const uint32_t e = epoch_.load(std::memory_order_relaxed) + 1; // only the host bumps the epoch - head_.store(pack_head(e, (uint32_t) n, 0), std::memory_order_release); - publish(); - return e; -} - -void ExpertPool::wait_parked(const char* what) { - hstate_.store(kWaitParked, std::memory_order_relaxed); - hstate_ms_.store(now_ms(), std::memory_order_relaxed); - uint32_t spins = 0; - std::chrono::steady_clock::time_point t0{}; - while (parked_.load(std::memory_order_acquire) != (uint32_t) n_) { - _mm_pause(); - if ((++spins & 1023u) != 0) continue; - const auto now = std::chrono::steady_clock::now(); - if (spins == 1024u) t0 = now; - else if (now - t0 > kStall) { - std::fprintf(stderr, "strata: the CPU expert pool stalled %s (%u of %d workers parked) - stopping the engine " - "so the server can start it again (issue #29)\n", - what, parked_.load(), n_); - strata::core::release_gpu_waits(stderr); // #267: the GPU may be spinning on this layer's flag - std::fflush(stderr); - std::abort(); - } - } -} - -void ExpertPool::wait_done(int n) { - hstate_.store(kWaitDone, std::memory_order_relaxed); - hstate_ms_.store(now_ms(), std::memory_order_relaxed); - uint32_t spins = 0, seen = 0; - std::chrono::steady_clock::time_point t0{}; - for (;;) { - const uint32_t d = done_.load(std::memory_order_acquire); - if (d >= (uint32_t) n) return; // `>=`: never a wait that an overshoot outlives - _mm_pause(); - if ((++spins & 1023u) != 0) continue; - const auto now = std::chrono::steady_clock::now(); - if (spins == 1024u || d != seen) { t0 = now; seen = d; } // progress restarts the clock - else if (now - t0 > kStall) { - std::fprintf(stderr, "strata: the CPU expert pool stalled: %u of %d jobs done, %u of %d workers parked - " - "stopping the engine so the server can start it again (issue #29)\n", - d, n, parked_.load(), n_); - strata::core::release_gpu_waits(stderr); // #267 - std::fflush(stderr); - std::abort(); - } - } -} - -void ExpertPool::drain(int id, ExpertScratch& scratch, uint32_t epoch) { - (void) id; - for (;;) { - const int ci = claim(epoch); - if (ci < 0) break; - const uint32_t i = (uint32_t) ci; - if (id >= 0) wstate_[(size_t) id].store(ci, std::memory_order_relaxed); - else { hstate_.store(ci, std::memory_order_relaxed); hstate_ms_.store(now_ms(), std::memory_order_relaxed); } - if (mode_ == 0) { - const ExpertJob& j = jobs_[i]; - s2_expert_vnni_q(j.blob, *j.act, j.out, scratch); - } else if (mode_ == 1) { - const int e = (int) i / parts_a_, part = (int) i % parts_a_; - const int r0 = FF * part / parts_a_, r1 = FF * (part + 1) / parts_a_; - s2_expert_gu_rows(jobs_[e].blob, *jobs_[e].act, split_[(size_t) e].ff, r0, r1); - } else if (mode_ == 2) { - const int e = (int) i / parts_b_, part = (int) i % parts_b_; - const int r0 = H * part / parts_b_, r1 = H * (part + 1) / parts_b_; - s2_expert_down_rows(jobs_[e].blob, split_[(size_t) e].a2, jobs_[e].out, r0, r1); - } else if (mode_ >= 5) { - // plan v0.3 P6: native layers, 5 = gate/up rows, 6 = down rows. The widths are the layer's own - // (NativeFmt n_ff / n_embd: 512 / 2048 for Qwen3.6-35B-A3B), not the canonical pack's FF / H: with - // those, the down phase wrote H - n_embd rows past every output row and the gate/up phase read - // FF - n_ff rows past every expert's gate/up block, and every verify window with a CPU-computed - // expert miss decoded to token 0. - const int per = mode_ == 5 ? (int) nfmt_->n_ff : (int) nfmt_->n_embd; - 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); - const int r1 = (int) std::min(per, r0 + (g1 - r)); - SplitBufMulti& sb = split_multi_[(size_t) e]; - if (mode_ == 5 && q2_native_kernels(nfmt_->gu_type)) { - // a native Q2_0 pack: gate and up rows on the Q2_0 kernels, then SwiGLU - thread_local float gbuf[MAXT][FF], ubuf[MAXT][FF]; - float* gp[MAXT]; - float* up[MAXT]; - for (int t = 0; t < mjobs_[e].nt; ++t) { gp[t] = gbuf[t]; up[t] = ubuf[t]; } - const int nbk = (int) (nfmt_->n_embd / 64); - q2_rows_any(mjobs_[e].blob, nfmt_->gu_row, nbk, mjobs_[e].act, mjobs_[e].nt, gp, r0, r1); - q2_rows_any(mjobs_[e].blob + nfmt_->up_off, nfmt_->gu_row, nbk, mjobs_[e].act, mjobs_[e].nt, up, r0, r1); - for (int t = 0; t < mjobs_[e].nt; ++t) - for (int r = r0; r < r1; ++r) - sb.ff[t][r] = (gbuf[t][r] / (1.f + std::exp(-gbuf[t][r]))) * ubuf[t][r]; - } else if (mode_ == 5) { - float* ff[MAXT]; - for (int t = 0; t < mjobs_[e].nt; ++t) ff[t] = sb.ff[t]; - native_gu_rows(*nfmt_, mjobs_[e].blob, mjobs_[e].nact, mjobs_[e].nt, ff, r0, r1); - } else if (q2_native_kernels(nfmt_->d_type)) { - // Q2_0 down (most IQ layers): the AVX-512 kernel, ggml-cpu has only a scalar one on x86 - const ActQ* a2[MAXT]; - for (int t = 0; t < mjobs_[e].nt; ++t) a2[t] = &sb.a2[t]; - q2_rows_any(mjobs_[e].blob + nfmt_->down_off, nfmt_->d_row, (int) (nfmt_->n_ff / 64), a2, - mjobs_[e].nt, mjobs_[e].out, r0, r1); - } else { - const void* hq[MAXT]; - for (int t = 0; t < mjobs_[e].nt; ++t) hq[t] = sb.hq[t]; - native_down_rows(*nfmt_, mjobs_[e].blob, hq, mjobs_[e].nt, mjobs_[e].out, r0, r1); - } - r += r1 - r0; - } - } else { - // plan v0.3 P6: an equal range of the phase's rows across ALL its experts (a range may span two) - const int per = mode_ == 3 ? FF : H; - const int64_t g0 = mrows_ * (int64_t) i / mtasks_, g1 = mrows_ * (int64_t) (i + 1) / mtasks_; - for (int64_t r = g0; r < g1;) { - const int e = (int) (r / per), r0 = (int) (r % per); - const int r1 = (int) std::min(per, r0 + (g1 - r)); - SplitBufMulti& sb = split_multi_[(size_t) e]; - if (mode_ == 3) { - float* ff[MAXT]; - for (int t = 0; t < mjobs_[e].nt; ++t) ff[t] = sb.ff[t]; - s2_expert_gu_rows_multi(mjobs_[e].blob, mjobs_[e].act, mjobs_[e].nt, ff, r0, r1); - } else { - const ActQ* a2[MAXT]; - for (int t = 0; t < mjobs_[e].nt; ++t) a2[t] = &sb.a2[t]; - s2_expert_down_rows_multi(mjobs_[e].blob, a2, mjobs_[e].nt, mjobs_[e].out, r0, r1); - } - r += r1 - r0; - } - } - done_.fetch_add(1, std::memory_order_release); - } -} - -void ExpertPool::run_phase(int mode, int n_tasks) { - wait_parked("before a phase"); - mode_ = mode; - njobs_ = n_tasks; - const uint32_t e = begin_batch(n_tasks); - if (host_works_) drain(-1, host_scratch_, e); - wait_done(n_tasks); - wait_parked("after a phase"); - hstate_.store(kIdle, std::memory_order_relaxed); - hstate_ms_.store(now_ms(), std::memory_order_relaxed); -} - -void ExpertPool::run_split(ExpertJob* jobs, int n) { - if (n <= 0) return; - if (n > kMaxSplit || n_ == 1 || expert_oracle_q8_0_enabled()) { run(jobs, n); return; } - const auto t0 = std::chrono::steady_clock::now(); - jobs_ = jobs; - const int threads = n_ + (host_works_ ? 1 : 0); - // about three tasks per thread in each phase, so the tail is short - parts_a_ = (std::max)(1, (3 * threads + n - 1) / n); - parts_b_ = parts_a_; - run_phase(1, n * parts_a_); - for (int e = 0; e < n; ++e) act_quant_q8_1(split_[(size_t) e].ff, FF, split_[(size_t) e].a2); - run_phase(2, n * parts_b_); - mode_ = 0; - ms_drain_ += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); -} - -void ExpertPool::run_split_multi(ExpertJobMulti* jobs, int n) { - if (n <= 0) return; - if (n > kMaxSplitMulti || expert_oracle_q8_0_enabled()) { - // one token at a time through the single-token path (the oracle contract has no multi kernel) - std::vector single; - for (int e = 0; e < n; ++e) - for (int t = 0; t < jobs[e].nt; ++t) { - ExpertJob j; - j.blob = jobs[e].blob; - j.act = jobs[e].act[t]; - j.out = jobs[e].out[t]; - single.push_back(j); - } - for (size_t i = 0; i < single.size(); i += kMaxSplit) - run_split(single.data() + i, (int) (std::min)((size_t) kMaxSplit, single.size() - i)); - return; - } - const auto t0 = std::chrono::steady_clock::now(); - mjobs_ = jobs; - const int threads = n_ + (host_works_ ? 1 : 0); - mtasks_ = 3 * threads; - mrows_ = (int64_t) n * FF; - run_phase(3, mtasks_); - const auto t1 = std::chrono::steady_clock::now(); - for (int e = 0; e < n; ++e) - for (int t = 0; t < jobs[e].nt; ++t) - act_quant_q8_1(split_multi_[(size_t) e].ff[t], FF, split_multi_[(size_t) e].a2[t]); - const auto t2 = std::chrono::steady_clock::now(); - mrows_ = (int64_t) n * H; - run_phase(4, mtasks_); - const auto t3 = std::chrono::steady_clock::now(); - ms_multi_gu += std::chrono::duration(t1 - t0).count(); - ms_multi_q += std::chrono::duration(t2 - t1).count(); - ms_multi_down += std::chrono::duration(t3 - t2).count(); - multi_bytes += (int64_t) n * (int64_t) BLOB; - mode_ = 0; - ms_drain_ += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); -} - -void ExpertPool::run_split_multi_native(const NativeFmt& f, ExpertJobMulti* jobs, int n) { - if (n <= 0) return; - const auto t0 = std::chrono::steady_clock::now(); - // more distinct experts than buffers: run them in batches - for (int b0 = 0; b0 < n; b0 += kMaxSplitMulti) { - const int nb = (std::min)(kMaxSplitMulti, n - b0); - mjobs_ = jobs + b0; - nfmt_ = &f; - const int threads = n_ + (host_works_ ? 1 : 0); - mtasks_ = 3 * threads; - mrows_ = (int64_t) nb * f.n_ff; // the layer's widths (see run_phase mode 5 / 6), not FF / H - const auto a = std::chrono::steady_clock::now(); - run_phase(5, mtasks_); - const auto b = std::chrono::steady_clock::now(); - for (int e = 0; e < nb; ++e) - for (int t = 0; t < mjobs_[e].nt; ++t) - if (q2_native_kernels(f.d_type)) act_quant_any(split_multi_[(size_t) e].ff[t], (int) f.n_ff, split_multi_[(size_t) e].a2[t]); - else native_quant_h(f, split_multi_[(size_t) e].ff[t], split_multi_[(size_t) e].hq[t]); - const auto c = std::chrono::steady_clock::now(); - mrows_ = (int64_t) nb * f.n_embd; - run_phase(6, mtasks_); - const auto d = std::chrono::steady_clock::now(); - ms_multi_gu += std::chrono::duration(b - a).count(); - ms_multi_q += std::chrono::duration(c - b).count(); - ms_multi_down += std::chrono::duration(d - c).count(); - } - multi_bytes += (int64_t) n * (int64_t) f.bytes; - mode_ = 0; - ms_drain_ += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); -} - -void ExpertPool::run(ExpertJob* jobs, int n) { - if (n <= 0) return; - if (n_ == 1) { // no workers: run inline, so a single-core machine still produces a token - for (int i = 0; i < n; ++i) s2_expert_vnni_q(jobs[i].blob, *jobs[i].act, jobs[i].out, scratch_[0]); - return; - } - // Wait for every worker to be parked BEFORE touching the batch, so the publish below is the only thing - // that can move a worker into the drain loop. - // - // THE THREE PHASES ARE TIMED SEPARATELY. They were one number, which cannot distinguish a pool that is - // slow at the WORK from one that is slow at the SYNCHRONISATION - and those need opposite fixes. - const auto t_a = std::chrono::steady_clock::now(); - wait_parked("before a batch"); - const auto t_b = std::chrono::steady_clock::now(); - jobs_ = jobs; - njobs_ = n; - mode_ = 0; - const uint32_t e = begin_batch(n); // done, then head (release), then the epoch: the batch is described first - - // ---- **THE HOST DRAINS TOO (R2.2), INSTEAD OF SPINNING ON `done_`.** - // - // The loop below used to be `while (done_ != n) _mm_pause();`. The host is pinned to core 0 - the core - // `physical_cores(true)` deliberately keeps the five workers off - so for the whole drain that core was - // idle while five cores did six cores' worth of work. Measured before the change: 33.7 GB/s against - // 5/6 x 44.14 = 36.8 for five workers and 44.14 for six. - // - // The host claims through the SAME `head_` counter, so this is not a second scheduler and nothing about - // the ordering changes: `head_` is a single `fetch_add`, every job is the same size, and a thread that - // arrives late simply claims nothing. `done_` is still the completion signal and the host still waits for - // it - what changed is only that the host arrives at that wait having done a share of the work. - // - // The host's `done_.fetch_add` is a release for the same reason a worker's is: `j.out` is read by the - // device after `run()` returns, so the write must be published, not merely performed. - if (host_works_) { - for (;;) { - const int ci = claim(e); - if (ci < 0) break; - hstate_.store(ci, std::memory_order_relaxed); - hstate_ms_.store(now_ms(), std::memory_order_relaxed); - const ExpertJob& j = jobs_[ci]; - s2_expert_vnni_q(j.blob, *j.act, j.out, host_scratch_); - done_.fetch_add(1, std::memory_order_release); - } - } - - wait_done(n); - // And park again, so the next `run` starts from a known state. See the header for why `done` alone is - // not enough. - const auto t_c = std::chrono::steady_clock::now(); - wait_parked("after a batch"); - hstate_.store(kIdle, std::memory_order_relaxed); - hstate_ms_.store(now_ms(), std::memory_order_relaxed); - const auto t_d = std::chrono::steady_clock::now(); - - ms_wait_park_ += std::chrono::duration(t_b - t_a).count(); - ms_drain_ += std::chrono::duration(t_c - t_b).count(); - ms_repark_ += std::chrono::duration(t_d - t_c).count(); -} - -} // namespace strata::kernels::cpu diff --git a/src/kernels/cpu/pool_affinity_linux.hpp b/src/kernels/cpu/pool_affinity_linux.hpp deleted file mode 100644 index 0791ac5..0000000 --- a/src/kernels/cpu/pool_affinity_linux.hpp +++ /dev/null @@ -1,69 +0,0 @@ -#pragma once - -#if defined(__linux__) -#include -#include - -#include -#include -#include -#include - -namespace strata::kernels::cpu::detail { - -// CPU_ALLOC and the sized macros also handle kernels whose CPU mask exceeds CPU_SETSIZE. -// Keep the native mask opaque: copy its bytes for storage and use CPU_*_S to inspect it. -class LinuxCpuSet { -public: - explicit LinuxCpuSet(int cpus) : bytes(CPU_ALLOC_SIZE(cpus)), set(CPU_ALLOC(cpus)) { - if (set) CPU_ZERO_S(bytes, set); - } - ~LinuxCpuSet() { CPU_FREE(set); } - LinuxCpuSet(const LinuxCpuSet&) = delete; - LinuxCpuSet& operator=(const LinuxCpuSet&) = delete; - - const size_t bytes; - cpu_set_t* const set; -}; - -// pthread affinity functions return an error number directly; they do not set errno. -// A too-small query buffer returns EINVAL, even when the number of online CPUs is small. -inline int get_thread_affinity(std::vector& mask, std::vector* cpus = nullptr) { - for (int count = CPU_SETSIZE;;) { - LinuxCpuSet current(count); - if (!current.set) return ENOMEM; - const int error = pthread_getaffinity_np(pthread_self(), current.bytes, current.set); - if (error == 0) { - mask.resize(current.bytes / sizeof(unsigned long)); - std::memcpy(mask.data(), current.set, current.bytes); - if (cpus) { - cpus->clear(); - for (int cpu = 0; cpu < count; ++cpu) - if (CPU_ISSET_S(cpu, current.bytes, current.set)) cpus->push_back(cpu); - } - return 0; - } - if (error != EINVAL || count > INT_MAX / 2) return error; - count *= 2; - } -} - -inline int set_thread_affinity(const std::vector& mask) { - constexpr size_t word_bits = sizeof(unsigned long) * CHAR_BIT; - if (mask.empty() || mask.size() > INT_MAX / word_bits) return EINVAL; - LinuxCpuSet target(static_cast(mask.size() * word_bits)); - if (!target.set) return ENOMEM; - std::memcpy(target.set, mask.data(), target.bytes); - return pthread_setaffinity_np(pthread_self(), target.bytes, target.set); -} - -inline int pin_thread_to_cpu(int core) { - if (core < 0 || core == INT_MAX) return EINVAL; - LinuxCpuSet target(core < CPU_SETSIZE ? CPU_SETSIZE : core + 1); - if (!target.set) return ENOMEM; - CPU_SET_S(core, target.bytes, target.set); - return pthread_setaffinity_np(pthread_self(), target.bytes, target.set); -} - -} // namespace strata::kernels::cpu::detail -#endif diff --git a/src/kernels/cpu/pool_affinity_linux_test.cpp b/src/kernels/cpu/pool_affinity_linux_test.cpp deleted file mode 100644 index 6b5752a..0000000 --- a/src/kernels/cpu/pool_affinity_linux_test.cpp +++ /dev/null @@ -1,290 +0,0 @@ -#ifndef _GNU_SOURCE -#define _GNU_SOURCE -#endif - -#include "strata/kernels/cpu/pool.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(__linux__) -#include "pool_affinity_linux.hpp" - -#include -#include -#include - -namespace cpu = strata::kernels::cpu; - -class DynamicCpuSet { -public: - explicit DynamicCpuSet(size_t count) - : count_(count), bytes_(CPU_ALLOC_SIZE(count)), set_(CPU_ALLOC(count)) { - if (set_) CPU_ZERO_S(bytes_, set_); - } - - ~DynamicCpuSet() { - if (set_) CPU_FREE(set_); - } - - DynamicCpuSet(const DynamicCpuSet&) = delete; - DynamicCpuSet& operator=(const DynamicCpuSet&) = delete; - - cpu_set_t* get() { return set_; } - const cpu_set_t* get() const { return set_; } - size_t bytes() const { return bytes_; } - size_t count() const { return count_; } - explicit operator bool() const { return set_ != nullptr; } - -private: - size_t count_; - size_t bytes_; - cpu_set_t* set_; -}; - -static size_t initial_cpu_count() { - const long configured = sysconf(_SC_NPROCESSORS_CONF); - return (std::max)(size_t(128), configured > 0 ? (size_t) configured : size_t(0)); -} - -// Query with CPU_ALLOC rather than cpu_set_t: this must observe CPUs beyond CPU_SETSIZE too. -static bool get_affinity(std::vector& ids) { - size_t count = initial_cpu_count(); - for (int attempt = 0; attempt < 8; ++attempt) { - DynamicCpuSet set(count); - if (!set) return false; - const int error = pthread_getaffinity_np(pthread_self(), set.bytes(), set.get()); - if (error == 0) { - ids.clear(); - for (size_t i = 0; i < set.count(); ++i) - if (CPU_ISSET_S(i, set.bytes(), set.get())) ids.push_back((int) i); - return !ids.empty(); - } - if (error != EINVAL || count > (size_t(1) << 20)) { - std::fprintf(stderr, "pthread_getaffinity_np failed: %s\n", std::strerror(error)); - return false; - } - count *= 2; - } - std::fprintf(stderr, "pthread_getaffinity_np still needs a larger CPU set\n"); - return false; -} - -static bool set_affinity(const std::vector& ids) { - if (ids.empty()) return false; - const int highest = *std::max_element(ids.begin(), ids.end()); - if (highest < 0) return false; - const size_t count = (std::max)(initial_cpu_count(), (size_t) highest + 1); - DynamicCpuSet set(count); - if (!set) return false; - for (int id : ids) { - if (id < 0 || (size_t) id >= count) return false; - CPU_SET_S((size_t) id, set.bytes(), set.get()); - } - const int error = pthread_setaffinity_np(pthread_self(), set.bytes(), set.get()); - if (error != 0) { - std::fprintf(stderr, "pthread_setaffinity_np failed: %s\n", std::strerror(error)); - return false; - } - return true; -} - -class OriginalAffinity { -public: - bool capture() { return get_affinity(ids_); } - const std::vector& ids() const { return ids_; } - bool restore() { return ids_.empty() || set_affinity(ids_); } - ~OriginalAffinity() { if (!ids_.empty()) set_affinity(ids_); } - -private: - std::vector ids_; -}; - -static bool expect_affinity(const std::vector& expected, const char* label) { - std::vector actual; - if (!get_affinity(actual)) { - std::fprintf(stderr, "Linux affinity test: %s: cannot query current affinity\n", label); - return false; - } - if (actual != expected) { - std::fprintf(stderr, "Linux affinity test: %s: expected %zu CPUs, observed %zu\n", - label, expected.size(), actual.size()); - return false; - } - return true; -} - -static bool round_trip_full_mask(const std::vector& allowed) { - const int target = allowed.front(); - const auto previous = cpu::pin_current_thread(target); - const bool pinned = previous.valid && expect_affinity({target}, "pin from full allowed mask"); - cpu::restore_thread_affinity(previous); - return pinned && expect_affinity(allowed, "restore full allowed mask"); -} - -static bool topology_respects_current_mask() { - std::vector allowed; - if (!get_affinity(allowed)) return false; - const auto topology = cpu::detect_cpu_topology(false); - if (topology.worker_cores.empty()) return false; - for (int core : topology.worker_cores) { - if (!std::binary_search(allowed.begin(), allowed.end(), core)) { - std::fprintf(stderr, "Linux affinity test: topology selected disallowed CPU %d\n", core); - return false; - } - } - return true; -} - -static bool round_trip_sparse_nested(const std::vector& allowed) { - if (allowed.size() < 2) { - std::puts("SKIP sparse/nested affinity: fewer than two allowed CPUs"); - return true; - } - const std::vector sparse{allowed.front(), allowed.back()}; - if (!set_affinity(sparse) || !expect_affinity(sparse, "establish sparse mask") || - !topology_respects_current_mask()) return false; - - const auto outer = cpu::pin_current_thread(sparse.front()); - const bool outer_pinned = outer.valid && expect_affinity({sparse.front()}, "outer pin"); - if (!outer_pinned) { - cpu::restore_thread_affinity(outer); - return false; - } - - const auto inner = cpu::pin_current_thread(sparse.back()); - const bool inner_pinned = inner.valid && expect_affinity({sparse.back()}, "inner pin"); - cpu::restore_thread_affinity(inner); - const bool outer_restored = expect_affinity({sparse.front()}, "restore inner pin to outer pin"); - cpu::restore_thread_affinity(outer); - const bool sparse_restored = expect_affinity(sparse, "restore outer pin to sparse mask"); - const bool full_restored = set_affinity(allowed) && expect_affinity(allowed, "restore full mask after sparse test"); - return inner_pinned && outer_restored && sparse_restored && full_restored; -} - -static bool round_trip_high_cpu(const std::vector& allowed, bool require_high) { - const auto it = std::find_if(allowed.begin(), allowed.end(), [](int id) { return id >= 64; }); - if (it == allowed.end()) { - if (require_high) { - std::fprintf(stderr, "Linux affinity test: --require-high-cpu requested, but no allowed CPU ID is >= 64\n"); - return false; - } - std::puts("SKIP high-CPU affinity path: no allowed CPU ID is >= 64 (use --require-high-cpu to require it)"); - return true; - } - const int target = allowed.front() == *it ? (allowed.size() > 1 ? allowed.back() : *it) : allowed.front(); - if (target == *it) { - if (require_high) { - std::fprintf(stderr, "Linux affinity test: --require-high-cpu needs at least two allowed CPUs to test restoration\n"); - return false; - } - std::puts("SKIP high-CPU affinity round trip: only one CPU is allowed, so no meaningful pin transition is possible"); - return true; - } - - // Restrict the caller to one high-numbered CPU, then pin to a different originally allowed CPU. - // Restoring the high-only mask catches truncation even when the original process mask is sparse. - const std::vector high_only{*it}; - if (!set_affinity(high_only) || !expect_affinity(high_only, "establish high-only mask") || - !topology_respects_current_mask()) return false; - const auto previous = cpu::pin_current_thread(target); - const bool pinned = previous.valid && expect_affinity({target}, "pin away from high-only mask"); - cpu::restore_thread_affinity(previous); - const bool restored = pinned && expect_affinity(high_only, "restore high-only mask"); - if (restored) std::printf("High-CPU affinity round trip: saved CPU %d, pin target %d\n", *it, target); - return restored; -} - -static bool negative_cpu_is_noop() { - std::vector before; - if (!get_affinity(before)) return false; - const auto invalid = cpu::pin_current_thread(-1); - std::vector after; - const bool unchanged = get_affinity(after) && before == after; - cpu::restore_thread_affinity(invalid); - return !invalid.valid && unchanged && expect_affinity(before, "negative CPU no-op"); -} - -static bool worker_thread_can_pin(int target) { - bool ok = false; - std::thread worker([&] { - std::vector before; - if (!get_affinity(before)) return; - std::vector saved; - if (cpu::detail::get_thread_affinity(saved) != 0) return; - const int pin_error = cpu::detail::pin_thread_to_cpu(target); - const bool pinned = pin_error == 0 && expect_affinity({target}, "worker thread helper pin") && - sched_getcpu() == target; - const int restore_error = cpu::detail::set_thread_affinity(saved); - ok = pinned && restore_error == 0 && expect_affinity(before, "worker thread helper restore"); - }); - worker.join(); - return ok; -} - -static bool failed_pin_preserves_affinity() { - std::vector before; - if (!get_affinity(before)) return false; - // An ID outside the caller's current mask may still be online and legal, so it is not a - // reliable failure case. INT_MAX is rejected before allocating or changing any CPU set. - const int error = cpu::detail::pin_thread_to_cpu(INT_MAX); - std::vector after; - const bool helper_unchanged = get_affinity(after) && before == after; - if (error == 0) { - std::fprintf(stderr, "Linux affinity test: pin_thread_to_cpu(INT_MAX) unexpectedly succeeded\n"); - return false; - } - const auto invalid = cpu::pin_current_thread(INT_MAX); - cpu::restore_thread_affinity(invalid); - std::vector after_public; - const bool public_unchanged = get_affinity(after_public) && before == after_public; - if (!helper_unchanged || invalid.valid || !public_unchanged) - std::fprintf(stderr, "Linux affinity test: failed pin changed the observed affinity or returned a valid snapshot\n"); - return helper_unchanged && !invalid.valid && public_unchanged; -} - -int main(int argc, char** argv) { - bool require_high = false; - for (int i = 1; i < argc; ++i) { - if (std::strcmp(argv[i], "--require-high-cpu") == 0) require_high = true; - else { - std::fprintf(stderr, "Unknown argument: %s\n", argv[i]); - return 2; - } - } - - OriginalAffinity original; - if (!original.capture()) { - std::fprintf(stderr, "Linux affinity test: cannot capture original thread affinity\n"); - return 1; - } - const auto allowed = original.ids(); - - bool ok = round_trip_full_mask(allowed) && worker_thread_can_pin(allowed.back()); - if (ok) ok = round_trip_sparse_nested(allowed); - if (ok) ok = round_trip_high_cpu(allowed, require_high); - if (ok) ok = negative_cpu_is_noop(); - if (ok) ok = failed_pin_preserves_affinity(); - const bool restored = original.restore() && expect_affinity(allowed, "final original affinity cleanup"); - if (!ok || !restored) return 1; - - std::printf("Linux affinity test: full, sparse/nested, worker helper, invalid-target, failed-pin, and cleanup checks passed (%zu allowed CPUs)\n", - allowed.size()); - return 0; -} - -#else - -int main() { - std::puts("SKIP Linux affinity test: Linux is required"); - return 0; -} - -#endif diff --git a/src/kernels/cpu/pool_affinity_test.cpp b/src/kernels/cpu/pool_affinity_test.cpp deleted file mode 100644 index 052ae59..0000000 --- a/src/kernels/cpu/pool_affinity_test.cpp +++ /dev/null @@ -1,148 +0,0 @@ -#include "strata/kernels/cpu/pool.hpp" -#include "pool_affinity_win.hpp" - -#include -#include -#include -#include - -namespace cpu = strata::kernels::cpu; - -static bool check(bool ok, const char* message) { - if (!ok) std::fprintf(stderr, "Windows affinity test: %s (error %lu)\n", message, (unsigned long) GetLastError()); - return ok; -} - -static bool select(const std::vector& ids) { - return SetThreadSelectedCpuSets(GetCurrentThread(), ids.empty() ? nullptr : ids.data(), (ULONG) ids.size()) != 0; -} - -static bool selected_is(std::vector expected) { - std::vector actual; - if (!cpu::detail::get_thread_cpu_sets(actual)) return false; - std::sort(actual.begin(), actual.end()); - std::sort(expected.begin(), expected.end()); - return actual == expected; -} - -// Establish reachability before the round trip: CPU Sets are soft affinity and cannot override an -// existing job/hard-affinity restriction. Afterwards, require the same observable reachability. -static bool observe(int core) { - for (int i = 0; i < 200; ++i) { - Sleep(1); - PROCESSOR_NUMBER current{}; - GetCurrentProcessorNumberEx(¤t); - if ((int) current.Group * 64 + current.Number == core) return true; - } - return false; -} - -static bool host_round_trips(const std::vector& cores, const std::vector& ids) { - if (!check(select({}), "clear initial thread CPU Sets")) return false; - std::vector reachable; - for (size_t i = 0; i < cores.size(); ++i) { - if (!check(select({ids[i]}), "select baseline CPU Set")) return false; - reachable.push_back(observe(cores[i])); - } - if (!check(select({}), "clear baseline CPU Sets")) return false; - - for (size_t i = 0; i < cores.size(); ++i) { - const auto previous = cpu::pin_current_thread(cores[i]); - const bool pinned = previous.valid && previous.cpu_sets.empty() && selected_is({ids[i]}); - cpu::restore_thread_affinity(previous); - if (!check(pinned && selected_is({}), "restore empty thread assignment")) return false; - } - - // GetThreadGroupAffinity alone misses a lost implicit all-group state. Selecting each CPU Set - // again must still permit execution there, without ever setting a hard group affinity. - for (size_t i = 0; i < cores.size(); ++i) { - if (!check(select({ids[i]}), "select CPU Set after restore")) return false; - if (reachable[i]) { - if (!check(observe(cores[i]), "lost CPU/group eligibility after host restore")) return false; - std::printf("Host restore: still executes on group %d processor %d\n", cores[i] / 64, cores[i] & 63); - } else { - std::printf("SKIP scheduling observation for group %d: not reachable before test\n", cores[i] / 64); - } - } - - // A nonempty selection may span groups. Nested host selections must restore the entire set. - if (!check(select(ids), "set existing multi-CPU selection")) return false; - const auto outer = cpu::pin_current_thread(cores.front()); - const auto inner = cpu::pin_current_thread(cores.back()); - const bool inner_ok = inner.valid && selected_is({ids.back()}); - cpu::restore_thread_affinity(inner); - const bool outer_ok = outer.valid && selected_is({ids.front()}); - cpu::restore_thread_affinity(outer); - if (!check(inner_ok && outer_ok && selected_is(ids), "restore nested / existing CPU Set selections")) return false; - const auto invalid = cpu::pin_current_thread(-1); - cpu::restore_thread_affinity(invalid); - if (!check(!invalid.valid && selected_is(ids), "invalid target must not mutate selection")) return false; - return check(select({}), "clear final host selection"); -} - -static bool inherited_default(int core, ULONG id, int temporary_core, ULONG temporary_id) { - ULONG count = 0; - if (!GetProcessDefaultCpuSets(GetCurrentProcess(), nullptr, 0, &count) && - GetLastError() != ERROR_INSUFFICIENT_BUFFER) return false; - std::vector saved(count); - if (count && !GetProcessDefaultCpuSets(GetCurrentProcess(), saved.data(), count, &count)) return false; - saved.resize(count); - if (!check(SetProcessDefaultCpuSets(GetCurrentProcess(), &id, 1) != 0, "set process default")) return false; - bool ok = false; - std::thread host([&] { - if (!select({})) return; - const bool reachable = observe(core); - const auto previous = cpu::pin_current_thread(temporary_core); - const bool overridden = previous.valid && selected_is({temporary_id}); - cpu::restore_thread_affinity(previous); - ULONG inherited = 0, required = 0; - ok = overridden && previous.cpu_sets.empty() && selected_is({}) && - GetProcessDefaultCpuSets(GetCurrentProcess(), &inherited, 1, &required) && - required == 1 && inherited == id && (!reachable || observe(core)); - }); - host.join(); - const bool restored = SetProcessDefaultCpuSets(GetCurrentProcess(), saved.empty() ? nullptr : saved.data(), - (ULONG) saved.size()) != 0; - return check(ok && restored, "restore inherited process default"); -} - -int main() { - const auto all = cpu::physical_cores(false); - std::vector cores; - std::vector ids; - for (int core : all) { - if (std::any_of(cores.begin(), cores.end(), [core](int other) { return other / 64 == core / 64; })) continue; - ULONG id = 0; - if (!cpu::detail::cpu_set_for_core(core, id)) continue; - cores.push_back(core); - ids.push_back(id); - } - if (!check(!cores.empty(), "no usable CPU Sets")) return 1; - if (!check(cores.size() == GetActiveProcessorGroupCount(), "CPU Sets do not cover all active groups")) return 1; - - // Hard pins belong on pool-owned threads; never contaminate the caller under test with one. - for (size_t i = 0; i < cores.size(); ++i) { - bool ok = false; - std::thread worker([&] { - if (!cpu::detail::set_thread_group_affinity(cores[i], (int) i)) return; - GROUP_AFFINITY pinned{}; - if (!GetThreadGroupAffinity(GetCurrentThread(), &pinned)) return; - ok = pinned.Group == cores[i] / 64 && pinned.Mask == (KAFFINITY(1) << (cores[i] & 63)); - // Host placement must also preserve an existing restrictive hard affinity. - const auto previous = cpu::pin_current_thread(cores.back()); - cpu::restore_thread_affinity(previous); - GROUP_AFFINITY after{}; - ok = ok && previous.valid && GetThreadGroupAffinity(GetCurrentThread(), &after) && - after.Group == pinned.Group && after.Mask == pinned.Mask; - }); - worker.join(); - if (!check(ok, "worker hard pin / caller hard-affinity preservation")) return 1; - } - - bool host_ok = false; - std::thread host([&] { host_ok = host_round_trips(cores, ids); }); - host.join(); - if (!host_ok || !inherited_default(cores.back(), ids.back(), cores.front(), ids.front())) return 1; - std::printf("Windows affinity test: worker pins, host CPU Sets and process-default restoration passed (%zu groups)\n", cores.size()); - return 0; -} diff --git a/src/kernels/cpu/pool_affinity_win.hpp b/src/kernels/cpu/pool_affinity_win.hpp deleted file mode 100644 index 6f0e402..0000000 --- a/src/kernels/cpu/pool_affinity_win.hpp +++ /dev/null @@ -1,64 +0,0 @@ -#pragma once - -#if defined(_WIN32) -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#include - -#include -#include -#include - -namespace strata::kernels::cpu::detail { - -// Hard affinity is only for pool-owned threads, which terminate with the pool. A caller's implicit -// all-group affinity cannot be restored from PreviousGroupAffinity, so the host uses CPU Sets below. -inline bool set_thread_group_affinity(int core, int worker) { - if (core < 0) return false; - GROUP_AFFINITY target{}; - target.Group = (WORD) (core / 64); - target.Mask = KAFFINITY(1) << (core & 63); - if (SetThreadGroupAffinity(GetCurrentThread(), &target, nullptr)) return true; - std::fprintf(stderr, "strata cpu pool: SetThreadGroupAffinity for worker %d (group %u, mask 0x%llx) failed: %lu; previous affinity kept\n", - worker, (unsigned) target.Group, (unsigned long long) target.Mask, (unsigned long) GetLastError()); - return false; -} - -inline bool get_thread_cpu_sets(std::vector& ids) { - ULONG count = 0; - if (!GetThreadSelectedCpuSets(GetCurrentThread(), nullptr, 0, &count) && - GetLastError() != ERROR_INSUFFICIENT_BUFFER) return false; - ids.resize(count); - if (count == 0) return true; - if (!GetThreadSelectedCpuSets(GetCurrentThread(), ids.data(), count, &count)) return false; - ids.resize(count); - return true; -} - -// CPU Set IDs are opaque: find the entry by both group and group-relative processor number. -inline bool cpu_set_for_core(int core, ULONG& id) { - ULONG bytes = 0; - if (!GetSystemCpuSetInformation(nullptr, 0, &bytes, GetCurrentProcess(), 0) && - GetLastError() != ERROR_INSUFFICIENT_BUFFER) return false; - std::vector buffer(bytes); - if (bytes && !GetSystemCpuSetInformation(reinterpret_cast(buffer.data()), - bytes, &bytes, GetCurrentProcess(), 0)) return false; - constexpr size_t header_size = offsetof(SYSTEM_CPU_SET_INFORMATION, CpuSet); - for (size_t offset = 0; offset + header_size <= bytes;) { - const auto* info = reinterpret_cast(buffer.data() + offset); - if (info->Size < header_size || info->Size > bytes - offset) break; - if (info->Type == CpuSetInformation && info->Size >= sizeof(SYSTEM_CPU_SET_INFORMATION) && info->CpuSet.Group == core / 64 && - info->CpuSet.LogicalProcessorIndex == (core & 63) && - (!info->CpuSet.Allocated || info->CpuSet.AllocatedToTargetProcess)) { - id = info->CpuSet.Id; - return true; - } - offset += info->Size; - } - SetLastError(ERROR_NOT_FOUND); - return false; -} - -} // namespace strata::kernels::cpu::detail -#endif diff --git a/src/kernels/cpu/pool_stress.cpp b/src/kernels/cpu/pool_stress.cpp deleted file mode 100644 index 2c9fca5..0000000 --- a/src/kernels/cpu/pool_stress.cpp +++ /dev/null @@ -1,99 +0,0 @@ -// src/kernels/cpu/pool_stress.cpp - issue #29: the expert pool under the load a big-VRAM card gives it. -// -// With most experts resident on the GPU, many layers hand the pool nothing, the workers go to sleep in the middle -// of a request, and the next tiny batch (one or two experts) is often finished by the host and the awake workers -// before a sleeper has even woken. That late wake-up is what the park/claim protocol has to survive. This drives -// hundreds of thousands of such batches - 0-4 jobs, run() and run_split(), with pauses long enough for the workers -// to sleep - and checks that every batch returns, with every job's output written. A watchdog thread turns a -// hang into a failure instead of a frozen test. -// -// pool_stress [seconds] (default 20) -#include "strata/kernels/cpu/pool.hpp" -#include "strata/kernels/cpu/expert.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace cpu = strata::kernels::cpu; - -int main(int argc, char** argv) { - const double seconds = argc > 1 ? std::atof(argv[1]) : 20.0; - const cpu::CpuFeatures feat = cpu::cpu_features(); - if (!feat.usable()) { - std::printf("CPU lacks %s: pool_stress SKIPPED\n", feat.reason()); - return 0; - } - constexpr int NJ = 4; - std::vector> blobs(NJ, std::vector(cpu::BLOB, 0)); - std::vector x(cpu::H, 0.25f); - cpu::ActQ act; - cpu::act_quant_q8_1(x.data(), cpu::H, act); - std::vector out((size_t) NJ * cpu::H); - std::vector jobs(NJ); - for (int e = 0; e < NJ; ++e) { - jobs[(size_t) e].blob = blobs[(size_t) e].data(); - jobs[(size_t) e].act = &act; - jobs[(size_t) e].out = out.data() + (size_t) e * cpu::H; - jobs[(size_t) e].slot = e; - } - - cpu::ExpertPool pool; - std::printf("pool_stress: %d workers + host, %.0f s\n", pool.workers(), seconds); - - // the watchdog: a batch that does not return within 10 s is a hang - std::atomic beat{0}; - std::atomic finished{false}; - std::thread dog([&] { - long long last = -1; - auto since = std::chrono::steady_clock::now(); - while (!finished.load()) { - std::this_thread::sleep_for(std::chrono::milliseconds(200)); - const long long b = beat.load(); - const auto now = std::chrono::steady_clock::now(); - if (b != last) { last = b; since = now; continue; } - if (now - since > std::chrono::seconds(10)) { - std::printf("\npool_stress: HANG - batch %lld has not returned for 10 s\n", b); - std::fflush(stdout); - std::_Exit(3); - } - } - }); - - std::mt19937 rng(29); - const float SENTINEL = -1.2345e33f; - long long batches = 0, sleeps = 0, missed = 0; - const auto t0 = std::chrono::steady_clock::now(); - while (std::chrono::steady_clock::now() - t0 < std::chrono::duration(seconds)) { - // now and then a gap long enough for every worker to go to sleep (the pool sleeps after 20 ms) - if (rng() % 64 == 0) { - std::this_thread::sleep_for(std::chrono::milliseconds(21 + (int) (rng() % 10))); - ++sleeps; - } else if (rng() % 4 == 0) { - std::this_thread::sleep_for(std::chrono::microseconds(rng() % 300)); - } - const int n = (int) (rng() % (NJ + 1)); - for (int e = 0; e < n; ++e) std::fill(jobs[(size_t) e].out, jobs[(size_t) e].out + cpu::H, SENTINEL); - if (rng() % 2) pool.run(jobs.data(), n); - else pool.run_split(jobs.data(), n); - for (int e = 0; e < n; ++e) - if (jobs[(size_t) e].out[0] == SENTINEL || jobs[(size_t) e].out[cpu::H - 1] == SENTINEL) ++missed; - beat.fetch_add(1); - ++batches; - } - finished.store(true); - dog.join(); - std::printf("pool_stress: %lld batches (%lld after the workers slept), %lld jobs not run\n", batches, sleeps, - missed); - if (missed) { - std::printf("pool_stress: FAILED\n"); - return 1; - } - std::printf("pool_stress OK\n"); - return 0; -} diff --git a/src/kernels/cpu/pool_test.cpp b/src/kernels/cpu/pool_test.cpp deleted file mode 100644 index dbc7288..0000000 --- a/src/kernels/cpu/pool_test.cpp +++ /dev/null @@ -1,224 +0,0 @@ -// src/kernels/cpu/pool_test.cpp - P2.S3's test for the expert pool. -// -// The pool's correctness claims are small and specific, so they are checked directly rather than through a -// timing number: -// -// 1. THE SAME ANSWER AS SERIAL. Every job's output must be bit-identical to running that expert serially. -// Each worker owns its own `ExpertScratch`, and the jobs share one read-only activation, so there is no -// legitimate source of difference - "close enough" here would be hiding a data race. -// 2. EVERY JOB RUNS EXACTLY ONCE. Claiming is `head.fetch_add`, and an off-by-one in the bound is the -// classic pool bug: it either drops a job or runs one twice. Checked with a sentinel-filled output -// buffer, so a dropped job is visible as an untouched slot rather than as a slightly wrong number. -// 3. REPEATED BATCHES. A pool that works once and hangs or corrupts on the second `run()` is the failure -// mode the park protocol exists to prevent, so `run()` is called many times in a row. -// 4. A BATCH BIGGER AND SMALLER THAN THE WORKER COUNT, because `n < workers` leaves most workers claiming -// nothing and `n > workers` is the real case (10 experts, 5 workers). -#include "strata/kernels/cpu/pool.hpp" -#include "strata/kernels/cpu/expert.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace cpu = strata::kernels::cpu; - -namespace { - -bool read_blob(const char* path, long long index, std::vector& out) { - out.assign(cpu::BLOB, 0); - std::FILE* f = std::fopen(path, "rb"); - if (!f) return false; -#if defined(_MSC_VER) - if (_fseeki64(f, index * (long long) cpu::BLOB, SEEK_SET) != 0) { std::fclose(f); return false; } -#else - if (fseeko(f, (off_t) index * (off_t) cpu::BLOB, SEEK_SET) != 0) { std::fclose(f); return false; } -#endif - const size_t got = std::fread(out.data(), 1, out.size(), f); - std::fclose(f); - return got == out.size(); -} - -double now_ms() { - using namespace std::chrono; - return duration(steady_clock::now().time_since_epoch()).count(); -} - -} // namespace - -int main(int argc, char** argv) { - bool selftest = false; - const char* path = "pack/full/experts.bin"; - long long layer = 0; - for (int i = 1; i < argc; ++i) { - const std::string a = argv[i]; - if (a == "--selftest") selftest = true; - else if (a == "--file" && i + 1 < argc) path = argv[++i]; - else if (a == "--layer" && i + 1 < argc) layer = std::atoll(argv[++i]); - else { std::fprintf(stderr, "usage: pool_test [--selftest] [--file P] [--layer N]\n"); return 2; } - } - - const cpu::CpuFeatures feat = cpu::cpu_features(); - if (!feat.usable()) { - std::printf(" CPU lacks %s - the VNNI path cannot run here; pool test SKIPPED, not passed.\n", - feat.reason()); - std::printf("\npool: 0 failures, 1 SKIPPED\n"); - return 0; - } - - int bad = 0; - - // ---- ten experts off one layer, which is exactly what a token uses - const int NEXP = 10; - std::vector> blobs((size_t) NEXP); - for (int e = 0; e < NEXP; ++e) - if (!read_blob(path, layer * 512 + e, blobs[(size_t) e])) { - std::fprintf(stderr, "cannot read expert %d of layer %lld from %s\n", e, layer, path); - return 2; - } - - std::mt19937 rng(99); - std::normal_distribution gauss(0.0f, 1.0f); - std::vector x(cpu::H); - for (auto& v : x) v = gauss(rng); - - cpu::ActQ act; - cpu::act_quant_q8_1(x.data(), cpu::H, act); - - // ---- serial reference - std::vector ref((size_t) NEXP * cpu::H); - { - cpu::ExpertScratch ws; - for (int e = 0; e < NEXP; ++e) - cpu::s2_expert_vnni_q(blobs[(size_t) e].data(), act, ref.data() + (size_t) e * cpu::H, ws); - } - - // ---- the pool - const std::vector cores = cpu::physical_cores(true); - const int hw = (int) std::thread::hardware_concurrency(); - std::printf(" %-44s %d logical, %d physical (skipping the first)\n", "cores the pool will use", - hw, (int) cores.size()); - - cpu::ExpertPool pool; - std::printf(" %-44s %d\n", "workers", pool.workers()); - - std::vector jobs((size_t) NEXP); - std::vector got((size_t) NEXP * cpu::H); - std::vector weights((size_t) NEXP); - for (int e = 0; e < NEXP; ++e) weights[(size_t) e] = 0.1f * (float) (e + 1); - - // ---- 1 + 2: same answer as serial, and every job exactly once. - // The output buffer starts at a sentinel no real result can equal, so a job that never runs shows up as - // an untouched slot instead of as a plausible number. - const float SENTINEL = -1.2345e33f; - for (int e = 0; e < NEXP; ++e) { - jobs[(size_t) e].blob = blobs[(size_t) e].data(); - jobs[(size_t) e].act = &act; - jobs[(size_t) e].out = got.data() + (size_t) e * cpu::H; - jobs[(size_t) e].weight = weights[(size_t) e]; - jobs[(size_t) e].slot = e; - std::fill(jobs[(size_t) e].out, jobs[(size_t) e].out + cpu::H, SENTINEL); - } - pool.run(jobs.data(), NEXP); - - long long not_run = 0, diff = 0; - float worst = 0.f; - for (int e = 0; e < NEXP; ++e) - for (int i = 0; i < cpu::H; ++i) { - const float a = ref[(size_t) e * cpu::H + i], b = got[(size_t) e * cpu::H + i]; - if (b == SENTINEL) { ++not_run; continue; } - if (std::memcmp(&a, &b, 4) != 0) ++diff; - worst = std::fmax(worst, std::fabs(a - b)); - } - std::printf(" %-44s %s (%lld of %d outputs untouched)\n", "every job ran exactly once", - not_run ? "*** NO ***" : "yes", not_run, NEXP * cpu::H); - if (not_run) ++bad; - // BIT-IDENTICAL, not "close". Each worker has a private scratch and the activation is shared read-only, - // so any difference at all is a race or a scratch collision - and a tolerance would hide exactly that. - std::printf(" %-44s %s (%lld of %d differ, worst |d| %.3e)\n", "identical to the serial run", - diff ? "*** NO ***" : "yes", diff, NEXP * cpu::H, (double) worst); - if (diff) ++bad; - - // ---- 3: repeated batches. A park protocol that works once and corrupts on the second call is the - // exact failure this loop is here to catch. - { - int repeats_bad = 0; - for (int r = 0; r < 200; ++r) { - for (int e = 0; e < NEXP; ++e) std::fill(jobs[(size_t) e].out, jobs[(size_t) e].out + cpu::H, SENTINEL); - pool.run(jobs.data(), NEXP); - for (int e = 0; e < NEXP && !repeats_bad; ++e) - for (int i = 0; i < cpu::H; ++i) - if (std::memcmp(&ref[(size_t) e * cpu::H + i], &got[(size_t) e * cpu::H + i], 4) != 0) { - ++repeats_bad; - break; - } - } - std::printf(" %-44s %s (200 consecutive batches)\n", "repeated batches stay correct", - repeats_bad ? "*** NO ***" : "yes"); - if (repeats_bad) ++bad; - } - - // ---- 4: batch sizes either side of the worker count - { - int size_bad = 0; - for (int n : {1, 2, pool.workers() - 1 > 0 ? pool.workers() - 1 : 1, pool.workers(), - pool.workers() + 1, NEXP}) { - if (n < 1 || n > NEXP) continue; - for (int e = 0; e < n; ++e) std::fill(jobs[(size_t) e].out, jobs[(size_t) e].out + cpu::H, SENTINEL); - pool.run(jobs.data(), n); - for (int e = 0; e < n && !size_bad; ++e) - for (int i = 0; i < cpu::H; ++i) - if (std::memcmp(&ref[(size_t) e * cpu::H + i], &got[(size_t) e * cpu::H + i], 4) != 0) { - ++size_bad; - break; - } - } - std::printf(" %-44s %s (1, w-1, w, w+1, 10)\n", "batch sizes around the worker count", - size_bad ? "*** NO ***" : "yes"); - if (size_bad) ++bad; - } - - // ---- and the number that matters for the ledger: c for one layer, 10 experts over 48 layers. - // - // BEST OF N, not a mean. The first version divided a 10-run total by 10 and reported 6.604 ms per layer - - // 2.1 GB/s against L9's measured 42.55 - purely because a CUDA build was running on the same 6-core - // machine at the time. A mean over a contended machine measures the contention; a best-of measures the - // instrument, and every other timing tool in this project already takes the best. The spread is printed - // so a contended run is visible rather than being read as a regression. - { - const int REPS = 20; - std::vector t((size_t) REPS, 0.0); - for (int r = 0; r < REPS; ++r) { - const double t0 = now_ms(); - pool.run(jobs.data(), NEXP); - t[(size_t) r] = now_ms() - t0; - } - std::vector sorted = t; - std::sort(sorted.begin(), sorted.end()); - const double best = sorted.front(), median = sorted[sorted.size() / 2], worst = sorted.back(); - const double gbs = (double) NEXP * cpu::BLOB / (best * 1e-3) / 1e9; - std::printf("\n %-44s %7.3f ms (%.1f GB/s)\n", "10 experts, one layer (best of 20)", - best, gbs); - std::printf(" %-44s %7.3f / %7.3f ms (spread %.2fx)\n", "median / worst", median, worst, - median / (best > 0 ? best : 1)); - std::printf(" %-44s %7.3f ms -> %.1f tok/s for the full 48 layers\n", - "extrapolated to 48 layers", best * 48, 1000.0 / (best * 48)); - std::printf(" L9 measured 42.55 GB/s on 6 cores; this pool uses %d workers (core 0 is left to the\n", - pool.workers()); - std::printf(" host loop), so %.1f GB/s x 6/%d = %.1f GB/s is the per-core comparison.\n", - gbs, pool.workers(), gbs * 6.0 / pool.workers()); - if (median / (best > 0 ? best : 1) > 1.5) - std::printf(" *** the spread is over 1.5x: this machine was CONTENDED and the median is not a\n" - " property of the pool. Re-run on a quiet machine before quoting it. ***\n"); - } - - std::printf("\npool: %d failures\n", bad); - if (bad) return 1; - if (selftest) std::printf("pool_test OK\n"); - return 0; -} diff --git a/src/kernels/cpu/q2_avx2.cpp b/src/kernels/cpu/q2_avx2.cpp deleted file mode 100644 index 8e276a5..0000000 --- a/src/kernels/cpu/q2_avx2.cpp +++ /dev/null @@ -1,130 +0,0 @@ -// src/kernels/cpu/q2_avx2.cpp - plan v0.3 P6: the Q2_0 expert rows and the activation quantizer for CPUs -// without AVX-512 (Intel Core 12th-14th gen and Core Ultra, AMD Zen 2/3). -// -// Compiled with AVX2 only, so nothing here can fault on those CPUs. The arithmetic is the AVX-512 kernels': -// codes 0..3 against the int8 activation per 32-value chunk, times the weight scale and the chunk scale, minus -// the weight scale times the chunk's `hx` (the -1 code offset); the quantizer is the scalar rule, bit for bit. -#include "strata/kernels/cpu/expert.hpp" - -#include - -#include -#include - -namespace strata::kernels::cpu { -namespace { - -inline float h2f(const uint8_t* p) { - uint16_t h; - std::memcpy(&h, p, 2); - return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128((int) h))); -} - -// 16 bytes of 2-bit codes (value i in byte i/4, bits 2*(i%4)) -> 64 codes in value order, two 32-byte vectors -inline void unpack64(const uint8_t* codes, __m256i& lo, __m256i& hi) { - const __m128i b = _mm_loadu_si128((const __m128i*) codes); - const __m128i m3 = _mm_set1_epi8(3); - const __m128i c0 = _mm_and_si128(b, m3); - const __m128i c1 = _mm_and_si128(_mm_srli_epi16(b, 2), m3); - const __m128i c2 = _mm_and_si128(_mm_srli_epi16(b, 4), m3); - const __m128i c3 = _mm_and_si128(_mm_srli_epi16(b, 6), m3); - const __m128i a0 = _mm_unpacklo_epi8(c0, c1), a1 = _mm_unpacklo_epi8(c2, c3); // bytes 0..7 - const __m128i b0 = _mm_unpackhi_epi8(c0, c1), b1 = _mm_unpackhi_epi8(c2, c3); // bytes 8..15 - lo = _mm256_set_m128i(_mm_unpackhi_epi16(a0, a1), _mm_unpacklo_epi16(a0, a1)); // values 0..31 - hi = _mm256_set_m128i(_mm_unpackhi_epi16(b0, b1), _mm_unpacklo_epi16(b0, b1)); // values 32..63 -} - -template -inline void row_multi(const uint8_t* row, const ActQ* const* a, int nblocks, float* res) { - __m256 acc[NT]; - float corr[NT]; - for (int t = 0; t < NT; ++t) { acc[t] = _mm256_setzero_ps(); corr[t] = 0.f; } - const __m256i ones = _mm256_set1_epi16(1); - for (int b = 0; b < nblocks; ++b) { - const uint8_t* blk = row + (size_t) b * 18; - const float d = h2f(blk); - __m256i lo, hi; - unpack64(blk + 2, lo, hi); - for (int t = 0; t < NT; ++t) { - const int8_t* q = a[t]->q + b * 64; - const __m256i s0 = _mm256_madd_epi16(_mm256_maddubs_epi16(lo, _mm256_loadu_si256((const __m256i*) q)), ones); - const __m256i s1 = _mm256_madd_epi16(_mm256_maddubs_epi16(hi, _mm256_loadu_si256((const __m256i*) (q + 32))), ones); - acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d * a[t]->scale[2 * b]), _mm256_cvtepi32_ps(s0), acc[t]); - acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d * a[t]->scale[2 * b + 1]), _mm256_cvtepi32_ps(s1), acc[t]); - corr[t] += d * (a[t]->hx[2 * b] + a[t]->hx[2 * b + 1]); - } - } - for (int t = 0; t < NT; ++t) { - const __m128 h = _mm_add_ps(_mm256_castps256_ps128(acc[t]), _mm256_extractf128_ps(acc[t], 1)); - const __m128 s = _mm_add_ps(h, _mm_movehl_ps(h, h)); - res[t] = _mm_cvtss_f32(_mm_add_ss(s, _mm_movehdup_ps(s))) - corr[t]; - } -} - -template -void rows(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, float* const* out, int r0, int r1) { - float res[NT]; - for (int r = r0; r < r1; ++r) { - row_multi(w + (size_t) r * row_bytes, a, nblocks, res); - for (int t = 0; t < NT; ++t) out[t][r] = res[t]; - } -} - -} // namespace - -void q2_0_gguf_rows_multi_avx2(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, - float* const* out, int r0, int r1) { - switch (nt) { - case 1: rows<1>(w, row_bytes, nblocks, a, out, r0, r1); break; - case 2: rows<2>(w, row_bytes, nblocks, a, out, r0, r1); break; - case 3: rows<3>(w, row_bytes, nblocks, a, out, r0, r1); break; - case 4: rows<4>(w, row_bytes, nblocks, a, out, r0, r1); break; - default: - for (int t0 = 0; t0 < nt; t0 += 4) { - const int k = nt - t0 < 4 ? nt - t0 : 4; - q2_0_gguf_rows_multi_avx2(w, row_bytes, nblocks, a + t0, k, out + t0, r0, r1); - } - } -} - -void act_quant_q8_1_avx2(const float* x, int n, ActQ& a) { - a.nchunks = n / QKA; - const __m256 absmask = _mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff)); - const __m256 half = _mm256_set1_ps(0.5f), mhalf = _mm256_set1_ps(-0.5f), zero = _mm256_setzero_ps(); - const __m256i lo = _mm256_set1_epi32(-127), hi = _mm256_set1_epi32(127); - for (int k = 0; k < a.nchunks; ++k) { - const float* xb = x + k * QKA; - __m256 v[4]; - __m256 m = _mm256_setzero_ps(); - for (int i = 0; i < 4; ++i) { - v[i] = _mm256_loadu_ps(xb + 8 * i); - m = _mm256_max_ps(m, _mm256_and_ps(v[i], absmask)); - } - __m128 h = _mm_max_ps(_mm256_castps256_ps128(m), _mm256_extractf128_ps(m, 1)); - h = _mm_max_ps(h, _mm_movehl_ps(h, h)); - const float amax = _mm_cvtss_f32(_mm_max_ss(h, _mm_movehdup_ps(h))); - const float s = amax > 0.f ? amax / 127.f : 0.f; - const float inv = s > 0.f ? 1.f / s : 0.f; - const __m256 vinv = _mm256_set1_ps(inv); - __m256i sum = _mm256_setzero_si256(); - alignas(32) int32_t qi[QKA]; - for (int i = 0; i < 4; ++i) { - const __m256 t = _mm256_mul_ps(v[i], vinv); - const __m256 r = _mm256_add_ps(t, _mm256_blendv_ps(mhalf, half, _mm256_cmp_ps(t, zero, _CMP_GE_OQ))); - __m256i q = _mm256_cvttps_epi32(r); - q = _mm256_min_epi32(_mm256_max_epi32(q, lo), hi); - sum = _mm256_add_epi32(sum, q); - _mm256_store_si256((__m256i*) (qi + 8 * i), q); - } - for (int j = 0; j < QKA; ++j) a.q[k * QKA + j] = (int8_t) qi[j]; - __m128i s4 = _mm_add_epi32(_mm256_castsi256_si128(sum), _mm256_extracti128_si256(sum, 1)); - s4 = _mm_add_epi32(s4, _mm_shuffle_epi32(s4, 0x4E)); - s4 = _mm_add_epi32(s4, _mm_shuffle_epi32(s4, 0xB1)); - const int32_t total = _mm_cvtsi128_si32(s4); - a.scale[k] = s; - a.sum[k] = total; - a.hx[k] = s * (float) total; - } -} - -} // namespace strata::kernels::cpu diff --git a/src/kernels/cpu/router_dot_parity.cpp b/src/kernels/cpu/router_dot_parity.cpp deleted file mode 100644 index bd1341b..0000000 --- a/src/kernels/cpu/router_dot_parity.cpp +++ /dev/null @@ -1,70 +0,0 @@ -// src/kernels/cpu/router_dot_parity.cpp - the router lookahead's BF16 dot on each rung this CPU has: the AVX2 kernel -// (kq_avx2.cpp) and the AVX1 one for older CPUs (kq_avx1.cpp), against a double-precision reference, plus the time -// of one layer's router. No GPU, no model: random BF16 rows of the model's router shape [512 x 2560], 1..8 tokens. -// -// router_dot_parity (STRATA_FORCE_ISA=avx leaves out the AVX2 kernel, as on an AVX-only CPU) -#include "strata/kernels/cpu/expert_layout.hpp" -#include "strata/kernels/cpu/kq_avx1.hpp" -#include "strata/kernels/cpu/kq_avx2.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace cpu = strata::kernels::cpu; - -int main() { - constexpr int R = 512, C = 2560, MAXT = 8; - std::mt19937 rng(7); - std::normal_distribution nd(0.f, 0.05f); - std::vector w((size_t) R * C); - for (auto& v : w) { - const float f = nd(rng); - uint32_t b; - std::memcpy(&b, &f, 4); - v = (uint16_t) (b >> 16); - } - std::vector x((size_t) MAXT * C); - for (auto& v : x) v = nd(rng) * 20.f; - std::vector ref((size_t) MAXT * R); - for (int t = 0; t < MAXT; ++t) - for (int r = 0; r < R; ++r) { - double s = 0; - for (int c = 0; c < C; ++c) { - const uint32_t b = (uint32_t) w[(size_t) r * C + c] << 16; - float f; - std::memcpy(&f, &b, 4); - s += (double) f * x[(size_t) t * C + c]; - } - ref[(size_t) t * R + r] = s; - } - int failures = 0; - auto run = [&](const char* tag, void (*fn)(const uint16_t*, int, int, const float*, int, float*)) { - std::vector out((size_t) MAXT * R); - for (int nt = 1; nt <= MAXT; ++nt) { - std::fill(out.begin(), out.end(), 0.f); - fn(w.data(), R, C, x.data(), nt, out.data()); - double num = 0, den = 0; - for (int i = 0; i < nt * R; ++i) { num += std::fabs(out[(size_t) i] - ref[(size_t) i]); den += std::fabs(ref[(size_t) i]); } - const double rel = num / (den + 1e-30); - if (nt == 1 || nt == MAXT) std::printf(" %-5s nt=%d rel %.2e vs the double reference\n", tag, nt, rel); - if (!(rel < 1e-5)) { std::printf(" %-5s nt=%d MISMATCH\n", tag, nt); ++failures; } - } - const int it = 20; - const auto t0 = std::chrono::steady_clock::now(); - for (int i = 0; i < it; ++i) fn(w.data(), R, C, x.data(), 4, out.data()); - const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count() / it; - std::printf(" %-5s one layer's router, 4 tokens: %.3f ms\n", tag, ms); - }; - std::printf("router_dot_parity: %s (avx2 %d, avx %d)\n", cpu::cpu_name().c_str(), (int) cpu::cpu_avx2_ok(), - (int) cpu::cpu_avx1_ok()); - if (cpu::cpu_avx2_ok()) run("avx2", cpu::bf16_rows_dot_multi); - if (cpu::cpu_avx1_ok()) run("avx", cpu::bf16_rows_dot_multi_avx1); - std::printf("router_dot_parity: %d failures\n", failures); - return failures == 0 ? 0 : 1; -} diff --git a/src/kernels/cuda/bf16_gemv.cu b/src/kernels/cuda/bf16_gemv.cu deleted file mode 100644 index 04473ad..0000000 --- a/src/kernels/cuda/bf16_gemv.cu +++ /dev/null @@ -1,141 +0,0 @@ -// src/kernels/cuda/bf16_gemv.cu - the BF16 GEMV. See the header for why it is not `s_gemv`. -#include "strata/kernels/bf16_gemv.hpp" - -#include "strata/kernels/bf16_bits.hpp" - -#include - -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int THREADS = 256; - -/// One thread per output row, walking it contiguously. Kept as the naive reference the split version is -/// checked against, and used directly for the shapes where the output width is already large. -__global__ void bf16_gemv_naive_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, - float* __restrict__ y, long long n_in, long long n_out) { - const long long o = (long long) blockIdx.x * blockDim.x + threadIdx.x; - if (o >= n_out) return; - const uint16_t* row = w + o * n_in; - float acc = 0.0f; - for (long long i = 0; i < n_in; ++i) - acc += f32_from_bf16(x[i]) * f32_from_bf16(row[i]); - y[o] = acc; -} - -/// One WARP per output row, lanes striding the reduction axis. For a fixed `i` consecutive lanes touch -/// consecutive addresses in this layout, so the load is coalesced - the property that took `gr_read` from -/// 262 ms/token to 8.9. -__global__ void bf16_gemv_warp_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, - float* __restrict__ y, long long n_in, long long n_out) { - const int warps_per_block = (int) (blockDim.x >> 5); - const long long o = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5); - if (o >= n_out) return; - const int lane = threadIdx.x & 31; - const uint16_t* row = w + o * n_in; - float acc = 0.0f; - for (long long i = lane; i < n_in; i += 32) - acc += f32_from_bf16(x[i]) * f32_from_bf16(row[i]); - for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, off); - if (lane == 0) y[o] = acc; -} - -/// TPR lanes cooperate on ONE row's reduction: `threads_per_row` threads each take a strided slice and the -/// block reduces through shared memory. Used when the output width is too small to fill the machine. -__global__ void bf16_gemv_split_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, - float* __restrict__ y, long long n_in, long long n_out, int tpr) { - extern __shared__ float scratch[]; - const long long o = blockIdx.x; - if (o >= n_out) return; - const int t = threadIdx.x; // 0 .. tpr-1 - const uint16_t* row = w + o * n_in; - float acc = 0.0f; - for (long long i = t; i < n_in; i += tpr) - acc += f32_from_bf16(x[i]) * f32_from_bf16(row[i]); - // block reduction; `tpr` is at most a few hundred, so a tree in shared is enough - scratch[t] = acc; - __syncthreads(); - for (int off = tpr >> 1; off > 0; off >>= 1) { - if (t < off) scratch[t] += scratch[t + off]; - __syncthreads(); - } - if (t == 0) y[o] = scratch[0]; -} - -inline void finish(void* stream, const char* what) { - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "%s launch: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } - if (stream != nullptr) return; - const cudaError_t s = cudaDeviceSynchronize(); - if (s != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(s)); - std::exit(1); - } -} - -} // namespace - -void bf16_gemv(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, void* stream) { - if (n_in <= 0 || n_out <= 0) return; - // **THIS USED TO ALWAYS USE THE NAIVE KERNEL, AND THE NAIVE KERNEL IS UNCOALESCED.** - // - // `bf16_gemv_naive_kernel` gives one THREAD per output row and walks the row contiguously, so at a fixed - // `i` the 32 threads of a warp read `w[(o+k)*n_in + i]` - addresses `n_in * 2` bytes apart. Every load in - // the kernel's inner loop costs 32 transactions instead of 1. The comment above that kernel claims it is - // "used directly for the shapes where the output width is already large", but nothing ever made that - // choice: this function called it unconditionally, at every shape. - // - // What that costs, from the nsys per-kernel table: **4.66 ms/token across 24 calls, 194 us each** - the - // third largest kernel in the engine at the time, moving 1.19 GiB/token at ~210 GB/s where a plain read at - // this geometry measures 641 GB/s (`bench/micro/p32_floor.cu`). - // - // `bf16_gemv_warp_kernel` exists, is checked against this one by `bf16_gemv_parity`, and is coalesced - - // consecutive lanes touch consecutive addresses - which is the property `gr_read`'s comment records as - // having taken it from 262 ms/token to 8.9. The threshold below is where warp-per-row has enough rows to - // fill the machine: 8 warps per block, so 64 rows is 8 blocks and 128 is 16, against 48 SMs. - if (n_out >= 64) { - const int warps = THREADS / 32; - const unsigned grid = (unsigned) ((n_out + warps - 1) / warps); - bf16_gemv_warp_kernel<<>>(x, w, y, n_in, n_out); - finish(stream, "bf16_gemv(warp)"); - return; - } - // Below the threshold the warp kernel would leave most of the machine idle, and the naive one is at least - // not wasting warps. It is still uncoalesced, so this is the branch to revisit if a small-output caller - // ever shows up hot in the profile. - const unsigned grid = (unsigned) ((n_out + THREADS - 1) / THREADS); - bf16_gemv_naive_kernel<<>>(x, w, y, n_in, n_out); - finish(stream, "bf16_gemv"); -} - -void bf16_gemv_split(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, - int threads_per_row, void* stream) { - if (n_in <= 0 || n_out <= 0) return; - // WARP-PER-ROW when the caller asks for 32, because that path needs no shared memory and no barrier - and - // with 48 output rows it is the configuration that fills the machine. A `tpr` that is not 32 and not a - // power of two is refused rather than quietly rounded, because the tree reduction below needs one. - if (threads_per_row == 32) { - const int warps = THREADS / 32; - const unsigned grid = (unsigned) ((n_out + warps - 1) / warps); - bf16_gemv_warp_kernel<<>>(x, w, y, n_in, n_out); - finish(stream, "bf16_gemv_split(warp)"); - return; - } - if (threads_per_row <= 0 || (threads_per_row & (threads_per_row - 1)) != 0) { - std::fprintf(stderr, "bf16_gemv_split: threads_per_row %d must be a power of two (32 selects the " - "warp-per-row path)\n", threads_per_row); - std::exit(1); - } - const unsigned grid = (unsigned) n_out; - bf16_gemv_split_kernel<<>>(x, w, y, n_in, n_out, threads_per_row); - finish(stream, "bf16_gemv_split"); -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/cvec.cu b/src/kernels/cuda/cvec.cu deleted file mode 100644 index 6682932..0000000 --- a/src/kernels/cuda/cvec.cu +++ /dev/null @@ -1,166 +0,0 @@ -// src/kernels/cuda/cvec.cu - see include/strata/kernels/cvec.hpp. -#include "strata/kernels/cvec.hpp" - -#include - -#include - -namespace strata::kernels { -namespace { - -constexpr int THREADS = 256; -constexpr int MAXK = 16; // n_embd up to 4096, held in registers between the dot and the update - -Cvec g_cvec; // the description; its device pointers are the uploading device's -bool g_on_host = false; -// the tables on every device that holds them (a layer split applies the vector on several) -constexpr int kDevices = 64; -struct DevTables { float* dir = nullptr; float* s = nullptr; int* on = nullptr; }; -DevTables g_dev[kDevices]; -std::vector g_dir_host, g_s_host; -int cur_device() { - int d = 0; - if (cudaGetDevice(&d) != cudaSuccess || d < 0 || d >= kDevices) d = 0; - return d; -} -bool upload_here(std::string& err) { - DevTables& t = g_dev[cur_device()]; - if (t.dir != nullptr) return true; - const int flag = g_on_host ? 1 : 0; - if (cudaMalloc(&t.dir, g_dir_host.size() * sizeof(float)) != cudaSuccess || - cudaMalloc(&t.s, g_s_host.size() * sizeof(float)) != cudaSuccess || cudaMalloc(&t.on, sizeof(int)) != cudaSuccess || - cudaMemcpy(t.dir, g_dir_host.data(), g_dir_host.size() * sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess || - cudaMemcpy(t.s, g_s_host.data(), g_s_host.size() * sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess || - cudaMemcpy(t.on, &flag, sizeof(int), cudaMemcpyHostToDevice) != cudaSuccess) { - err = "control vector: device allocation failed"; - t = DevTables{}; - return false; - } - return true; -} - -// the fused hyper-connection read's gate (fused_gr.cu), so a write done here is bitwise the one it would have folded -__device__ __forceinline__ float sigmoidf_(float x) { return 1.0f / (1.0f + __expf(-x)); } - -// one block per (stream, token): the pending write, then h . v over the stream, then the update -__global__ void cvec_kernel(float* __restrict__ R, const float* __restrict__ dir, const float* __restrict__ s_l, - const int* __restrict__ on, int mode, int64_t layer, int n, int hc, int64_t r_ld, - const float* __restrict__ bo, int64_t bo_ld, const float* __restrict__ inj, - int64_t inj_ld, int write) { - const int c = blockIdx.x; - const int64_t t = blockIdx.y; - float* r = R + t * r_ld + (int64_t) c * n; - const float s = s_l[layer]; - const bool steer = *on != 0 && s != 0.0f; // uniform over the block - if (!steer && !write) return; - const float* v = dir + layer * n; - const float w = write ? 2.0f * sigmoidf_(inj[t * inj_ld + c] / (float) hc) : 0.0f; - const float* b = write ? bo + t * bo_ld : nullptr; - float x[MAXK]; - float dot = 0.0f; -#pragma unroll - for (int k = 0; k < MAXK; ++k) { - const int d = threadIdx.x + k * THREADS; - if (d < n) { - float xv = r[d]; - if (write) xv = fmaf(b[d], w, xv); - x[k] = xv; - if (steer && mode == 0) dot = fmaf(xv, v[d], dot); - } - } - if (steer && mode == 0) { - __shared__ float part[THREADS / 32]; -#pragma unroll - for (int o = 16; o > 0; o >>= 1) dot += __shfl_xor_sync(0xffffffffu, dot, o); - if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = dot; - __syncthreads(); - if (threadIdx.x < 32) { - float p = threadIdx.x < THREADS / 32 ? part[threadIdx.x] : 0.0f; -#pragma unroll - for (int o = 16; o > 0; o >>= 1) p += __shfl_xor_sync(0xffffffffu, p, o); - if (threadIdx.x == 0) part[0] = p; - } - __syncthreads(); - dot = part[0] * s; // s (h . v) - } -#pragma unroll - for (int k = 0; k < MAXK; ++k) { - const int d = threadIdx.x + k * THREADS; - if (d < n) { - float xv = x[k]; - if (steer) xv = mode == 0 ? fmaf(-dot, v[d], xv) : xv + v[d]; - r[d] = xv; - } - } -} - -} // namespace - -const Cvec& cvec() { return g_cvec; } - -bool cvec_upload(const std::vector& dir, const std::vector& s, int mode, int first, int last, - int64_t n_embd, int64_t hc, std::string& err) { - if (n_embd < 1 || n_embd > (int64_t) THREADS * MAXK) { err = "control vector: unsupported n_embd"; return false; } - if (s.empty() || dir.size() != s.size() * (size_t) n_embd) { err = "control vector: bad table sizes"; return false; } - int prev = 0; // a new vector replaces the old one on every device - cudaGetDevice(&prev); - for (int d = 0; d < kDevices; ++d) { - if (g_dev[d].dir == nullptr) continue; - cudaSetDevice(d); - cudaDeviceSynchronize(); - cudaFree(g_dev[d].dir); - cudaFree(g_dev[d].s); - cudaFree(g_dev[d].on); - g_dev[d] = DevTables{}; - } - cudaSetDevice(prev); - g_dir_host = dir; - g_s_host = s; - g_on_host = true; - if (!upload_here(err)) return false; - const DevTables& t = g_dev[cur_device()]; - g_cvec.dir = t.dir; - g_cvec.s = t.s; - g_cvec.on = t.on; - g_cvec.mode = mode; - g_cvec.first = first; - g_cvec.last = last; - g_cvec.n_embd = n_embd; - g_cvec.hc = hc; - g_cvec.steered.assign(s.size(), false); - for (size_t l = 0; l < s.size(); ++l) g_cvec.steered[l] = s[l] != 0.0f; - return true; -} - -bool cvec_replicate(std::string& err) { return !g_cvec.loaded() || upload_here(err); } - -void cvec_set_enabled(bool on) { - if (!g_cvec.loaded() || on == g_on_host) return; - int prev = 0; - cudaGetDevice(&prev); - const int v = on ? 1 : 0; - for (int d = 0; d < kDevices; ++d) { - if (g_dev[d].on == nullptr) continue; - cudaSetDevice(d); - cudaDeviceSynchronize(); // nothing in flight may still read the flag - cudaMemcpy(g_dev[d].on, &v, sizeof(int), cudaMemcpyHostToDevice); - } - cudaSetDevice(prev); - g_on_host = on; -} - -bool cvec_enabled() { return g_cvec.loaded() && g_on_host; } - -void cvec_apply(float* R, int64_t layer, int64_t T, int64_t r_ld, const float* bo, int64_t bo_ld, const float* inj, - int64_t inj_ld, bool write, void* stream) { - if (!g_cvec.loaded() || T < 1) return; - const DevTables& t = g_dev[cur_device()]; - if (t.dir == nullptr) throw std::runtime_error("cvec_apply: the control vector is not on this device (cvec_replicate)"); - const dim3 grid((unsigned) g_cvec.hc, (unsigned) T); - cvec_kernel<<>>(R, t.dir, t.s, t.on, g_cvec.mode, layer, - (int) g_cvec.n_embd, (int) g_cvec.hc, r_ld, bo, bo_ld, - inj, inj_ld, write ? 1 : 0); - if (cudaPeekAtLastError() != cudaSuccess) throw std::runtime_error("cvec_apply: launch failed"); -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/dequant_bf16.cu b/src/kernels/cuda/dequant_bf16.cu deleted file mode 100644 index 32601d6..0000000 --- a/src/kernels/cuda/dequant_bf16.cu +++ /dev/null @@ -1,261 +0,0 @@ -// src/kernels/cuda/dequant_bf16.cu - see include/strata/kernels/dequant_bf16.hpp. -// -// Arithmetic transcribed from ggml/src/ggml-quants.c at the pinned llama.cpp (MIT License, Copyright (c) 2023-2026 -// The ggml authors): dequantize_row_q2_0/q4_0/q5_0/q8_0/q3_K/q4_K/q5_K/q6_K/iq4_nl/iq4_xs. -#include "strata/kernels/dequant_bf16.hpp" -#include "strata/kernels/iq_kernels.hpp" - -#include -#include - -#include -#include - -namespace strata::kernels { -namespace { - -__device__ __forceinline__ float h2f(const uint8_t* p) { - return __half2float(__ushort_as_half((uint16_t) (p[0] | (p[1] << 8)))); -} -__device__ __forceinline__ uint16_t f2bf(float f) { - uint32_t u = __float_as_uint(f); - // a NaN (a NaN scale in the block) stays a quiet NaN, as in ggml_compute_fp32_to_bf16 and `bf16_from_f32`: - // the rounding add below would carry it into -0 or inf - if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64u); - u += 0x7fffu + ((u >> 16) & 1u); // round to nearest even - return (uint16_t) (u >> 16); -} -__device__ __forceinline__ void put(uint16_t* o, int i, float v) { o[i] = f2bf(v); } -struct H16 { uint16_t v; }; -__device__ __forceinline__ void put(H16* o, int i, float v) { o[i].v = __half_as_ushort(__float2half_rn(v)); } -__device__ __forceinline__ void put(float* o, int i, float v) { o[i] = v; } - -__constant__ int8_t kv_iq4nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113}; - -__device__ __forceinline__ void scale_min_k4(int j, const uint8_t* q, int& d, int& m) { - if (j < 4) { d = q[j] & 63; m = q[j + 4] & 63; } - else { d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4); m = (q[j + 4] >> 4) | ((q[j] >> 6) << 4); } -} - -// One 32-element group `g` (row-major over the whole slice); `out` points at that group's 32 outputs. -template -__device__ __forceinline__ void group32(const uint8_t* row_blocks, int gi_in_row, T* out) { - if constexpr (TYPE == 42) { // Q2_0: 64 per block of 18 B - const uint8_t* b = row_blocks + (size_t) (gi_in_row / 2) * 18; - const float d = h2f(b); - const int e0 = (gi_in_row % 2) * 32; -#pragma unroll - for (int j = 0; j < 32; ++j) { - const int e = e0 + j; - const int q = (b[2 + e / 4] >> ((e % 4) * 2)) & 3; - put(out, j, (float) (q - 1) * d); - } - } else if constexpr (TYPE == 2) { // Q4_0 - const uint8_t* b = row_blocks + (size_t) gi_in_row * 18; - const float d = h2f(b); - for (int j = 0; j < 16; ++j) { - put(out, j, (float) ((b[2 + j] & 0x0F) - 8) * d); - put(out, j + 16, (float) ((b[2 + j] >> 4) - 8) * d); - } - } else if constexpr (TYPE == 6) { // Q5_0 - const uint8_t* b = row_blocks + (size_t) gi_in_row * 22; - const float d = h2f(b); - const uint32_t qh = (uint32_t) b[2] | ((uint32_t) b[3] << 8) | ((uint32_t) b[4] << 16) | ((uint32_t) b[5] << 24); - for (int j = 0; j < 16; ++j) { - const int xh0 = ((qh >> j) << 4) & 0x10; - const int xh1 = (qh >> (j + 12)) & 0x10; - put(out, j, (float) (((b[6 + j] & 0x0F) | xh0) - 16) * d); - put(out, j + 16, (float) (((b[6 + j] >> 4) | xh1) - 16) * d); - } - } else if constexpr (TYPE == 7) { // Q5_1 - const uint8_t* b = row_blocks + (size_t) gi_in_row * 24; - const float d = h2f(b), m = h2f(b + 2); - const uint32_t qh = (uint32_t) b[4] | ((uint32_t) b[5] << 8) | - ((uint32_t) b[6] << 16) | ((uint32_t) b[7] << 24); - for (int j = 0; j < 16; ++j) { - const int xh0 = ((qh >> j) & 1) << 4; - const int xh1 = ((qh >> (j + 16)) & 1) << 4; - put(out, j, (float) ((b[8 + j] & 15) | xh0) * d + m); - put(out, j + 16, (float) ((b[8 + j] >> 4) | xh1) * d + m); - } - } else if constexpr (TYPE == 8) { // Q8_0 - const uint8_t* b = row_blocks + (size_t) gi_in_row * 34; - const float d = h2f(b); - for (int j = 0; j < 32; ++j) put(out, j, (float) (int8_t) b[2 + j] * d); - } else if constexpr (TYPE == 20) { // IQ4_NL - const uint8_t* b = row_blocks + (size_t) gi_in_row * 18; - const float d = h2f(b); - for (int j = 0; j < 16; ++j) { - put(out, j, d * (float) kv_iq4nl[b[2 + j] & 0xf]); - put(out, j + 16, d * (float) kv_iq4nl[b[2 + j] >> 4]); - } - } else if constexpr (TYPE == 11) { // Q3_K: hmask[32] qs[64] scales[12] d - const uint8_t* b = row_blocks + (size_t) (gi_in_row / 8) * 110; - const int gi = gi_in_row % 8, n = gi / 4, jj = gi % 4; - const uint8_t* hm = b; - const uint8_t* q = b + 32 + n * 32; - const uint8_t* sc = b + 96; - const float d_all = h2f(b + 108); - uint32_t aux[4]; - memcpy(aux, sc, 12); - const uint32_t kmask1 = 0x03030303u, kmask2 = 0x0f0f0f0fu, tmp = aux[2]; - aux[2] = ((aux[0] >> 4) & kmask2) | (((tmp >> 4) & kmask1) << 4); - aux[3] = ((aux[1] >> 4) & kmask2) | (((tmp >> 6) & kmask1) << 4); - aux[0] = (aux[0] & kmask2) | (((tmp >> 0) & kmask1) << 4); - aux[1] = (aux[1] & kmask2) | (((tmp >> 2) & kmask1) << 4); - const int8_t* scales = reinterpret_cast(aux); - const int shift = 2 * jj; - const uint8_t m = (uint8_t) (1u << (n * 4 + jj)); - for (int t = 0; t < 32; ++t) { - const int is = n * 8 + jj * 2 + (t >= 16 ? 1 : 0); - const float dl = d_all * (float) (scales[is] - 32); - put(out, t, dl * (float) ((int) ((q[t] >> shift) & 3) - ((hm[t] & m) ? 0 : 4))); - } - } else if constexpr (TYPE == 12) { // Q4_K: d dmin scales[12] qs[128] - const uint8_t* b = row_blocks + (size_t) (gi_in_row / 8) * 144; - const int gi = gi_in_row % 8, j64 = gi / 2, hi = gi % 2; - const float d = h2f(b), dmin = h2f(b + 2); - int sc, m; - scale_min_k4(gi, b + 4, sc, m); - const float d1 = d * (float) sc, m1 = dmin * (float) m; - const uint8_t* q = b + 16 + 32 * j64; - for (int l = 0; l < 32; ++l) put(out, l, d1 * (float) (hi ? (q[l] >> 4) : (q[l] & 0xF)) - m1); - } else if constexpr (TYPE == 13) { // Q5_K: d dmin scales[12] qh[32] qs[128] - const uint8_t* b = row_blocks + (size_t) (gi_in_row / 8) * 176; - const int gi = gi_in_row % 8, j64 = gi / 2, hi = gi % 2; - const float d = h2f(b), dmin = h2f(b + 2); - int sc, m; - scale_min_k4(gi, b + 4, sc, m); - const float d1 = d * (float) sc, m1 = dmin * (float) m; - const uint8_t* qh = b + 16; - const uint8_t* ql = b + 48 + 32 * j64; - const uint8_t u = (uint8_t) (1u << (2 * j64 + hi)); - for (int l = 0; l < 32; ++l) { - const int nib = hi ? (ql[l] >> 4) : (ql[l] & 0xF); - put(out, l, d1 * (float) (nib + ((qh[l] & u) ? 16 : 0)) - m1); - } - } else if constexpr (TYPE == 14) { // Q6_K: ql[128] qh[64] scales[16] d - const uint8_t* b = row_blocks + (size_t) (gi_in_row / 8) * 210; - const int gi = gi_in_row % 8, n = gi / 4, qu = gi % 4; - const uint8_t* ql = b + 64 * n; - const uint8_t* qh = b + 128 + 32 * n; - const int8_t* sc = reinterpret_cast(b + 192) + 8 * n; - const float d = h2f(b + 208); - for (int l = 0; l < 32; ++l) { - const int is = l / 16; - int q; - if (qu == 0) q = (ql[l] & 0xF) | (((qh[l] >> 0) & 3) << 4); - else if (qu == 1) q = (ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4); - else if (qu == 2) q = (ql[l] >> 4) | (((qh[l] >> 4) & 3) << 4); - else q = (ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4); - put(out, l, d * (float) sc[is + 2 * qu] * (float) (q - 32)); - } - } else if constexpr (TYPE == 23) { // IQ4_XS: d scales_h scales_l[4] qs[128] - const uint8_t* b = row_blocks + (size_t) (gi_in_row / 8) * 136; - const int ib = gi_in_row % 8; - const float d = h2f(b); - const uint16_t scales_h = (uint16_t) (b[2] | (b[3] << 8)); - const int ls = ((b[4 + ib / 2] >> (4 * (ib % 2))) & 0xf) | (((scales_h >> (2 * ib)) & 3) << 4); - const float dl = d * (float) (ls - 32); - const uint8_t* qs = b + 8 + 16 * ib; - for (int j = 0; j < 16; ++j) { - put(out, j, dl * (float) kv_iq4nl[qs[j] & 0xf]); - put(out, j + 16, dl * (float) kv_iq4nl[qs[j] >> 4]); - } - } -} - -template -__global__ void dequant_kernel(const uint8_t* __restrict__ blocks, int64_t row_bytes, int64_t row0, int64_t rows, - int64_t groups_per_row, T* __restrict__ out) { - const int64_t g = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (g >= rows * groups_per_row) return; - const int64_t r = g / groups_per_row, gi = g % groups_per_row; - group32(blocks + (row0 + r) * row_bytes, (int) gi, out + r * groups_per_row * 32 + gi * 32); -} - -bool geometry(int type, int& block_elems, int& block_bytes) { - switch (type) { - case 2: block_elems = 32; block_bytes = 18; return true; - case 6: block_elems = 32; block_bytes = 22; return true; - case 7: block_elems = 32; block_bytes = 24; return true; - case 8: block_elems = 32; block_bytes = 34; return true; - case 20: block_elems = 32; block_bytes = 18; return true; - case 11: block_elems = 256; block_bytes = 110; return true; - case 12: block_elems = 256; block_bytes = 144; return true; - case 13: block_elems = 256; block_bytes = 176; return true; - case 14: block_elems = 256; block_bytes = 210; return true; - case 23: block_elems = 256; block_bytes = 136; return true; - case 42: block_elems = 64; block_bytes = 18; return true; - default: return false; - } -} - -template -void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, T* out, void* stream) { - int be = 0, bb = 0; - if (!geometry(type, be, bb) || cols % be != 0 || rows <= 0) { - std::fprintf(stderr, "dequant: unsupported type %d or shape %lld x %lld\n", type, (long long) rows, - (long long) cols); - std::exit(1); - } - const int64_t row_bytes = cols / be * bb, gpr = cols / 32, total = rows * gpr; - const unsigned grid = (unsigned) ((total + 255) / 256); - const uint8_t* p = (const uint8_t*) blocks; - cudaStream_t st = (cudaStream_t) stream; -#define STRATA_DQ(TY) dequant_kernel<<>>(p, row_bytes, row0, rows, gpr, out); break - switch (type) { - case 2: STRATA_DQ(2); - case 6: STRATA_DQ(6); - case 7: STRATA_DQ(7); - case 8: STRATA_DQ(8); - case 11: STRATA_DQ(11); - case 12: STRATA_DQ(12); - case 13: STRATA_DQ(13); - case 14: STRATA_DQ(14); - case 20: STRATA_DQ(20); - case 23: STRATA_DQ(23); - case 42: STRATA_DQ(42); - } -#undef STRATA_DQ - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { std::fprintf(stderr, "dequant launch: %s\n", cudaGetErrorString(e)); std::exit(1); } -} - -} // namespace - -bool dequant_bf16_supported(int ggml_type) noexcept { - int a, b; - return geometry(ggml_type, a, b); -} - -namespace { -// plan v0.3 P6: the i-quant formats (llama.cpp's dequantizers, iq_kernels.cu) -bool iq_only(int t) { return t == 16 || t == 17 || t == 18 || t == 21 || t == 22 || t == 29; } -} // namespace - -void dequant_bf16(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, uint16_t* out, - void* stream) { - launch(ggml_type, blocks, row0, rows, cols, out, stream); -} - -void dequant_f16(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, uint16_t* out, - void* stream) { - if (iq_only(ggml_type)) { - iq_dequant_f16(ggml_type, (const uint8_t*) blocks + (size_t) row0 * iq_row_bytes(ggml_type, cols), rows * cols, - out, stream); - return; - } - launch(ggml_type, blocks, row0, rows, cols, reinterpret_cast(out), stream); -} - -void dequant_f32(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, float* out, void* stream) { - if (iq_only(ggml_type)) { - iq_dequant_f32(ggml_type, (const uint8_t*) blocks + (size_t) row0 * iq_row_bytes(ggml_type, cols), rows * cols, - out, stream); - return; - } - launch(ggml_type, blocks, row0, rows, cols, out, stream); -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/dequant_s2.cu b/src/kernels/cuda/dequant_s2.cu deleted file mode 100644 index c141b93..0000000 --- a/src/kernels/cuda/dequant_s2.cu +++ /dev/null @@ -1,51 +0,0 @@ -// src/kernels/cuda/dequant_s2.cu - P2.S2's first naive kernel. -// -// S2 is Q2_0's canonical form and 31.64 GiB of the artifact is Q2_0, so this is the single hottest decode in -// the engine. The canonical plane layout is `docs/pack-format.md`'s: codes packed 4 per byte LSB-first -// (element i at byte i/4, bits (i%4)*2 - Q2_0's own convention, kept for every form) and one FP32 scale per -// group (64 elements for S2). The decode is `(code + code_bias) * scale` with `code_bias = -1`, the -// subtraction inside the INTEGER domain, which is what makes it bit-exact (docs/pack-format.md §3.1). -// -// Naive on purpose: one thread per block, no vectors, no shared memory, no unrolling. Phase 3 changes this -// file and the parity test in src/kernels/dequant_s2_parity.cpp is what says whether a change is still right. -#include "strata/kernels/dequant_s2.hpp" - -#include - -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int QK = 64; // S2 group = Q2_0 block = 64 elements -constexpr int CODES_PER_BYTE = 4; - -__global__ void dequant_s2_kernel(const uint8_t* __restrict__ codes, const float* __restrict__ scales, - float* __restrict__ out, long long n_blocks) { - const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x; - if (b >= n_blocks) return; - const float d = scales[b]; - const uint8_t* c = codes + b * (QK / CODES_PER_BYTE); - float* y = out + b * QK; - for (int j = 0; j < QK; ++j) { - const int code = (c[j / CODES_PER_BYTE] >> ((j % CODES_PER_BYTE) * 2)) & 0x03; - y[j] = (float)(code - 1) * d; // the -1 is applied to the CODE, then ONE multiply - } -} - -} // namespace - -void dequant_s2(const uint8_t* codes, const float* scales, float* out, int64_t n_blocks) { - if (n_blocks <= 0) return; - const int threads = 256; - const long long blocks = (n_blocks + threads - 1) / threads; - dequant_s2_kernel<<<(unsigned) blocks, threads>>>(codes, scales, out, n_blocks); - const cudaError_t e = cudaDeviceSynchronize(); - if (e != cudaSuccess) { - std::fprintf(stderr, "dequant_s2: %s\n", cudaGetErrorString(e)); - std::exit(1); - } -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/elementwise.cu b/src/kernels/cuda/elementwise.cu deleted file mode 100644 index 4817763..0000000 --- a/src/kernels/cuda/elementwise.cu +++ /dev/null @@ -1,397 +0,0 @@ -// src/kernels/cuda/elementwise.cu - P2.S5's glue kernels. See the header for why each exists. -#include "strata/kernels/elementwise.hpp" -#include "strata/kernels/dp4a.hpp" - -#include "strata/kernels/bf16_bits.hpp" -#include "strata/kernels/f16_bits.hpp" - -#include - -#include -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int THREADS = 256; - -__global__ void embedding_gather_kernel(const uint8_t* __restrict__ codes, - const float* __restrict__ scales, - const float* __restrict__ offsets, int64_t n, - int code_bits, int code_bias, int group_elems, - float* __restrict__ out) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n) return; - const int per_byte = 8 / code_bits; - const unsigned mask = (1u << code_bits) - 1u; - const int code = (codes[i / per_byte] >> ((i % per_byte) * code_bits)) & mask; - const int64_t group = i / group_elems; - const float product = __fmul_rn((float) (code + code_bias), scales[group]); - out[i] = __fadd_rn(product, offsets ? offsets[group] : 0.0f); -} - -/// `ggml_compute_softplus_f32`: `log1p(exp(x))`, with the large-x branch that avoids overflow. -/// -/// The branch is not cosmetic. `exp(89)` overflows f32 and `exp(20)` is already 4.85e8 where `log1p` loses -/// relative precision; above 20 the function is `x` to within f32 anyway. -__device__ __forceinline__ float softplus_dev(float x) { return x > 20.0f ? x : log1pf(expf(x)); } - -__global__ void gdn_gate_kernel(const float* __restrict__ alpha, const float* __restrict__ dt, - const float* __restrict__ ssm_a, float* __restrict__ gate, int64_t h_v) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= h_v) return; - const int64_t t = i / h_v; // `n_tokens` is the leading dim; the real call has one token - const int64_t h = i % h_v; - gate[i] = softplus_dev(alpha[i] + dt[h]) * ssm_a[h]; - (void) t; -} - -__global__ void scale_kernel(float* __restrict__ x, int64_t n, float s) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) x[i] *= s; -} - -// `dst[i] += src[i]`. See the header: this is what lets R4's GPU half and CPU half run at the same -// time and still add up to one `parts` buffer. -__global__ void add_kernel(float* __restrict__ dst, const float* __restrict__ src, long long n) { - const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) dst[i] += src[i]; -} - -__global__ void to_f16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, int64_t n) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) y[i] = f16_from_f32(x[i]); -} - -__global__ void to_bf16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, int64_t n) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) y[i] = bf16_from_f32(x[i]); -} - -__global__ void silu_kernel(float* __restrict__ x, int64_t n) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n) return; - // DOUBLE then cast, matching `ref/gdn.py`'s numpy: its arrays are f32 but `np.exp` on an f32 array is - // computed to f32 precision by a different algorithm than `expf`, and the reference is the oracle. The - // difference is in the last bits and this is one line. - const double v = (double) x[i]; - x[i] = (float) (v / (1.0 + exp(-v))); -} - -/// A bounded launch: a zero-length grid is illegal, and `n == 0` is a real call (an empty selection). -inline unsigned grid_for(int64_t n) { return (unsigned) ((n + THREADS - 1) / THREADS); } - -/// One WARP per row, reduced through shuffles. The rows here are short and few - (24, 256), (2, 256), -/// (4, 128) - so a block-per-row tree would spend its time in `__syncthreads` for 8 warps of 32, and the whole -/// call is 30 rows. A warp reduction with NO shared memory and NO barrier is the shape that fits. -__global__ void rms_norm_weighted_kernel(float* __restrict__ x, const float* __restrict__ w, int64_t rows, - int64_t cols, float eps) { - - const int lane = threadIdx.x & 31; - const int64_t row = ((int64_t) blockIdx.x * (blockDim.x >> 5)) + (threadIdx.x >> 5); - // **THE ROW GUARD IS NOT DECORATION, AND ITS ABSENCE WAS THE QSA BUG.** The launcher rounds the grid up to - // whole 4-warp blocks, so a call with `rows` = 2 - the QSA k-norm, the only non-multiple-of-4 row count in - // the engine - runs EIGHT warps: rows 0 and 1 are the data, and rows 2 and 3 write 2*cols floats PAST the - // end of `b.kcur`, which in the arena is exactly where `b.vcur` begins. `b.vcur` was therefore silently - // replaced by two rows of `rms_norm(...) * attn_k_norm`: a normalized vector with l2 ~20.6 against V's - // ~5.7, which the attention then attended to. `rope_neox_kernel` has had this guard all along. - if (row >= rows) return; - float* r = x + row * cols; - float acc = 0.0f; - for (int64_t c = lane; c < cols; c += 32) acc += r[c] * r[c]; - for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, off); - // The MEAN, not the sum: `ref/qsa.py::rms_norm` divides by `np.mean(np.square(x))`. Broadcasting the - // reciprocal from lane 0 keeps all 32 lanes on the same value - computing `rsqrt` per lane would be the - // same number but a needless 32-way divergence in the last bit. - float inv = 0.0f; - if (lane == 0) inv = rsqrtf(acc / (float) cols + eps); - inv = __shfl_sync(0xFFFFFFFFu, inv, 0); - for (int64_t c = lane; c < cols; c += 32) r[c] = (w ? r[c] * w[c] : r[c]) * inv; -} - -void sync_if_needed(void* stream, const char* what) { - if (stream != nullptr) return; - const cudaError_t e = cudaDeviceSynchronize(); - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -bool check_launch(const char* what) { - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "%s launch: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } - return true; -} - -} // namespace - -void embedding_gather(const uint8_t* codes, const float* scales, const float* offsets, - int64_t n, int code_bits, int code_bias, int group_elems, - float* out, void* stream) { - if (n <= 0) return; - embedding_gather_kernel<<>>( - codes, scales, offsets, n, code_bits, code_bias, group_elems, out); - check_launch("embedding_gather"); -} - -void gdn_gate(const float* alpha, const float* dt, const float* ssm_a, float* gate, int64_t n_tokens, - int64_t h_v, void* stream) { - if (n_tokens <= 0 || h_v <= 0) return; - const int64_t n = n_tokens * h_v; - gdn_gate_kernel<<>>(alpha, dt, ssm_a, gate, h_v); - check_launch("gdn_gate"); - sync_if_needed(stream, "gdn_gate"); -} - -void scale_inplace(float* x, int64_t n, float s, void* stream) { - if (n <= 0) return; - scale_kernel<<>>(x, n, s); - check_launch("scale_inplace"); - sync_if_needed(stream, "scale_inplace"); -} - -void add_inplace(float* dst, const float* src, int64_t n, void* stream) { - if (n <= 0) return; - add_kernel<<>>(dst, src, n); - check_launch("add_inplace"); - sync_if_needed(stream, "add_inplace"); -} - -void f32_to_f16_bulk(const float* x, uint16_t* y, int64_t n, void* stream) { - if (n <= 0) return; - to_f16_kernel<<>>(x, y, n); - check_launch("f32_to_f16_bulk"); - sync_if_needed(stream, "f32_to_f16_bulk"); -} - -void f32_to_bf16_bulk(const float* x, uint16_t* y, int64_t n, void* stream) { - if (n <= 0) return; - to_bf16_kernel<<>>(x, y, n); - check_launch("f32_to_bf16_bulk"); - sync_if_needed(stream, "f32_to_bf16_bulk"); -} - -void silu_inplace(float* x, int64_t n, void* stream) { - if (n <= 0) return; - silu_kernel<<>>(x, n); - check_launch("silu_inplace"); - sync_if_needed(stream, "silu_inplace"); -} - -/// THE DOORBELL. One thread, one INCREMENT - the cost is the launch, and inside a graph that is paid once. -/// -/// **IT INCREMENTS THE MEMORY, AND IT DOES NOT TAKE THE VALUE AS AN ARGUMENT.** The first version did - -/// doorbell_ring(d_seq, *(h_seq) + 1u) - and that is a CLONED LITERAL: the expression is evaluated on the HOST -/// at CAPTURE time, so the graph rings 1 on every replay and a host waiting for a change waits forever. It -/// would have looked like a working doorbell on the first token, which is the worst way for it to be wrong. -/// **THE FENCE IS NOT DECORATION, AND ITS ABSENCE WAS COSTING ~10 ms PER TOKEN ON THE HOST SIDE.** -/// -/// The ring PUBLISHES three buffers the host is about to read - `h_x_f`, `h_ids`, `h_weights` - so the increment -/// must be ordered after their writes, or the host can observe the ring and then read a payload that has not -/// landed. `__threadfence_system()` is what orders them, and it covers the HOST as well as the device, which is -/// the whole point: the reader is the CPU. -/// -/// Without it the host loop was compensating with a driver call. `session_loop` polled with `cudaEventQuery` -/// on EVERY spin iteration, because round 195 had measured that a memory-only spin never saw the datum flip - -/// and that measurement was right about the symptom and wrong about the cause. The cause is this missing fence: -/// the write was not ordered into host-visible memory, so no amount of reading it would show it, and the driver -/// call was flushing the whole pipeline enough to make it appear. A 10-22 us driver call per iteration is a -/// very expensive substitute for one fence instruction. -/// -/// **THE STORE IS VOLATILE**, like `doorbell_publish_kernel`'s. On RDNA4 (gfx1201) a plain store to mapped pinned -/// memory stays in the GPU's L2 until the stream is synchronized - the host never saw the ring (tests/hip/handoff: -/// 0 of 100 rings seen without a sync; volatile, a system-scope atomic store or a fence after the store: 100 of 100). -__global__ void doorbell_ring_kernel(uint32_t* seq) { - __threadfence_system(); - *(volatile uint32_t*) seq = *(volatile uint32_t*) seq + 1u; -} - -__global__ void doorbell_wait_kernel(const volatile uint32_t* flag, const volatile uint32_t* seq) { - const uint32_t want = *seq; - while (*flag != want) strata_spin_pause(); - __threadfence_system(); -} - -void doorbell_wait(const uint32_t* d_flag, const uint32_t* d_seq, void* stream) { - if (d_flag == nullptr || d_seq == nullptr) return; - doorbell_wait_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(d_flag, d_seq); - check_launch("doorbell_wait"); -} - -__global__ void copy_from_mapped_kernel(float4* __restrict__ dst, const volatile float4* src, int64_t n4) { - for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n4; i += (int64_t) gridDim.x * blockDim.x) { - const float4 v = const_cast(src)[i]; - dst[i] = v; - } -} - -// the CPU rows of a verify window, skipping the rows the GPU plan computes itself (the -// pool writes +0.0 into those, so this writes +0.0 too): block = row, the plan's hit rows `dst[0, *count)`. -__global__ void copy_rows_from_mapped_kernel(float4* __restrict__ dst, const volatile float4* src, int64_t row4, - const int32_t* __restrict__ hit_rows, const int32_t* __restrict__ count) { - const int row = blockIdx.x; - __shared__ int hit; - if (threadIdx.x == 0) { - int h = 0; - const int c = *count; - for (int i = 0; i < c; ++i) h |= hit_rows[i] == row; - hit = h; - } - __syncthreads(); - float4* d = dst + (int64_t) row * row4; - if (hit) { - for (int64_t i = threadIdx.x; i < row4; i += blockDim.x) d[i] = make_float4(0.0f, 0.0f, 0.0f, 0.0f); - } else { - const volatile float4* sr = src + (int64_t) row * row4; - for (int64_t i = threadIdx.x; i < row4; i += blockDim.x) d[i] = const_cast(sr)[i]; - } -} -namespace { -__global__ void scatter_rows_kernel(const float4* __restrict__ src, float4* dst, const int32_t* __restrict__ rows, - int64_t w4) { - const int64_t r = blockIdx.x; - const float4* s = src + r * w4; - float4* d = dst + (int64_t) rows[r] * w4; - for (int64_t i = threadIdx.x; i < w4; i += blockDim.x) d[i] = s[i]; -} -} // namespace -void scatter_rows_f32(const float* src, float* dst, const int32_t* rows, int64_t n, int64_t width, void* stream) { - if (n <= 0) return; - if ((width & 3) != 0 || ((uintptr_t) dst & 15) != 0 || ((uintptr_t) src & 15) != 0) { - std::fprintf(stderr, "scatter_rows_f32: width must be a multiple of 4 and both pointers 16-byte aligned\n"); - std::exit(1); - } - scatter_rows_kernel<<<(unsigned) n, 128, 0, (cudaStream_t) stream>>>((const float4*) src, (float4*) dst, rows, width / 4); -} -void copy_rows_from_mapped(float* dst, const float* src, int64_t rows, int64_t width, const int32_t* hit_rows, - const int32_t* count, void* stream) { - if (rows <= 0) return; - if ((width & 3) != 0 || ((uintptr_t) dst & 15) != 0 || ((uintptr_t) src & 15) != 0) { - std::fprintf(stderr, "copy_rows_from_mapped: width must be a multiple of 4 and both pointers 16-byte aligned\n"); - std::exit(1); - } - copy_rows_from_mapped_kernel<<<(unsigned) rows, 128, 0, (cudaStream_t) stream>>>((float4*) dst, (const volatile float4*) src, - width / 4, hit_rows, count); -} -void copy_from_mapped(float* dst, const float* src, int64_t n, void* stream) { - if (n <= 0) return; - if ((n & 3) != 0 || ((uintptr_t) dst & 15) != 0 || ((uintptr_t) src & 15) != 0) { - std::fprintf(stderr, "copy_from_mapped: n must be a multiple of 4 and both pointers 16-byte aligned\n"); - std::exit(1); - } - const int64_t n4 = n / 4; - const int blocks = (int) ((n4 + 255) / 256 < 64 ? (n4 + 255) / 256 : 64); - copy_from_mapped_kernel<<>>((float4*) dst, (const volatile float4*) src, n4); - check_launch("copy_from_mapped"); -} - -__global__ void doorbell_publish_kernel(const float* __restrict__ x, const int32_t* __restrict__ ids, - const float* __restrict__ w, int n, int k, float* x_out, int32_t* ids_out, - float* w_out, uint32_t* seq) { - for (int i = threadIdx.x; i < n; i += blockDim.x) x_out[i] = x[i]; - if ((int) threadIdx.x < k) { - ids_out[threadIdx.x] = ids[threadIdx.x]; - if (w_out != nullptr) w_out[threadIdx.x] = w[threadIdx.x]; - } - __threadfence_system(); - __syncthreads(); - if (threadIdx.x == 0) { - *(volatile uint32_t*) seq = *(volatile uint32_t*) seq + 1u; - } -} - -__global__ void doorbell_publish_res_kernel(const float* __restrict__ x, const int32_t* __restrict__ ids, - const int32_t* __restrict__ d_res, int n_expert, int n, int k, - float* x_out, int32_t* ids_out, uint32_t* seq) { - int any_miss = 0; - if ((int) threadIdx.x < k) { - const int32_t id = ids[threadIdx.x]; - ids_out[threadIdx.x] = id; - if (d_res == nullptr || id < 0 || id >= n_expert || d_res[id] < 0) any_miss = 1; - } - if (__syncthreads_or(any_miss)) { - for (int i = threadIdx.x; i < n; i += blockDim.x) x_out[i] = x[i]; - __threadfence_system(); - } else if ((int) threadIdx.x < k) { - __threadfence_system(); - } - __syncthreads(); - if (threadIdx.x == 0) { - *(volatile uint32_t*) seq = *(volatile uint32_t*) seq + 1u; - } -} - -// #649 (HIP, STRATA_DOORBELL_STORE=1): the same publish, but the ring is STORED (the step's own number, known at -// capture) instead of read-modify-written over PCIe - one store, no read of host memory from the GPU. -__global__ void doorbell_publish_value_kernel(const float* __restrict__ x, const int32_t* __restrict__ ids, - const float* __restrict__ w, int n, int k, float* x_out, int32_t* ids_out, - float* w_out, uint32_t* seq, uint32_t value) { - for (int i = threadIdx.x; i < n; i += blockDim.x) x_out[i] = x[i]; - if ((int) threadIdx.x < k) { ids_out[threadIdx.x] = ids[threadIdx.x]; w_out[threadIdx.x] = w[threadIdx.x]; } - __threadfence_system(); - __syncthreads(); - if (threadIdx.x == 0) { - __threadfence_system(); - *(volatile uint32_t*) seq = value; - __threadfence_system(); - } -} - -void doorbell_publish_value(const float* x, const int32_t* ids, const float* weights, int64_t n, int64_t k, - float* x_out, int32_t* ids_out, float* weights_out, uint32_t* d_seq, uint32_t value, - void* stream) { - if (k > 1024) { std::fprintf(stderr, "doorbell_publish: k too large\n"); std::exit(1); } - doorbell_publish_value_kernel<<<1, 1024, 0, (cudaStream_t) stream>>>(x, ids, weights, (int) n, (int) k, x_out, - ids_out, weights_out, d_seq, value); -} - -void doorbell_publish(const float* x, const int32_t* ids, const float* weights, int64_t n, int64_t k, float* x_out, - int32_t* ids_out, float* weights_out, uint32_t* d_seq, void* stream) { - if (k > 1024) { std::fprintf(stderr, "doorbell_publish: k too large\n"); std::exit(1); } - doorbell_publish_kernel<<<1, 1024, 0, (cudaStream_t) stream>>>(x, ids, weights, (int) n, (int) k, x_out, ids_out, - weights_out, d_seq); - check_launch("doorbell_publish"); -} - -void doorbell_publish_res(const float* x, const int32_t* ids, const int32_t* d_res, int n_expert, int64_t n, int64_t k, - float* x_out, int32_t* ids_out, uint32_t* d_seq, void* stream) { - if (k > 1024) { std::fprintf(stderr, "doorbell_publish_res: k too large\n"); std::exit(1); } - doorbell_publish_res_kernel<<<1, 1024, 0, (cudaStream_t) stream>>>(x, ids, d_res, n_expert, (int) n, (int) k, - x_out, ids_out, d_seq); - check_launch("doorbell_publish_res"); -} - -__global__ void copy_i32_from_mapped_kernel(int32_t* __restrict__ dst, const volatile int32_t* src, int n) { - for (int i = threadIdx.x; i < n; i += blockDim.x) dst[i] = src[i]; -} - -void copy_i32_from_mapped(int32_t* dst, const int32_t* src, int64_t n, void* stream) { - if (n <= 0) return; - copy_i32_from_mapped_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(dst, (const volatile int32_t*) src, (int) n); - check_launch("copy_i32_from_mapped"); -} - -void doorbell_ring(uint32_t* d_seq, void* stream) { - if (d_seq == nullptr) return; - doorbell_ring_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(d_seq); - check_launch("doorbell_ring"); - sync_if_needed(stream, "doorbell_ring"); -} - -void rms_norm_weighted(float* x, const float* w, int64_t rows, int64_t cols, float eps, void* stream) { - if (rows <= 0 || cols <= 0) return; - // 4 warps per block, so a row count that is not a multiple of 4 wastes at most 3 warps rather than - // launching a block per row for a 2-row call. - const unsigned warps_per_block = 4; - const unsigned grid = (unsigned) ((rows + warps_per_block - 1) / warps_per_block); - rms_norm_weighted_kernel<<>>(x, w, rows, cols, eps); - check_launch("rms_norm_weighted"); - sync_if_needed(stream, "rms_norm_weighted"); -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/fused_gdn.cu b/src/kernels/cuda/fused_gdn.cu deleted file mode 100644 index bdbc3e1..0000000 --- a/src/kernels/cuda/fused_gdn.cu +++ /dev/null @@ -1,169 +0,0 @@ -// src/kernels/cuda/fused_gdn.cu - see include/strata/kernels/fused_gdn.hpp. -#include "strata/kernels/fused_gdn.hpp" - -#include - -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int S = 128; // state size (rows = cols = 128) -constexpr int RG = 4; // row groups -constexpr int RPG = S / RG; // 32 rows per thread - -__global__ void __launch_bounds__(S * RG) gdn_step_norm_kernel(float* __restrict__ state, const float* __restrict__ q, - const float* __restrict__ k, const float* __restrict__ v, - const float* __restrict__ gate, - const float* __restrict__ beta, - const float* __restrict__ z, - const float* __restrict__ gamma, float eps, - float* __restrict__ y, int h_k, int h_v, int silu) { - __shared__ float sk[S], sq[S]; - __shared__ float red[RG][S]; - __shared__ float wsum[S * RG / 32]; - const int head = blockIdx.x; - const int col = threadIdx.x; // 0..127 - const int rg = threadIdx.y; // 0..3 - const int tid = rg * S + col; - const int qh = head % h_k; - if (tid < S) { sk[tid] = k[qh * S + tid]; sq[tid] = q[qh * S + tid]; } - float s[RPG]; - float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col; - const size_t row_stride = (size_t) h_v * S; -#pragma unroll - for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride]; - __syncthreads(); - const float g = __expf(gate[head]); - float kv = 0.0f; -#pragma unroll - for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); - red[rg][col] = kv; - __syncthreads(); - const float kv_col = red[0][col] + red[1][col] + red[2][col] + red[3][col]; - const float delta = (v[head * S + col] - g * kv_col) * beta[head]; - float o = 0.0f; -#pragma unroll - for (int r = 0; r < RPG; ++r) { - s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); - o = fmaf(s[r], sq[rg * RPG + r], o); - base[r * row_stride] = s[r]; - } - __syncthreads(); // every thread has read red[] for kv_col - red[rg][col] = o; - __syncthreads(); - float oc = 0.0f, sq_part = 0.0f; - if (rg == 0) { - oc = (red[0][col] + red[1][col] + red[2][col] + red[3][col]) * rsqrtf((float) S); - sq_part = oc * oc; - } - // RMS over the head's 128 outputs: warps of row group 0 are threads 0..127. - for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part += __shfl_xor_sync(0xffffffffu, sq_part, o2); - if ((tid & 31) == 0) wsum[tid >> 5] = sq_part; - __syncthreads(); - if (rg == 0) { - const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; - const float scale = rsqrtf(ss / (float) S + eps); - const float zz = z[head * S + col]; - // the gate: sigmoid(z) for Flash-Next (unchanged arithmetic), SiLU(z) = z / (1 + exp(-z)) for Qwen3.6 - const float act = silu ? zz / (1.0f + __expf(-zz)) : (1.0f / (1.0f + __expf(-zz))); - y[head * S + col] = oc * scale * gamma[col] * act; - } -} - -__global__ void __launch_bounds__(S) gdn_conv_l2_kernel(float* __restrict__ hist, const float* __restrict__ qkv, - const float* __restrict__ w, float* __restrict__ h, - int qk_heads, float eps) { - __shared__ float part[S / 32]; - const int c = blockIdx.x * S + threadIdx.x; - const float v0 = hist[c * 3], v1 = hist[c * 3 + 1], v2 = hist[c * 3 + 2], x = qkv[c]; - float sum = v0 * w[c * 4] + v1 * w[c * 4 + 1] + v2 * w[c * 4 + 2] + x * w[c * 4 + 3]; - hist[c * 3] = v1; - hist[c * 3 + 1] = v2; - hist[c * 3 + 2] = x; - float y = sum / (1.0f + __expf(-sum)); - if ((int) blockIdx.x < qk_heads) { - float sq = y * y; - for (int o = 16; o > 0; o >>= 1) sq += __shfl_xor_sync(0xffffffffu, sq, o); - if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sq; - __syncthreads(); - const float ss = part[0] + part[1] + part[2] + part[3]; - y *= rsqrtf(ss + eps); - } - h[c] = y; -} - -__global__ void __launch_bounds__(256) gdn_ab_kernel(const float* __restrict__ x, const uint16_t* __restrict__ wa, - const uint16_t* __restrict__ wb, const float* __restrict__ dt, - const float* __restrict__ ssm_a, float* __restrict__ gate, - float* __restrict__ beta, int n, int h_v) { - const int row = blockIdx.x * 8 + (threadIdx.x >> 5), lane = threadIdx.x & 31; - if (row >= 2 * h_v) return; - const bool is_beta = row >= h_v; - const int r = is_beta ? row - h_v : row; - const uint4* w4 = reinterpret_cast((is_beta ? wb : wa) + (size_t) r * n); - float acc = 0.0f; - for (int j = lane; j < n / 8; j += 32) { - const uint4 wv = __ldg(w4 + j); - const float4 xa = *reinterpret_cast(x + j * 8); - const float4 xb = *reinterpret_cast(x + j * 8 + 4); - acc = fmaf(__uint_as_float(wv.x << 16), xa.x, acc); acc = fmaf(__uint_as_float(wv.x & 0xffff0000u), xa.y, acc); - acc = fmaf(__uint_as_float(wv.y << 16), xa.z, acc); acc = fmaf(__uint_as_float(wv.y & 0xffff0000u), xa.w, acc); - acc = fmaf(__uint_as_float(wv.z << 16), xb.x, acc); acc = fmaf(__uint_as_float(wv.z & 0xffff0000u), xb.y, acc); - acc = fmaf(__uint_as_float(wv.w << 16), xb.z, acc); acc = fmaf(__uint_as_float(wv.w & 0xffff0000u), xb.w, acc); - } - for (int o = 16; o > 0; o >>= 1) acc += __shfl_xor_sync(0xffffffffu, acc, o); - if (lane != 0) return; - if (is_beta) { - beta[r] = 1.0f / (1.0f + __expf(-acc)); - } else { - const float v = acc + dt[r]; - const float sp = v > 20.0f ? v : log1pf(__expf(v)); - gate[r] = sp * ssm_a[r]; - } -} - -} // namespace - -void fused_gdn_conv_l2(float* history, const float* qkv, const float* conv_w, float* h, int channels, int qk_heads, - float eps, void* stream) { - if (!history || !qkv || !conv_w || !h || channels % S != 0 || qk_heads < 0 || qk_heads > channels / S) { - std::fprintf(stderr, "fused_gdn_conv_l2: invalid arguments\n"); - std::exit(1); - } - gdn_conv_l2_kernel<<<(unsigned) (channels / S), S, 0, (cudaStream_t) stream>>>(history, qkv, conv_w, h, qk_heads, eps); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { std::fprintf(stderr, "fused_gdn_conv_l2: %s\n", cudaGetErrorString(e)); std::exit(1); } -} - -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) { - if (!x || !w_alpha || !w_beta || !dt || !ssm_a || !gate || !beta || n_embd % 8 != 0 || h_v <= 0) { - std::fprintf(stderr, "fused_gdn_ab: invalid arguments\n"); - std::exit(1); - } - gdn_ab_kernel<<<(unsigned) ((2 * h_v + 7) / 8), 256, 0, (cudaStream_t) stream>>>(x, w_alpha, w_beta, dt, ssm_a, gate, - beta, n_embd, h_v); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { std::fprintf(stderr, "fused_gdn_ab: %s\n", cudaGetErrorString(e)); std::exit(1); } -} - -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) { - if (!state || !q || !k || !v || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v <= 0 || h_v % h_k) { - std::fprintf(stderr, "fused_gdn_step_norm: invalid arguments\n"); - std::exit(1); - } - gdn_step_norm_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>(state, q, k, v, gate, beta, z, - gamma, eps, y, h_k, h_v, - act == GdnGate::Silu ? 1 : 0); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "fused_gdn_step_norm: %s\n", cudaGetErrorString(e)); - std::exit(1); - } -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu deleted file mode 100644 index 71012ff..0000000 --- a/src/kernels/cuda/fused_gr.cu +++ /dev/null @@ -1,1371 +0,0 @@ -// src/kernels/cuda/fused_gr.cu - see include/strata/kernels/fused_gr.hpp. -#include "strata/core/emulate.hpp" -#include "strata/kernels/fused_gr.hpp" -#include "strata/kernels/bf16_bits.hpp" -#include "strata/kernels/verify_kernels.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int N = 2560; // n_embd -constexpr int HC = 4; // streams -constexpr int D = N * HC; // 10240 -constexpr int LR = 320; // hc_lr -constexpr int THREADS = 256; -constexpr int WARPS = THREADS / 32; -constexpr int DOWN_BLOCKS = LR / WARPS; // 40 blocks of 8 rows; one more for the inject rows -constexpr int UP_COLS = 32; // columns d per `up` block (x 4 streams = 128 rows) -constexpr int UP_BLOCKS = N / UP_COLS; // 80 - -__device__ __forceinline__ float warp_sum(float v) { -#pragma unroll - for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); - return v; -} -__device__ __forceinline__ float sigmoidf_(float x) { return 1.0f / (1.0f + __expf(-x)); } - -// 8 bf16 packed in a uint4 against 8 floats. -__device__ __forceinline__ float dot8(const uint4 w, const float* x) { - float acc = 0.0f; - const uint32_t v[4] = {w.x, w.y, w.z, w.w}; -#pragma unroll - for (int j = 0; j < 4; ++j) { - acc = fmaf(__uint_as_float(v[j] << 16), x[2 * j], acc); - acc = fmaf(__uint_as_float(v[j] & 0xffff0000u), x[2 * j + 1], acc); - } - return acc; -} - -__global__ void __launch_bounds__(THREADS) gr_down_kernel(FusedGrArgs a) { - __shared__ __align__(16) float xn[D]; - __shared__ float part[WARPS][HC]; - __shared__ float s_rs[HC]; - const int t = threadIdx.x, lane = t & 31, warp = t >> 5; - float gw[HC]; -#pragma unroll - for (int c = 0; c < HC; ++c) gw[c] = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; - // 1. R' * w_norm into shared memory, and the per-stream sums of squares of R'. - float ss[HC] = {0.0f, 0.0f, 0.0f, 0.0f}; - for (int i = t * 4; i < D; i += THREADS * 4) { - const int c = i / N, d = i - c * N; - float4 r = *reinterpret_cast(a.R + i); - if (a.apply) { - const float4 b = *reinterpret_cast(a.bo_prev + d); - r.x = fmaf(b.x, gw[c], r.x); r.y = fmaf(b.y, gw[c], r.y); - r.z = fmaf(b.z, gw[c], r.z); r.w = fmaf(b.w, gw[c], r.w); - } - const float4 g = *reinterpret_cast(a.w_norm + i); - float sq = r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; -#pragma unroll - for (int cc = 0; cc < HC; ++cc) if (cc == c) ss[cc] += sq; - *reinterpret_cast(xn + i) = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w); - } -#pragma unroll - for (int c = 0; c < HC; ++c) { - const float v = warp_sum(ss[c]); - if (lane == 0) part[warp][c] = v; - } - __syncthreads(); - if (t < HC) { - float s = 0.0f; - for (int w = 0; w < WARPS; ++w) s += part[w][t]; - s_rs[t] = rsqrtf(s / (float) N + a.eps); - if (blockIdx.x == 0) a.rs[t] = s_rs[t]; - } - __syncthreads(); - for (int i = t; i < D; i += THREADS) xn[i] *= s_rs[i / N]; - __syncthreads(); - // 2. one warp per output row: 10240 bf16 = 1280 chunks of 8, 40 per lane. - const bool inject_block = blockIdx.x == DOWN_BLOCKS; - const int row = inject_block ? warp : blockIdx.x * WARPS + warp; - if (inject_block && (a.w_inject == nullptr || warp >= HC)) return; - const uint16_t* wrow = (inject_block ? a.w_inject : a.w_down) + (size_t) row * D; - const uint4* w4 = reinterpret_cast(wrow); - float acc = 0.0f; -#pragma unroll 4 - for (int j = lane; j < D / 8; j += 32) acc += dot8(__ldg(w4 + j), xn + j * 8); - acc = warp_sum(acc); - if (lane != 0) return; - if (inject_block) { - a.inject_out[row] = acc; - } else { - const float x = acc / (float) HC; - a.lo[row] = x / (1.0f + __expf(-x)); - } -} - -__global__ void __launch_bounds__(THREADS) gr_up_kernel(FusedGrArgs a) { - __shared__ __align__(16) float lo[LR]; - __shared__ float g[HC][UP_COLS]; - const int t = threadIdx.x, lane = t & 31, warp = t >> 5; - const int d0 = blockIdx.x * UP_COLS; - for (int k = t; k < LR; k += THREADS) lo[k] = a.lo[k]; - __syncthreads(); - // 128 rows (4 streams x 32 columns), 16 per warp: 320 bf16 = 40 chunks of 8. - for (int r = warp; r < HC * UP_COLS; r += WARPS) { - const int c = r / UP_COLS, dd = r - c * UP_COLS, i = c * N + d0 + dd; - const uint4* w4 = reinterpret_cast(a.w_up + (size_t) i * LR); - float acc = dot8(__ldg(w4 + lane), lo + lane * 8); - if (lane < LR / 8 - 32) acc += dot8(__ldg(w4 + 32 + lane), lo + (32 + lane) * 8); - acc = warp_sum(acc); - if (lane == 0) { - float rv = a.R[i]; - if (a.apply) { - rv = fmaf(a.bo_prev[d0 + dd], 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC), rv); - a.R_out[i] = rv; // this block owns column d0+dd of every stream - } - const float x = rv * a.w_norm[i] * a.rs[c]; - g[c][dd] = x * sigmoidf_(acc); - } - } - __syncthreads(); - if (t < UP_COLS) { - float s = 0.0f; -#pragma unroll - for (int c = 0; c < HC; ++c) s += g[c][t]; - a.mixed[d0 + t] = s / (float) HC; - } -} - -// ================================ plan v0.3 P6: T tokens, one weight read ================================ -struct GrMulti { - FusedGrArgs a[kFusedGrMaxT]; - float* xn; - int T; -}; - -// Step 1 of `gr_down_kernel`, one block per token, same threads and reduction order: rs[t] and xn[t] to global. -__global__ void __launch_bounds__(THREADS) gr_norm_multi_kernel(GrMulti m) { - __shared__ float part[WARPS][HC]; - __shared__ float s_rs[HC]; - const FusedGrArgs& a = m.a[blockIdx.x]; - float* xn = m.xn + (size_t) blockIdx.x * D; - const int t = threadIdx.x, lane = t & 31, warp = t >> 5; - float gw[HC]; -#pragma unroll - for (int c = 0; c < HC; ++c) gw[c] = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; - float ss[HC] = {0.0f, 0.0f, 0.0f, 0.0f}; - for (int i = t * 4; i < D; i += THREADS * 4) { - const int c = i / N, d = i - c * N; - float4 r = *reinterpret_cast(a.R + i); - if (a.apply) { - const float4 b = *reinterpret_cast(a.bo_prev + d); - r.x = fmaf(b.x, gw[c], r.x); r.y = fmaf(b.y, gw[c], r.y); - r.z = fmaf(b.z, gw[c], r.z); r.w = fmaf(b.w, gw[c], r.w); - } - const float4 g = *reinterpret_cast(a.w_norm + i); - float sq = r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; -#pragma unroll - for (int cc = 0; cc < HC; ++cc) if (cc == c) ss[cc] += sq; - *reinterpret_cast(xn + i) = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w); - } -#pragma unroll - for (int c = 0; c < HC; ++c) { - const float v = warp_sum(ss[c]); - if (lane == 0) part[warp][c] = v; - } - __syncthreads(); - if (t < HC) { - float s = 0.0f; - for (int w = 0; w < WARPS; ++w) s += part[w][t]; - s_rs[t] = rsqrtf(s / (float) N + a.eps); - a.rs[t] = s_rs[t]; - } - __syncthreads(); - for (int i = t; i < D; i += THREADS) xn[i] *= s_rs[i / N]; -} - -// Step 2 of `gr_down_kernel` for T tokens. One warp per row (so each lane accumulates the same chunks in the -// same order as the single-token kernel); per tile the lane's weight chunks are loaded BEFORE the activation -// tile is staged, so the DRAM and L2 traffic are in flight together. -// -// TILEV = xn floats per token staged at a time. The tile only changes the staging granularity: the lane's chunk -// order (lane + 32*q within the tile, tiles ascending) is strictly increasing for either value, so the results are -// bitwise identical to `gr_down_kernel` for both. 2560 stages 320 chunks of 8 per tile (10 per lane); cards whose -// opt-in below 8 * 2560 * 4 B slices the tokens - sm_75 (64 KiB) carries 6 tokens of it - run TILEV 1280 instead, -// which fits all eight tokens in one 40 KiB launch and stages 160 chunks of 8 (5 per lane, half the registers held -// for the weight prefetch); smaller tiles raise how many blocks share an SM (the 41-block grid), e.g. three blocks -// of four tokens instead of one on sm_75. -template -__global__ void __launch_bounds__(THREADS) gr_down_multi_kernel(GrMulti m) { - constexpr int TQ = TILEV / 8 / 32; // uint4 weight chunks per lane per tile - extern __shared__ __align__(16) float tile[]; // [T][TILEV] - const int t = threadIdx.x, lane = t & 31, warp = t >> 5; - const int T = m.T; - const bool inject_block = blockIdx.x == DOWN_BLOCKS; - const int row = inject_block ? warp : blockIdx.x * WARPS + warp; - const bool active = !(inject_block && (m.a[0].w_inject == nullptr || warp >= HC)); - const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D; - const uint4* w4 = reinterpret_cast(wrow); - float acc[MAX_T]; -#pragma unroll - for (int k = 0; k < MAX_T; ++k) acc[k] = 0.0f; - for (int base = 0; base < D; base += TILEV) { - uint4 wv[TQ]; - if (active) { -#pragma unroll - for (int q = 0; q < TQ; ++q) wv[q] = __ldg(w4 + base / 8 + lane + 32 * q); - } - __syncthreads(); // the previous tile is consumed - const float4* src4 = reinterpret_cast(m.xn); - float4* tile4 = reinterpret_cast(tile); - for (int i = t; i < T * (TILEV / 4); i += THREADS) { - const int k = i / (TILEV / 4), off = i - k * (TILEV / 4); - tile4[i] = src4[((size_t) k * D + base) / 4 + off]; - } - __syncthreads(); - if (!active) continue; -#pragma unroll - for (int q = 0; q < TQ; ++q) { - const int j = lane + 32 * q; -#pragma unroll - for (int k = 0; k < MAX_T; ++k) - if (k < T) acc[k] += dot8(wv[q], tile + k * TILEV + j * 8); - } - } - if (!active) return; - float s[MAX_T]; -#pragma unroll - for (int k = 0; k < MAX_T; ++k) s[k] = k < T ? warp_sum(acc[k]) : 0.0f; - // lane k writes token k (every lane holds every sum after the xor reduction) -#pragma unroll - for (int k = 0; k < MAX_T; ++k) { - if (k >= T || lane != k) continue; - if (inject_block) { - m.a[k].inject_out[row] = s[k]; - } else { - const float x = s[k] / (float) HC; - m.a[k].lo[row] = x / (1.0f + __expf(-x)); - } - } -} - -constexpr int UPM_COLS = 16; // columns per block (x 4 streams = 64 rows, 8 per warp) -constexpr int UPM_BLOCKS = N / UPM_COLS; // 160 - -// `gr_up_kernel` for T tokens: each row of w_up read once; the T dots reduced by xor so every lane holds every -// sum, and lane k runs token k's epilogue - the T epilogues in parallel instead of one after another. -__global__ void __launch_bounds__(THREADS) gr_up_multi_kernel(GrMulti m) { - __shared__ __align__(16) float lo[kFusedGrMaxT][LR]; - __shared__ float g[kFusedGrMaxT][HC][UPM_COLS]; - const int t = threadIdx.x, lane = t & 31, warp = t >> 5; - const int T = m.T; - const int d0 = blockIdx.x * UPM_COLS; - for (int i = t; i < T * LR; i += THREADS) lo[i / LR][i % LR] = m.a[i / LR].lo[i % LR]; - __syncthreads(); - for (int r = warp; r < HC * UPM_COLS; r += WARPS) { - const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; - const uint4* w4 = reinterpret_cast(m.a[0].w_up + (size_t) i * LR); - const uint4 wa = __ldg(w4 + lane); - const uint4 wb = lane < LR / 8 - 32 ? __ldg(w4 + 32 + lane) : make_uint4(0, 0, 0, 0); - // the epilogue inputs of this lane's token, fetched while the dots run - float rv = 0.0f, wn = 0.0f, rsc = 0.0f, bo = 0.0f, ip = 0.0f; - bool apply = false; - if (lane < T) { - const FusedGrArgs& a = m.a[lane]; - rv = a.R[i]; - wn = a.w_norm[i]; - rsc = a.rs[c]; - apply = a.apply; - if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; } - } - float mine = 0.0f; -#pragma unroll - for (int k = 0; k < kFusedGrMaxT; ++k) { - if (k >= T) break; - float acc = dot8(wa, lo[k] + lane * 8); - if (lane < LR / 8 - 32) acc += dot8(wb, lo[k] + (32 + lane) * 8); - acc = warp_sum(acc); - if (lane == k) mine = acc; - } - if (lane < T) { - if (apply) { - rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv); - m.a[lane].R_out[i] = rv; - } - const float x = rv * wn * rsc; - g[lane][c][dd] = x * sigmoidf_(mine); - } - } - __syncthreads(); - for (int i = t; i < T * UPM_COLS; i += THREADS) { - const int k = i / UPM_COLS, col = i - k * UPM_COLS; - float s = 0.0f; -#pragma unroll - for (int c = 0; c < HC; ++c) s += g[k][c][col]; - m.a[k].mixed[d0 + col] = s / (float) HC; - } -} - - -// ================================ hc read v3 (opt-in: STRATA_GR_V3=1) - two kernels, stream-split ================ -// The norm kernel runs on only T blocks (~16 us of pure latency per call) and `down` on 41 blocks (~280 GB/s). -// v3: `down` is split over (row group, stream[, column half]) = 164 or 328 blocks; each block stages its slice of -// R' * w_norm for the T tokens, reduces that slice's sum of squares itself, and writes UNSCALED partial dots. The -// rms scale is per stream, so w_down . xn = sum_c rs[c] * (w_down[:, c] . (R'[c] * w_norm[c])) - `up` applies it -// in its prologue (lo, inject, rs). Same maths, ANOTHER SUMMATION ORDER: not bitwise the default kernels, hence -// opt-in. Dynamic shared memory is T * (N / S) floats: S (1 or 2 column halves) is the smallest that fits the -// card's opt-in limit at kFusedGrMaxT tokens (Ampere 99 KB: S = 1; Turing / HIP 64 KB: S = 2); a card where -// neither fits keeps the default kernels. -constexpr int PR = LR + HC; // partial rows per (token, stream): 320 down + 4 inject -constexpr int TQ3 = N / 8 / 32; // uint4 weight chunks per lane in one stream's slice (10) - -template -__global__ void __launch_bounds__(THREADS) gr_down_v3_kernel(GrMulti m, float* __restrict__ part, float* __restrict__ ssg) { - extern __shared__ __align__(16) float xs[]; // [T][N / S] - constexpr int R2 = 1; // down rows per warp - __shared__ float red[WARPS][MAX_T]; - const int t = threadIdx.x, lane = t & 31, warp = t >> 5; - const int T = EXACT_T ? MAX_T : m.T; - // S = 2: each stream's 2560 columns in two halves (blockIdx.y = stream * S + half): twice the blocks - constexpr int SL = N / S, TQS = SL / 8 / 32; - const int rg = blockIdx.x, c = blockIdx.y / S, h = blockIdx.y - (blockIdx.y / S) * S; - constexpr int NDB = LR / (WARPS * R2); // down row blocks per stream; block NDB = the inject rows - const bool inject_block = rg == NDB; - // warp w owns rows row0 + w * R2 + r (r < R2); the inject block: warps 0-3, one row each - const int row0 = inject_block ? warp : (rg * WARPS + warp) * R2; - const int nrows = inject_block ? ((m.a[0].w_inject != nullptr && warp < HC) ? 1 : 0) : R2; - const bool active = nrows > 0; - const uint16_t* wbase = inject_block ? m.a[0].w_inject : m.a[0].w_down; - float ssp[MAX_T]; -#pragma unroll - for (int k = 0; k < MAX_T; ++k) { - ssp[k] = 0.0f; - if (!EXACT_T && k >= T) continue; - const FusedGrArgs& a = m.a[k]; - const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; - const float4* R4 = reinterpret_cast(a.R + (size_t) c * N + (size_t) h * SL); - const float4* G4 = reinterpret_cast(a.w_norm + (size_t) c * N + (size_t) h * SL); - const float4* B4 = reinterpret_cast(a.bo_prev + (size_t) h * SL); - float4* X4 = reinterpret_cast(xs + (size_t) k * SL); - for (int i = t; i < SL / 4; i += THREADS) { - float4 r = R4[i]; - if (a.apply) { - const float4 b = B4[i]; - r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); - r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); - } - const float4 g = G4[i]; - ssp[k] += r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; - X4[i] = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w); - } - } -#pragma unroll - for (int k = 0; k < MAX_T; ++k) { - if (!EXACT_T && k >= T) break; - const float v = warp_sum(ssp[k]); - if (lane == 0) red[warp][k] = v; - } - __syncthreads(); - if (rg == 0 && t < T) { - float sum = 0.0f; - for (int w = 0; w < WARPS; ++w) sum += red[w][t]; - ssg[(t * HC + c) * S + h] = sum; - } - if (!active) return; -#pragma unroll - for (int r = 0; r < R2; ++r) { - if (r >= nrows) break; - const uint4* w4 = reinterpret_cast(wbase + (size_t) (row0 + r) * D + (size_t) c * N + (size_t) h * SL); - float acc[MAX_T]; -#pragma unroll - for (int k = 0; k < MAX_T; ++k) acc[k] = 0.0f; -#pragma unroll - for (int q = 0; q < TQS; ++q) { - const int j = lane + 32 * q; - const uint4 wvq = __ldg(w4 + j); -#pragma unroll - for (int k = 0; k < MAX_T; ++k) - if (EXACT_T || k < T) acc[k] += dot8(wvq, xs + (size_t) k * SL + j * 8); - } - const int prow = inject_block ? LR + warp : row0 + r; -#pragma unroll - for (int k = 0; k < MAX_T; ++k) { - if (!EXACT_T && k >= T) break; - const float v = warp_sum(acc[k]); - if (lane == 0) part[(((size_t) k * HC + c) * S + h) * PR + prow] = v; - } - } -} - -template -__global__ void __launch_bounds__(THREADS) gr_up_v3_kernel(GrMulti m, const float* __restrict__ part, - const float* __restrict__ ssg) { - __shared__ __align__(16) float lo[MAX_T][LR]; - __shared__ float rsS[MAX_T][HC]; - __shared__ float g[MAX_T][HC][UPM_COLS]; - const int t = threadIdx.x, lane = t & 31, warp = t >> 5; - const int T = EXACT_T ? MAX_T : m.T; - const int d0 = blockIdx.x * UPM_COLS; - constexpr int RPW = HC * UPM_COLS / WARPS; // 8 rows per warp - if (t < T * HC) { - const int k = t / HC, c = t - k * HC; - float ss = 0.0f; -#pragma unroll - for (int h = 0; h < S; ++h) ss += ssg[t * S + h]; - const float r = rsqrtf(ss / (float) N + m.a[k].eps); - rsS[k][c] = r; - if (blockIdx.x == 0) m.a[k].rs[c] = r; - } - __syncthreads(); - for (int i = t; i < T * LR; i += THREADS) { - const int k = i / LR, r = i - k * LR; - float sum = 0.0f; -#pragma unroll - for (int c = 0; c < HC; ++c) { - float p = 0.0f; -#pragma unroll - for (int h = 0; h < S; ++h) p += part[(((size_t) k * HC + c) * S + h) * PR + r]; - sum = fmaf(rsS[k][c], p, sum); - } - const float x = sum / (float) HC; - lo[k][r] = x / (1.0f + __expf(-x)); - } - if (blockIdx.x == 0 && t < T * HC) { - const int k = t / HC, cc = t - k * HC; - if (m.a[k].w_inject != nullptr) { - float sum = 0.0f; -#pragma unroll - for (int c = 0; c < HC; ++c) { - float p = 0.0f; -#pragma unroll - for (int h = 0; h < S; ++h) p += part[(((size_t) k * HC + c) * S + h) * PR + LR + cc]; - sum = fmaf(rsS[k][c], p, sum); - } - m.a[k].inject_out[cc] = sum; - } - } - __syncthreads(); -#pragma unroll - for (int q = 0; q < RPW; ++q) { - const int r = warp + q * WARPS; - const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; - const uint4* w4 = reinterpret_cast(m.a[0].w_up + (size_t) i * LR); - const uint4 wa = __ldg(w4 + lane); - const uint4 wb = lane < LR / 8 - 32 ? __ldg(w4 + 32 + lane) : make_uint4(0, 0, 0, 0); - float rv = 0.0f, wn = 0.0f, bo = 0.0f, ip = 0.0f; - bool apply = false; - if (lane < T) { - const FusedGrArgs& a = m.a[lane]; - rv = a.R[i]; - wn = a.w_norm[i]; - apply = a.apply; - if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; } - } - float mine = 0.0f; -#pragma unroll - for (int k = 0; k < MAX_T; ++k) { - if (!EXACT_T && k >= T) break; - float acc = dot8(wa, lo[k] + lane * 8); - if (lane < LR / 8 - 32) acc += dot8(wb, lo[k] + (32 + lane) * 8); - acc = warp_sum(acc); - if (lane == k) mine = acc; - } - if (lane < T) { - if (apply) { - rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv); - m.a[lane].R_out[i] = rv; - } - const float x = rv * wn * rsS[lane][c]; - g[lane][c][dd] = x * sigmoidf_(mine); - } - } - __syncthreads(); - for (int i = t; i < T * UPM_COLS; i += THREADS) { - const int k = i / UPM_COLS, col = i - k * UPM_COLS; - float sum = 0.0f; -#pragma unroll - for (int c = 0; c < HC; ++c) sum += g[k][c][col]; - m.a[k].mixed[d0 + col] = sum / (float) HC; - } -} -// ================================ #315: split / staged - the same arithmetic, split differently ================== -// The multi read's variants beside the plain read (0.1.31's default; not main's opt-in STRATA_GR_V3 read, which sums -// in another order). Every variant computes each output with exactly the plain read's operations in its order (so -// bitwise the plain read and the single-token read); only who does what, and when, changes. `fused_gr_check` -// compares them on the card before a verify window uses them (STRATA_HC_SPLIT below). -// - the norm (split and staged): one block per token AND stream instead of one per token. Each thread visits -// exactly the elements, in the order, it visited for that stream in the plain read, so every sum of squares and rs -// is the same; then it recomputes its R' * w_norm and writes it times rs (the plain read stored the product and -// scaled it in place: the same two roundings). On an RTX 4080 SUPER, the plain read's norm took 0.58 ms per -// 4-token round (96 launches of 1-4 blocks), this one 0.23 ms. -// - the down projection, split: the plain read's kernel. -// - the down projection, staged: the plain read's 8 rows per block and lane order, but the activations arrive by -// cp.async in half-stream tiles, two in flight, so no thread waits on a chain of loads, and they sit in shared -// memory as two planes (floats 0-3 and 4-7 of every 8), so a warp's reads hit no bank twice. The next tile's -// weights are loaded while the current one is used. A tile is 160 = 5 x 32 chunks of 8, so a lane still -// accumulates its chunks lane + 32 q in ascending order, as in the plain read with either tile. Before sm_80 -// (and on HIP) the staging is a plain copy: the same bits, only not asynchronous. -constexpr int kHcPlain = 1, kHcSplit = 2, kHcStaged = 3; -constexpr int H_TILE = 1280; // staged tile: half a stream = 160 chunks of 8, 5 per lane -constexpr int HQ = H_TILE / 8 / 32; -constexpr int N_HTILES = D / H_TILE; // 8 -static_assert(N % H_TILE == 0, "a staged tile never straddles two streams"); -static_assert(H_TILE % 256 == 0, "a staged tile holds whole rounds of 32 chunks: the plain read's lane order"); - -__global__ void __launch_bounds__(THREADS) gr_norm_split_kernel(GrMulti m) { - __shared__ float part[WARPS]; - __shared__ float s_rs; - const FusedGrArgs& a = m.a[blockIdx.x]; - const int c = blockIdx.y; - float* xn = m.xn + (size_t) blockIdx.x * D; - const int t = threadIdx.x, lane = t & 31, warp = t >> 5; - const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; - float ss = 0.0f; - for (int i = t * 4; i < D; i += THREADS * 4) { - if (i / N != c) continue; // another stream's element: another block's - const int d = i - c * N; - float4 r = *reinterpret_cast(a.R + i); - if (a.apply) { - const float4 b = *reinterpret_cast(a.bo_prev + d); - r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); - r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); - } - const float sq = r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; - ss += sq; - } - const float v = warp_sum(ss); - if (lane == 0) part[warp] = v; - __syncthreads(); - if (t == 0) { - float s = 0.0f; - for (int w = 0; w < WARPS; ++w) s += part[w]; - s_rs = rsqrtf(s / (float) N + a.eps); - a.rs[c] = s_rs; - } - __syncthreads(); - const float rs = s_rs; - for (int i = t * 4; i < D; i += THREADS * 4) { - if (i / N != c) continue; - const int d = i - c * N; - float4 r = *reinterpret_cast(a.R + i); - if (a.apply) { - const float4 b = *reinterpret_cast(a.bo_prev + d); - r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); - r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); - } - const float4 g = *reinterpret_cast(a.w_norm + i); - const float px = r.x * g.x, py = r.y * g.y, pz = r.z * g.z, pw = r.w * g.w; - *reinterpret_cast(xn + i) = make_float4(px * rs, py * rs, pz * rs, pw * rs); - } -} - -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 && !defined(__HIPCC__) -#define STRATA_GR_CP_ASYNC 1 -#endif -__device__ __forceinline__ void cp_async16(void* smem, const void* gmem) { -#if defined(STRATA_GR_CP_ASYNC) - const unsigned sa = (unsigned) __cvta_generic_to_shared(smem); - asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(sa), "l"(gmem) : "memory"); -#else - *reinterpret_cast(smem) = *reinterpret_cast(gmem); -#endif -} -__device__ __forceinline__ void cp_async_commit() { -#if defined(STRATA_GR_CP_ASYNC) - asm volatile("cp.async.commit_group;\n" ::: "memory"); -#endif -} -__device__ __forceinline__ void cp_async_wait1() { -#if defined(STRATA_GR_CP_ASYNC) - asm volatile("cp.async.wait_group 1;\n" ::: "memory"); -#endif -} -__device__ __forceinline__ void cp_async_wait0() { -#if defined(STRATA_GR_CP_ASYNC) - asm volatile("cp.async.wait_group 0;\n" ::: "memory"); -#endif -} - -// `dot8` with its 8 activations as two float4: the same eight fmaf in the same order -__device__ __forceinline__ float dot8v(const uint4 w, const float4 x0, const float4 x1) { - float acc = 0.0f; - acc = fmaf(__uint_as_float(w.x << 16), x0.x, acc); - acc = fmaf(__uint_as_float(w.x & 0xffff0000u), x0.y, acc); - acc = fmaf(__uint_as_float(w.y << 16), x0.z, acc); - acc = fmaf(__uint_as_float(w.y & 0xffff0000u), x0.w, acc); - acc = fmaf(__uint_as_float(w.z << 16), x1.x, acc); - acc = fmaf(__uint_as_float(w.z & 0xffff0000u), x1.y, acc); - acc = fmaf(__uint_as_float(w.w << 16), x1.z, acc); - acc = fmaf(__uint_as_float(w.w & 0xffff0000u), x1.w, acc); - return acc; -} - -// Stage tile `h` of every token into `buf`: [T][2 planes][160 chunks] float4, plane 0 = floats 0-3 of a chunk. -__device__ __forceinline__ void stage_htile(const GrMulti& m, int T, int h, float4* buf, int t) { - for (int i = t; i < T * (H_TILE / 4); i += THREADS) { - const int k = i / (H_TILE / 4), s4 = i - k * (H_TILE / 4); // s4: float4 of the tile, chunk s4/2, half s4&1 - const float* src = m.xn + (size_t) k * D + (size_t) h * H_TILE + (size_t) s4 * 4; - cp_async16(buf + (size_t) k * (H_TILE / 4) + (s4 & 1) * (H_TILE / 8) + (s4 >> 1), src); - } -} - -template -__global__ void __launch_bounds__(THREADS) gr_down_staged_kernel(GrMulti m) { - extern __shared__ __align__(16) float4 hbuf[]; // 2 buffers x [T][2][160] float4 - const int t = threadIdx.x, lane = t & 31, warp = t >> 5; - const int T = m.T; - const bool inject_block = blockIdx.x == DOWN_BLOCKS; - const int row = inject_block ? warp : blockIdx.x * WARPS + warp; - const bool active = !(inject_block && (m.a[0].w_inject == nullptr || warp >= HC)); - const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D; - const uint4* w4 = reinterpret_cast(wrow); - const size_t buf_f4 = (size_t) T * (H_TILE / 4); // float4 per buffer (the second one follows the first) - float acc[MAX_T]; -#pragma unroll - for (int k = 0; k < MAX_T; ++k) acc[k] = 0.0f; - uint4 wv[HQ], wnext[HQ]; - if (active) { -#pragma unroll - for (int q = 0; q < HQ; ++q) wv[q] = __ldg(w4 + lane + 32 * q); - } - stage_htile(m, T, 0, hbuf, t); - cp_async_commit(); - stage_htile(m, T, 1, hbuf + buf_f4, t); - cp_async_commit(); -#pragma unroll 1 - for (int h = 0; h < N_HTILES; ++h) { - if (active && h + 1 < N_HTILES) { -#pragma unroll - for (int q = 0; q < HQ; ++q) wnext[q] = __ldg(w4 + (h + 1) * (H_TILE / 8) + lane + 32 * q); - } - if (h + 1 < N_HTILES) cp_async_wait1(); // tile h has landed (h + 1 may still be on its way) - else cp_async_wait0(); - __syncthreads(); - const float4* cur = hbuf + (h & 1) * buf_f4; - if (active) { -#pragma unroll - for (int q = 0; q < HQ; ++q) { - const int j = lane + 32 * q; -#pragma unroll - for (int k = 0; k < MAX_T; ++k) { - if (k < T) { - const float4* pk = cur + (size_t) k * (H_TILE / 4); - acc[k] += dot8v(wv[q], pk[j], pk[H_TILE / 8 + j]); - } - } - } - } - __syncthreads(); // every warp is done with buffer h & 1 - if (h + 2 < N_HTILES) stage_htile(m, T, h + 2, hbuf + (h & 1) * buf_f4, t); - cp_async_commit(); // an empty group at the end keeps the wait counts simple - if (h + 1 < N_HTILES) { -#pragma unroll - for (int q = 0; q < HQ; ++q) wv[q] = wnext[q]; - } - } - if (!active) return; - float s[MAX_T]; -#pragma unroll - for (int k = 0; k < MAX_T; ++k) s[k] = k < T ? warp_sum(acc[k]) : 0.0f; - // lane k writes token k (every lane holds every sum after the xor reduction) -#pragma unroll - for (int k = 0; k < MAX_T; ++k) { - if (k >= T || lane != k) continue; - if (inject_block) { - m.a[k].inject_out[row] = s[k]; - } else { - const float x = s[k] / (float) HC; - m.a[k].lo[row] = x / (1.0f + __expf(-x)); - } - } -} - -// The tokens a down kernel may carry in one launch on the current card, and the plain read's tile: the plain read -// stages n_tok * TILEV floats (1280 on sm_75, 2560 elsewhere), staged two tiles of n_tok * H_TILE. The shared-memory -// opt-in is set here once per device (a per-DEVICE setting: a layer split runs these kernels on two cards). -int down_chunk(bool staged, int* tile_out) { - static bool attr[64] = {}; - static int chunk[64] = {}; // tokens the plain down kernel may carry in one launch on this card - static int chunk_staged[64] = {}; // the same for staged - static int tile[64] = {}; // the plain down kernel's TILEV on this card (1280 on sm_75, 2560 elsewhere) - int dev = 0; - cudaGetDevice(&dev); - if (dev < 0 || dev >= 64) { - *tile_out = 2560; - return kFusedGrMaxT; - } - if (!attr[dev]) { - int optin = 0; - cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev); - optin = strata::smem_optin_of(optin); // STRATA_EMULATE_CC (tests only) - // the down kernel stages n_tok*TILEV floats of dynamic shared memory - 80 KB at the full 8 tokens of the - // CUDA tile. sm_75 gets the smaller tile: all eight tokens fit one 40 KiB launch there (no more slicing), - // the TQ-5 prefetch holds half the registers, and the smaller blocks raise how many of the 41-block grid - // share an SM. Cards whose opt-in is still below that (or that report no opt-in at all) slice the tokens; - // the down kernel's outputs (lo, inject_out) are strictly per-token, so the chunk boundaries are safe, and - // the up kernel below still sees every token of the batch in one launch. -#if defined(__HIPCC__) -#if defined(STRATA_HIP_GFX906) - const bool small_tile = false; // gfx906: 64 KiB LDS, the 2560 tile as before (8 tokens slice into launches) -#else - const bool small_tile = true; // all eight tokens fit gfx1100's 64 KiB LDS at this tile -#endif -#else - int cc_maj = 0, cc_min = 0; - cudaDeviceGetAttribute(&cc_maj, cudaDevAttrComputeCapabilityMajor, dev); - cudaDeviceGetAttribute(&cc_min, cudaDevAttrComputeCapabilityMinor, dev); - const bool small_tile = strata::cc_major_of(cc_maj) * 10 + strata::cc_minor_of(cc_min) == 75; -#endif - const int tv = small_tile ? 1280 : 2560; - tile[dev] = tv; - int want = (int) (kFusedGrMaxT * tv * sizeof(float)); - if (optin > 0 && want > optin) want = optin; - if (small_tile) { - cudaFuncSetAttribute(gr_down_multi_kernel<1280>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); - } else { - cudaFuncSetAttribute(gr_down_multi_kernel<2560>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); - } - int want_staged = (int) (2 * kFusedGrMaxT * H_TILE * sizeof(float)); - if (optin > 0 && want_staged > optin) want_staged = optin; - cudaFuncSetAttribute(gr_down_staged_kernel<>, cudaFuncAttributeMaxDynamicSharedMemorySize, want_staged); - cudaGetLastError(); // drop any error the attempt left behind - // The opt-in is a promise a pre-Volta card does not keep: an sm_60 answers 65536 and accepts the - // cudaFuncSetAttribute for 61440 B, then fails the LAUNCH with "invalid argument". What such a card - // will launch is its per-block limit, so the capacity comes from that below sm_70 - the same tokens - // the "no opt-in" branch assumes, but taken from the attribute that is actually enforced. -#if defined(__HIPCC__) - const int usable = optin > 0 ? optin : 48 * 1024; -#else - int cc = 0, per_block = 0; - cudaDeviceGetAttribute(&cc, cudaDevAttrComputeCapabilityMajor, dev); - cudaDeviceGetAttribute(&per_block, cudaDevAttrMaxSharedMemoryPerBlock, dev); - cc = strata::cc_major_of(cc); - const int usable = (cc >= 7 && optin > 0) ? optin : per_block; -#endif - const int capacity = usable / (int) (tv * sizeof(float)); - chunk[dev] = capacity < 1 ? 1 : (capacity > kFusedGrMaxT ? kFusedGrMaxT : capacity); - const int capacity_staged = usable / (int) (2 * H_TILE * sizeof(float)); - chunk_staged[dev] = capacity_staged < 1 ? 1 : (capacity_staged > kFusedGrMaxT ? kFusedGrMaxT : capacity_staged); - attr[dev] = true; - } - *tile_out = tile[dev] ? tile[dev] : 2560; - return staged ? chunk_staged[dev] : chunk[dev]; -} - -// The multi read as `variant` (kHcPlain, kHcSplit or kHcStaged): the norm, the down projection in launches of as -// many tokens as fit the card, the up projection; the profile's stamps after the norm and after the down projection. -// kHcPlain is the default read exactly as before (never main's opt-in STRATA_GR_V3 path, which fused_gr_read_multi -// takes first). -#if defined(STRATA_HIP_GFX906) -__global__ void __launch_bounds__(THREADS) gr_norm_fast_kernel(GrMulti m); // below, with the AMD fast path -__global__ void __launch_bounds__(THREADS) gr_up_fast_kernel(GrMulti m); -} // namespace -static bool gr_fast(); -namespace { -#endif -void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long long* stamp_buf, int stamp_i0) { - const int n_tok = m.T; -#if defined(STRATA_HIP_GFX906) - // gfx906: the latency-hidden norm/up (STRATA_GR_FAST=0: off) - the same sums in the same order as the kernels - // they replace (gr_parity checks the multi-token read against single-token calls bitwise) - const bool fast = gr_fast(); - if (variant >= kHcSplit) gr_norm_split_kernel<<>>(m); - else if (fast) gr_norm_fast_kernel<<>>(m); - else gr_norm_multi_kernel<<>>(m); -#else - if (variant >= kHcSplit) gr_norm_split_kernel<<>>(m); - else gr_norm_multi_kernel<<>>(m); -#endif - if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, (void*) st); - const bool staged = variant >= kHcStaged; - int tv = 2560; - const int chunk_tok = down_chunk(staged, &tv); - const size_t per_tok = (staged ? (size_t) 2 * H_TILE : (size_t) tv) * sizeof(float); - for (int c0 = 0; c0 < n_tok; c0 += chunk_tok) { - const int ct = n_tok - c0 < chunk_tok ? n_tok - c0 : chunk_tok; - GrMulti c{}; - if (ct == n_tok) { - c = m; - } else { - c.xn = m.xn + (size_t) c0 * D; - c.T = ct; - for (int k = 0; k < ct; ++k) c.a[k] = m.a[c0 + k]; - } - const size_t smem = (size_t) ct * per_tok; - // #443, opt-in STRATA_GR_DOWN_MAX4=1: launches of up to 4 tokens hold 4 tokens' sums per thread instead of - // kFusedGrMaxT - the same tile, block size, accumulation order and plain/split/staged path, so the same bits - // (read once: this runs per layer when decode is not captured) - static const bool max4_on = [] { const char* v = std::getenv("STRATA_GR_DOWN_MAX4"); return v && std::atoi(v) != 0; }(); - const bool max4 = max4_on && ct <= 4; - if (staged) { - if (max4) gr_down_staged_kernel<4><<>>(c); - else gr_down_staged_kernel<><<>>(c); - } else if (tv == 1280) { - if (max4) gr_down_multi_kernel<1280, 4><<>>(c); - else gr_down_multi_kernel<1280><<>>(c); - } else { - if (max4) gr_down_multi_kernel<2560, 4><<>>(c); - else gr_down_multi_kernel<2560><<>>(c); - } - } - if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, (void*) st); -#if defined(STRATA_HIP_GFX906) - if (fast) gr_up_fast_kernel<<>>(m); - else -#endif - gr_up_multi_kernel<<>>(m); -} - -/// STRATA_HC_SPLIT: unset or 2 = the newest the check accepts (staged), 1 = at most split, 0 = the plain read -int env_variant() { - const char* e = std::getenv("STRATA_HC_SPLIT"); - if (e == nullptr || e[0] == '\0') return kHcStaged; - if (e[0] == '0') return kHcPlain; - if (e[0] == '1') return kHcSplit; - return kHcStaged; -} - -// per device: the variant `fused_gr_check` chose (0 = not checked yet) -std::atomic g_variant[64]; - - -#if defined(STRATA_HIP_GFX906) -// ---- AMD fast path (STRATA_GR_FAST, default 1; 0 = the old kernels): the same arithmetic per value in the same order, latency -// hidden. gr_norm: one block per token (as before) but a thread's 10 float4 of R / bo / w_norm are loaded -// before any is used, and xn stays in registers until rs is known (was: store, then re-read the 40 KB). -// gr_up: a warp's 8 rows of w_up and their epilogue inputs are loaded before the dots (was: one row's load chain -// after another). -constexpr int NQ = D / (THREADS * 4); // 10 float4 per thread -static_assert(D % (THREADS * 4) == 0, "whole float4 per thread"); -__global__ void __launch_bounds__(THREADS) gr_norm_fast_kernel(GrMulti m) { - __shared__ float part[WARPS][HC]; - __shared__ float s_rs[HC]; - const FusedGrArgs& a = m.a[blockIdx.x]; - float* xn = m.xn + (size_t) blockIdx.x * D; - const int t = threadIdx.x, lane = t & 31, warp = t >> 5; - float gw[HC]; -#pragma unroll - for (int c = 0; c < HC; ++c) gw[c] = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; - float4 r[NQ], g[NQ]; -#pragma unroll - for (int k = 0; k < NQ; ++k) { - const int i = t * 4 + k * THREADS * 4; - r[k] = *reinterpret_cast(a.R + i); - g[k] = *reinterpret_cast(a.w_norm + i); - } - if (a.apply) { -#pragma unroll - for (int k = 0; k < NQ; ++k) { - const int i = t * 4 + k * THREADS * 4, c = i / N, d = i - c * N; - const float4 b = *reinterpret_cast(a.bo_prev + d); - r[k].x = fmaf(b.x, gw[c], r[k].x); r[k].y = fmaf(b.y, gw[c], r[k].y); - r[k].z = fmaf(b.z, gw[c], r[k].z); r[k].w = fmaf(b.w, gw[c], r[k].w); - } - } - float ss[HC] = {0.0f, 0.0f, 0.0f, 0.0f}; -#pragma unroll - for (int k = 0; k < NQ; ++k) { - const int i = t * 4 + k * THREADS * 4, c = i / N; - const float sq = r[k].x * r[k].x + r[k].y * r[k].y + r[k].z * r[k].z + r[k].w * r[k].w; -#pragma unroll - for (int cc = 0; cc < HC; ++cc) if (cc == c) ss[cc] += sq; - r[k] = make_float4(r[k].x * g[k].x, r[k].y * g[k].y, r[k].z * g[k].z, r[k].w * g[k].w); - } -#pragma unroll - for (int c = 0; c < HC; ++c) { - const float v = warp_sum(ss[c]); - if (lane == 0) part[warp][c] = v; - } - __syncthreads(); - if (t < HC) { - float s = 0.0f; - for (int w = 0; w < WARPS; ++w) s += part[w][t]; - s_rs[t] = rsqrtf(s / (float) N + a.eps); - a.rs[t] = s_rs[t]; - } - __syncthreads(); -#pragma unroll - for (int k = 0; k < NQ; ++k) { - const int i = t * 4 + k * THREADS * 4; - const float sr = s_rs[i / N]; - *reinterpret_cast(xn + i) = make_float4(r[k].x * sr, r[k].y * sr, r[k].z * sr, r[k].w * sr); - } -} -// gr_up: 8 lanes per row instead of a 32-lane warp. Lane j holds the old lanes j, j+8, j+16, j+24 (and chunk -// 32+j, the old lane j's second chunk): the xor tree's stages 16 and 8 are its own adds (a + b == b + a), stages -// 4, 2, 1 are shuffles inside the 8 - the same tree, bitwise the same sum, 3 shuffles a token instead of 5 and no -// idle lanes on the tail chunks. A block's 64 rows are 2 passes of 32 groups, their weights loaded up front. -__device__ __forceinline__ float xor8(float v) { -#pragma unroll - for (int o = 4; o > 0; o >>= 1) v += __shfl_xor(v, o, 64); - return v; -} -__global__ void __launch_bounds__(THREADS) gr_up_fast_kernel(GrMulti m) { - __shared__ __align__(16) float lo[kFusedGrMaxT][LR]; - __shared__ float g[kFusedGrMaxT][HC][UPM_COLS]; - const int t = threadIdx.x, j = t & 7, grp = t >> 3; - const int T = m.T; - const int d0 = blockIdx.x * UPM_COLS; - static_assert(LR == 40 * 8 && HC * UPM_COLS == 64 && THREADS == 256, "geometry"); - uint4 w[2][5]; - float rv[2] = {0.0f, 0.0f}, wn[2] = {0.0f, 0.0f}, rsc[2] = {0.0f, 0.0f}, bo[2] = {0.0f, 0.0f}, ip[2] = {0.0f, 0.0f}; - const bool apply = j < T && m.a[j < T ? j : 0].apply; -#pragma unroll - for (int p = 0; p < 2; ++p) { - const int r = grp + 32 * p, c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; - const uint4* w4 = reinterpret_cast(m.a[0].w_up + (size_t) i * LR); -#pragma unroll - for (int q = 0; q < 4; ++q) w[p][q] = __ldg(w4 + j + 8 * q); - w[p][4] = __ldg(w4 + 32 + j); - if (j < T) { - const FusedGrArgs& a = m.a[j]; - rv[p] = a.R[i]; - wn[p] = a.w_norm[i]; - rsc[p] = a.rs[c]; - if (apply) { bo[p] = a.bo_prev[d0 + dd]; ip[p] = a.inj_prev[c]; } - } - } - for (int i = t; i < T * LR; i += THREADS) lo[i / LR][i % LR] = m.a[i / LR].lo[i % LR]; - __syncthreads(); -#pragma unroll - for (int p = 0; p < 2; ++p) { - const int r = grp + 32 * p, c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; - float mine = 0.0f; -#pragma unroll - for (int k = 0; k < kFusedGrMaxT; ++k) { - if (k >= T) break; - const float* l = lo[k]; - const float p0 = dot8(w[p][0], l + j * 8) + dot8(w[p][4], l + (32 + j) * 8); // old lane j - const float p1 = dot8(w[p][1], l + (j + 8) * 8); // old lane j + 8 - const float p2 = dot8(w[p][2], l + (j + 16) * 8); // old lane j + 16 - const float p3 = dot8(w[p][3], l + (j + 24) * 8); // old lane j + 24 - const float s = xor8((p0 + p2) + (p1 + p3)); // stage 16: (j, j+16), (j+8, j+24); stage 8; then 4, 2, 1 - if (j == k) mine = s; - } - if (j < T) { - float x0 = rv[p]; - if (apply) { - x0 = fmaf(bo[p], 2.0f * sigmoidf_(ip[p] / (float) HC), x0); - m.a[j].R_out[i] = x0; - } - const float x = x0 * wn[p] * rsc[p]; - g[j][c][dd] = x * sigmoidf_(mine); - } - } - __syncthreads(); - for (int i = t; i < T * UPM_COLS; i += THREADS) { - const int k = i / UPM_COLS, col = i - k * UPM_COLS; - float s = 0.0f; -#pragma unroll - for (int c = 0; c < HC; ++c) s += g[k][c][col]; - m.a[k].mixed[d0 + col] = s / (float) HC; - } -} -#endif - -#if defined(STRATA_HIP_GFX906) -// ---- AMD: `gr_down_multi` split along K. The CUDA kernel is one warp per row of w_down (320 + 4 rows), 41 -// blocks: on a 60-CU gfx906 that left most of the card idle and read the 6.5 MB matrix at ~100 GB/s. Here a block -// is 8 wavefronts = 8 rows of one K-slice of 2048 (the slice of every token's xn staged in LDS once), 41 x 5 -// blocks, and a second kernel adds the 5 slice sums in a fixed order and runs the epilogue. A token's result does -// not depend on how many tokens share the window (each column is reduced on its own). -constexpr int GS_SL = 2048; // K per slice -constexpr int GS_S = D / GS_SL; // 5 slices -constexpr int GS_ROWS = LR + HC; // 324: the down rows, then the inject rows -constexpr int GS_WAVES = 8; -static_assert(D % GS_SL == 0 && GS_SL == 64 * 8 * 4, "a lane takes 4 chunks of 8 per slice"); -// the slice sums: a module-scope device array is per device by construction, and needs no allocation during a -// graph capture -__device__ float g_gr_part[GS_S * kFusedGrMaxT * GS_ROWS]; -__global__ void __launch_bounds__(GS_WAVES * 64) gr_down_split_kernel(GrMulti m) { - float* part = g_gr_part; - extern __shared__ __align__(16) float tile[]; // [T][GS_SL] - const int t = threadIdx.x, lane = t & 63, wave = t >> 6; - const int T = m.T, sl = blockIdx.y; - const bool inject_block = blockIdx.x == DOWN_BLOCKS; - const int row = inject_block ? wave : blockIdx.x * GS_WAVES + wave; - const bool active = !(inject_block && (m.a[0].w_inject == nullptr || wave >= HC)); - const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D; - const uint4* w4 = reinterpret_cast(wrow) + sl * (GS_SL / 8); - uint4 wv[4]; - if (active) { -#pragma unroll - for (int q = 0; q < 4; ++q) wv[q] = __ldg(w4 + lane + 64 * q); - } - const float4* src4 = reinterpret_cast(m.xn); - float4* tile4 = reinterpret_cast(tile); - for (int i = t; i < T * (GS_SL / 4); i += GS_WAVES * 64) { - const int k = i / (GS_SL / 4), off = i - k * (GS_SL / 4); - tile4[i] = src4[((size_t) k * D + (size_t) sl * GS_SL) / 4 + off]; - } - __syncthreads(); - if (!active) return; - float acc[kFusedGrMaxT]; -#pragma unroll - for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f; -#pragma unroll - for (int q = 0; q < 4; ++q) { - const int j = lane + 64 * q; -#pragma unroll - for (int k = 0; k < kFusedGrMaxT; ++k) - if (k < T) acc[k] += dot8(wv[q], tile + k * GS_SL + j * 8); - } -#pragma unroll - for (int k = 0; k < kFusedGrMaxT; ++k) { - if (k >= T) break; - float v = acc[k]; -#pragma unroll - for (int off = 32; off > 0; off >>= 1) v += __shfl_xor(v, off, 64); - if (lane == 0) part[((size_t) sl * kFusedGrMaxT + k) * GS_ROWS + (inject_block ? LR + row : row)] = v; - } -} -__global__ void gr_down_finish_kernel(GrMulti m) { - const float* part = g_gr_part; - const int i = blockIdx.x * blockDim.x + threadIdx.x; - const int k = i / GS_ROWS, r = i - k * GS_ROWS; - if (k >= m.T) return; - const bool inject = r >= LR; - if (inject && m.a[0].w_inject == nullptr) return; - float s = 0.0f; -#pragma unroll - for (int sl = 0; sl < GS_S; ++sl) s += part[((size_t) sl * kFusedGrMaxT + k) * GS_ROWS + r]; - if (inject) { - m.a[k].inject_out[r - LR] = s; - } else { - const float x = s / (float) HC; - m.a[k].lo[r] = x / (1.0f + __expf(-x)); - } -} - -#endif - -} // namespace - -#if defined(STRATA_HIP_GFX906) -int g_gr_fast = -1; // fused_gr_set_fast (the bench); -1 = STRATA_GR_FAST -static bool gr_fast() { - static const bool env = [] { const char* v = std::getenv("STRATA_GR_FAST"); return v ? std::atoi(v) != 0 : true; }(); - return g_gr_fast >= 0 ? g_gr_fast != 0 : env; -} -#else -int g_gr_fast = -1; -#endif -void fused_gr_set_fast(int on) { g_gr_fast = on; } - -void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf, - int stamp_i0) { - if (n_tok < 1 || n_tok > kFusedGrMaxT || xn_scratch == nullptr) { - std::fprintf(stderr, "fused_gr_read_multi: invalid arguments\n"); - std::exit(1); - } - GrMulti m; - for (int t = 0; t < n_tok; ++t) { - m.a[t] = a[t]; - const FusedGrArgs& x = a[t]; - if (!x.R || !x.w_norm || !x.w_down || !x.w_up || !x.lo || !x.rs || !x.mixed || (x.w_inject && !x.inject_out) || - (x.apply && (!x.bo_prev || !x.inj_prev || !x.R_out)) || x.w_down != a[0].w_down || x.w_up != a[0].w_up || - x.w_inject != a[0].w_inject || x.w_norm != a[0].w_norm) { - std::fprintf(stderr, "fused_gr_read_multi: invalid arguments for token %d\n", t); - std::exit(1); - } - } - m.xn = xn_scratch; - m.T = n_tok; - cudaStream_t st = (cudaStream_t) stream; - // STRATA_GR_V3=1: the two-kernel read above (another summation order - opt-in) - static const bool v3 = [] { const char* v = std::getenv("STRATA_GR_V3"); return v != nullptr && std::atoi(v) != 0; }(); - static int split3[64] = {}; // per device: 0 = not decided yet, 1 / 2 = column halves S, -1 = does not fit - int dev3 = 0; - if (v3) { - cudaGetDevice(&dev3); - if (dev3 >= 0 && dev3 < 64 && split3[dev3] == 0) { - int optin = 0; - cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev3); - const int limit = optin > 0 ? optin : 48 * 1024; - const int need1 = (int) (kFusedGrMaxT * N * sizeof(float)), need6 = (int) (6 * N * sizeof(float)), need2 = need1 / 2; - int split = -1; - if (need1 <= limit && - cudaFuncSetAttribute(gr_down_v3_kernel<1, kFusedGrMaxT, false>, cudaFuncAttributeMaxDynamicSharedMemorySize, need1) == cudaSuccess && - cudaFuncSetAttribute(gr_down_v3_kernel<1, 6, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, need6) == cudaSuccess) { - cudaFuncSetAttribute(gr_down_v3_kernel<1, 4, true>, cudaFuncAttributePreferredSharedMemoryCarveout, 100); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 4, false>, cudaFuncAttributePreferredSharedMemoryCarveout, 100); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 2, true>, cudaFuncAttributePreferredSharedMemoryCarveout, 100); - split = 1; - } else if (need2 <= limit) - // #375 (kenh0u): the S = 2 split (a 64 KB opt-in card: Turing) disagrees with itself in gr_parity - // (graph replay vs direct call) - such a card keeps the default read until that split is fixed - std::fprintf(stderr, "strata: STRATA_GR_V3=1 needs the two-half split on this card, which fails its " - "checks (#375): the default read is used\n"); - cudaGetLastError(); // drop any error the attempts left behind - split3[dev3] = split; - } - } - const int split = v3 && dev3 >= 0 && dev3 < 64 ? split3[dev3] : -1; - if (split > 0) { // 2 kernels; scratch = partials + sums of squares - float* part = xn_scratch; - float* ssg = xn_scratch + (size_t) n_tok * HC * 2 * PR; // room for S = 2 - const size_t sm = (size_t) n_tok * (N / split) * sizeof(float); - if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, stream); - if (split == 2) gr_down_v3_kernel<2><<>>(m, part, ssg); - else if (n_tok == 2) gr_down_v3_kernel<1, 2, true><<>>(m, part, ssg); - else if (n_tok == 4) gr_down_v3_kernel<1, 4, true><<>>(m, part, ssg); - else if (n_tok == 6) gr_down_v3_kernel<1, 6, true><<>>(m, part, ssg); - else if (n_tok < 4) gr_down_v3_kernel<1, 4, false><<>>(m, part, ssg); - else gr_down_v3_kernel<1, kFusedGrMaxT, false><<>>(m, part, ssg); - if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, stream); - if (split == 2) gr_up_v3_kernel<2><<>>(m, part, ssg); - else if (n_tok == 2) gr_up_v3_kernel<1, 2, true><<>>(m, part, ssg); - else if (n_tok == 4) gr_up_v3_kernel<1, 4, true><<>>(m, part, ssg); - else if (n_tok == 6) gr_up_v3_kernel<1, 6, true><<>>(m, part, ssg); - else if (n_tok < 4) gr_up_v3_kernel<1, 4, false><<>>(m, part, ssg); - else gr_up_v3_kernel<1, kFusedGrMaxT, false><<>>(m, part, ssg); - const cudaError_t e3 = cudaGetLastError(); - if (e3 != cudaSuccess) { - std::fprintf(stderr, "fused_gr_read_multi v3: %s\n", cudaGetErrorString(e3)); - std::exit(1); - } - return; - } -#if defined(STRATA_HIP_GFX906) - // gfx906, opt-in STRATA_GR_SPLIT=1: the latency-hidden norm/up (STRATA_GR_FAST) with the K-split down (~3% faster - // per verify window). Its fixed-order finish sums the K slices in another order than the single-token - // fused_gr_read, so the multi-token read is then no longer bitwise equal to T single-token calls (gr_parity's - // contract); off by default for that reason. - static const bool split_on = std::getenv("STRATA_GR_SPLIT") && std::string(std::getenv("STRATA_GR_SPLIT")) == "1"; - if (split_on) { - const bool fast = gr_fast(); - if (fast) gr_norm_fast_kernel<<>>(m); - else gr_norm_multi_kernel<<>>(m); - if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, stream); - gr_down_split_kernel<<>>( - m); - gr_down_finish_kernel<<<(unsigned) ((n_tok * GS_ROWS + 255) / 256), 256, 0, st>>>(m); - if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, stream); - if (fast) gr_up_fast_kernel<<>>(m); - else gr_up_multi_kernel<<>>(m); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "fused_gr_read_multi: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - return; - } -#endif - // the default read (STRATA_GR_V3 unset): v1, or the bitwise-equal v2 / v3 this card's check accepted - launch_multi(m, fused_gr_variant(), st, stamp_buf, stamp_i0); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "fused_gr_read_multi: %s\n", cudaGetErrorString(e)); - std::exit(1); - } -} - -bool fused_gr_supported(int64_t n_embd, int64_t hc, int64_t hc_lr) { - return n_embd == N && hc == HC && hc_lr == LR; -} - -void fused_gr_read(const FusedGrArgs& a, void* stream) { - if (!a.R || !a.w_norm || !a.w_down || !a.w_up || !a.lo || !a.rs || !a.mixed || - (a.w_inject && !a.inject_out) || (a.apply && (!a.bo_prev || !a.inj_prev || !a.R_out)) || - (a.apply && a.inj_prev == a.inject_out)) { - std::fprintf(stderr, "fused_gr_read: invalid arguments\n"); - std::exit(1); - } - cudaStream_t st = (cudaStream_t) stream; - gr_down_kernel<<>>(a); - gr_up_kernel<<>>(a); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "fused_gr_read: %s\n", cudaGetErrorString(e)); - std::exit(1); - } -} - - -namespace { - -/// The plain read, split, staged and (for one token) the single-token read on random bf16 weights and random inputs, -/// 1..8 tokens, with and without the pending write; every output of split and staged compared with the plain read's -/// bit for bit (and the plain read's with the single-token read's). `why[v]` gets the first difference of variant -/// v; false if the check itself could not run. -bool fused_gr_selftest(bool ok_variant[4], std::string why[4]) { - constexpr int TM = kFusedGrMaxT; - constexpr int NV = 4; // sets: 0 = plain, 1 = split, 2 = staged, 3 = single-token - std::mt19937 rng(20260930u); - std::normal_distribution nd(0.0f, 1.0f); - std::vector h_down((size_t) LR * D), h_up((size_t) D * LR), h_inj((size_t) HC * D); - std::vector h_norm(D), h_R((size_t) TM * D), h_bo((size_t) TM * N), h_ip((size_t) TM * HC); - for (auto& w : h_down) w = bf16_from_f32(0.02f * nd(rng)); - for (auto& w : h_up) w = bf16_from_f32(0.05f * nd(rng)); - for (auto& w : h_inj) w = bf16_from_f32(0.02f * nd(rng)); - for (auto& w : h_norm) w = 1.0f + 0.1f * nd(rng); - for (auto& x : h_R) x = nd(rng); - for (auto& x : h_bo) x = 0.5f * nd(rng); - for (auto& x : h_ip) x = 2.0f * nd(rng); - for (int v = 0; v < 4; ++v) { ok_variant[v] = v == 1; why[v].clear(); } - - const size_t n_set = (size_t) TM * (D + D + LR + HC + HC + N); // R_out, xn, lo, rs, inject, mixed (floats) - const size_t bytes = h_down.size() * 2 + h_up.size() * 2 + h_inj.size() * 2 + - (h_norm.size() + h_R.size() + h_bo.size() + h_ip.size() + NV * n_set) * 4 + 32 * 256; - uint8_t* base = nullptr; - if (cudaMalloc((void**) &base, bytes) != cudaSuccess) { - cudaGetLastError(); - why[0] = "no room for the check (" + std::to_string(bytes >> 20) + " MiB)"; - return false; - } - size_t off = 0; - auto take = [&](size_t b) { void* p = base + off; off += (b + 255) / 256 * 256; return p; }; - uint16_t* d_down = (uint16_t*) take(h_down.size() * 2); - uint16_t* d_up = (uint16_t*) take(h_up.size() * 2); - uint16_t* d_inj = (uint16_t*) take(h_inj.size() * 2); - float* d_norm = (float*) take(h_norm.size() * 4); - float* d_R = (float*) take(h_R.size() * 4); - float* d_bo = (float*) take(h_bo.size() * 4); - float* d_ip = (float*) take(h_ip.size() * 4); - struct Set { float *R_out, *xn, *lo, *rs, *inj, *mixed; } set[NV]; - for (Set& x : set) { - x.R_out = (float*) take((size_t) TM * D * 4); x.xn = (float*) take((size_t) TM * D * 4); - x.lo = (float*) take((size_t) TM * LR * 4); x.rs = (float*) take((size_t) TM * HC * 4); - x.inj = (float*) take((size_t) TM * HC * 4); x.mixed = (float*) take((size_t) TM * N * 4); - } - cudaStream_t st = nullptr; - bool ok = off <= bytes && cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking) == cudaSuccess && - cudaMemcpyAsync(d_down, h_down.data(), h_down.size() * 2, cudaMemcpyHostToDevice, st) == cudaSuccess && - cudaMemcpyAsync(d_up, h_up.data(), h_up.size() * 2, cudaMemcpyHostToDevice, st) == cudaSuccess && - cudaMemcpyAsync(d_inj, h_inj.data(), h_inj.size() * 2, cudaMemcpyHostToDevice, st) == cudaSuccess && - cudaMemcpyAsync(d_norm, h_norm.data(), h_norm.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess && - cudaMemcpyAsync(d_R, h_R.data(), h_R.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess && - cudaMemcpyAsync(d_bo, h_bo.data(), h_bo.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess && - cudaMemcpyAsync(d_ip, h_ip.data(), h_ip.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess; - if (!ok) why[0] = "setting up the check failed"; - std::vector h1, h2; - // true when equal; false with the first difference in `w` (or a read-back failure in `ok`) - auto same = [&](const float* d1, const float* d2, size_t n, const char* what, int T, int apply, std::string& w) { - h1.resize(n); - h2.resize(n); - if (cudaMemcpyAsync(h1.data(), d1, n * 4, cudaMemcpyDeviceToHost, st) != cudaSuccess || - cudaMemcpyAsync(h2.data(), d2, n * 4, cudaMemcpyDeviceToHost, st) != cudaSuccess || - cudaStreamSynchronize(st) != cudaSuccess) { - why[0] = "reading back the check failed"; - ok = false; - return false; - } - for (size_t i = 0; i < n; ++i) { - uint32_t u1, u2; - std::memcpy(&u1, &h1[i], 4); - std::memcpy(&u2, &h2[i], 4); - if (u1 != u2) { - char buf[192]; - std::snprintf(buf, sizeof buf, "%s differs for %d token(s)%s at %zu (%08x, not %08x)", what, T, - apply ? " with the pending write" : "", i, u2, u1); - w = buf; - return false; - } - } - return true; - }; - auto all_same = [&](const Set& s1, const Set& s2, int T, int apply, std::string& w) { - return same(s1.lo, s2.lo, (size_t) T * LR, "lo", T, apply, w) && - same(s1.rs, s2.rs, (size_t) T * HC, "rs", T, apply, w) && - same(s1.inj, s2.inj, (size_t) T * HC, "inject", T, apply, w) && - same(s1.mixed, s2.mixed, (size_t) T * N, "mixed", T, apply, w) && - same(s1.R_out, s2.R_out, (size_t) T * D, "R", T, apply, w); - }; - ok_variant[2] = ok_variant[3] = ok; - bool single_ok = ok; - for (int apply = 0; apply < 2 && ok; ++apply) { - for (int T = 1; T <= TM && ok; ++T) { - FusedGrArgs a[NV][TM]; - for (int v = 0; v < NV; ++v) { - const size_t span = (size_t) ((uint8_t*) (set[v].mixed + (size_t) TM * N) - (uint8_t*) set[v].R_out); - ok = ok && cudaMemsetAsync(set[v].R_out, 0xFF, span, st) == cudaSuccess; // the whole set - for (int k = 0; k < T; ++k) { - FusedGrArgs& x = a[v][k]; - x.R = d_R + (size_t) k * D; x.R_out = set[v].R_out + (size_t) k * D; x.apply = apply != 0; - x.bo_prev = d_bo + (size_t) k * N; x.inj_prev = d_ip + (size_t) k * HC; - x.w_norm = d_norm; x.w_down = d_down; x.w_up = d_up; x.w_inject = d_inj; x.eps = 1e-6f; - x.lo = set[v].lo + (size_t) k * LR; x.rs = set[v].rs + (size_t) k * HC; - x.inject_out = set[v].inj + (size_t) k * HC; x.mixed = set[v].mixed + (size_t) k * N; - } - } - for (int v = 0; v < 3; ++v) { - GrMulti m; - for (int k = 0; k < T; ++k) m.a[k] = a[v][k]; - m.xn = set[v].xn; - m.T = T; - launch_multi(m, v + 1, st, nullptr, 0); - } - if (T == 1) fused_gr_read(a[3][0], st); - if (cudaGetLastError() != cudaSuccess || cudaStreamSynchronize(st) != cudaSuccess) { - why[0] = "a kernel of the check failed"; - ok = false; - break; - } - if (ok_variant[2] && !all_same(set[0], set[1], T, apply, why[2])) ok_variant[2] = false; - if (ok && ok_variant[3] && !all_same(set[0], set[2], T, apply, why[3])) ok_variant[3] = false; - if (ok && T == 1 && single_ok && !all_same(set[3], set[0], T, apply, why[1])) single_ok = false; - } - } - if (!single_ok && ok) { // the plain read itself disagrees with the single-token read - why[2] = why[3] = "the plain read differs from the single-token read: " + why[1]; - ok_variant[2] = ok_variant[3] = false; - } - if (st != nullptr) { - cudaStreamSynchronize(st); - cudaStreamDestroy(st); - } - cudaFree(base); - cudaGetLastError(); - if (!ok) ok_variant[2] = ok_variant[3] = false; - return ok; -} - -} // namespace - -int fused_gr_variant() { - int dev = 0; - cudaGetDevice(&dev); - const int v = dev >= 0 && dev < 64 ? g_variant[dev].load() : 0; - if (v > 0) return v; - // not checked on this card: the plain read, unless STRATA_HC_SPLIT names a variant (a test such as gr_parity) - const char* e = std::getenv("STRATA_HC_SPLIT"); - return e != nullptr && (e[0] == '1' || e[0] == '2') ? env_variant() : kHcPlain; -} - -void fused_gr_check() { - int dev = 0; - cudaGetDevice(&dev); - if (dev < 0 || dev >= 64 || g_variant[dev].load() > 0) return; - const int want = env_variant(); - if (want == kHcPlain) { - g_variant[dev].store(kHcPlain); - std::fprintf(stderr, "strata hc: CUDA%d: the hyper-connection read runs as the plain one (STRATA_HC_SPLIT=0)\n", - dev); - return; - } - bool okv[4]; - std::string why[4]; - const bool ran = fused_gr_selftest(okv, why); - int use = kHcPlain; - if (want >= kHcStaged && okv[kHcStaged]) use = kHcStaged; - else if (okv[kHcSplit]) use = kHcSplit; - g_variant[dev].store(use); - if (!ran) - std::fprintf(stderr, "strata hc: CUDA%d: the check of split/staged could not run (%s)\n", dev, why[0].c_str()); - static const char* const name[4] = {"", "plain", "split", "staged"}; - for (int v = kHcStaged; v >= kHcSplit; --v) - if (v <= want && !okv[v] && ran) - std::fprintf(stderr, "strata hc: CUDA%d: the %s read differs from the plain read on this card - not used: " - "%s\n", dev, name[v], why[v].c_str()); - static const char* const what[4] = { - "", "the plain read (the norm per token, the down projection on 41 blocks)", - "split (the norm per token and stream, then the plain read's down projection)", - "staged (the norm per token and stream, the down projection's activations staged ahead by cp.async)"}; - std::fprintf(stderr, "strata hc: CUDA%d: the hyper-connection read runs as %s%s\n", dev, what[use], - use >= kHcSplit ? "; checked bit for bit against the plain read on this card (STRATA_HC_SPLIT=1 or 0 " - "for the earlier ones)" : ""); -} - - -} // namespace strata::kernels diff --git a/src/kernels/cuda/gdn.cu b/src/kernels/cuda/gdn.cu deleted file mode 100644 index 15b9f25..0000000 --- a/src/kernels/cuda/gdn.cu +++ /dev/null @@ -1,253 +0,0 @@ -// src/kernels/cuda/gdn.cu - P2.S2: the gated delta-net's non-projection parts. -// -// See include/strata/kernels/gdn.hpp for the state layout (S, h_v, S) and for why the recurrence needs no -// barrier at all: every line of it touches only one (j, h) column, so one thread owns a column end to end. -#include "strata/kernels/gdn.hpp" - -#include - -#include -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int JTHREADS = 32; ///< threads along j, the state's fast axis -/// Heads staged per block. **THIS IS A LATENCY-HIDING KNOB, NOT A CAPACITY ONE, AND IT WAS SET WRONG.** -/// -/// The kernel is one thread per `(h, j)` COLUMN of the state, so the thread count is fixed at -/// `S * h_v` = 128 * 48 = **6,144** no matter how the work is packed - and `MAX_H` decides only how many of -/// those columns share a block: -/// -/// MAX_H = 8 grid = (S/32, h_v/8) = (4, 6) = 24 blocks x 32 threads -> 1 warp on 24 of 48 SMs -/// MAX_H = 1 grid = (S/32, h_v/1) = (4, 48) = 192 blocks x 32 threads -> 4 warps on every SM -/// -/// Each thread walks `i` in 0..S-1 TWICE per head with a strided global load each step, so it is entirely -/// latency-bound: a warp that issues one 128-byte transaction and then waits ~600 cycles needs other warps to -/// run meanwhile, and at 24 blocks there were none. Measured 0.2800 ms per GDN block - 10 ms of a 71.5 ms -/// token, 14%, in a kernel touching 12.6 MB that a 643 GB/s card should do in 0.020 ms. -/// -/// The arithmetic does not change at all: the same columns are computed by the same code, in different blocks. -constexpr int MAX_H = 1; ///< heads staged in shared memory per block - -/// ggml_compute_softplus_f32: log1p(exp(x)), with the large-x branch that avoids overflow. -__device__ __forceinline__ float softplus_f(float x) { return x > 20.0f ? x : log1pf(expf(x)); } -__device__ __forceinline__ float sigmoid_f(float x) { return 1.0f / (1.0f + expf(-x)); } - -/// One step of the recurrence. One thread per (h, j) column of the state. -/// -/// `ks`/`qs` stage `k[idx[h]]` and `q[idx[h]]` for the block's heads. Within a warp h is constant and j -/// varies, so the staged row is read with a single broadcast - which is also why the GLOBAL loads of -/// `q`/`k` are done once per block into shared instead of once per thread. -__global__ void gdn_step_kernel(float* __restrict__ state, const float* __restrict__ q, - const float* __restrict__ k, const float* __restrict__ v, - const float* __restrict__ gate, const float* __restrict__ beta, - float* __restrict__ o, int S, int h_k, int h_v) { - __shared__ float ks[MAX_H][128]; - __shared__ float qs[MAX_H][128]; - __shared__ float dec_s[MAX_H]; - __shared__ float beta_s[MAX_H]; - - const int h0 = blockIdx.y * MAX_H; - const int nh = min(MAX_H, h_v - h0); - const int j = blockIdx.x * JTHREADS + threadIdx.x; - - // stage this block's q/k rows and its per-head scalars - for (int hi = 0; hi < nh; ++hi) { - const int h = h0 + hi; - const int src = h % h_k; // MODULO head pairing - for (int i = threadIdx.x; i < S; i += JTHREADS) { - ks[hi][i] = k[src * S + i]; - qs[hi][i] = q[src * S + i]; - } - if (threadIdx.x == 0) { - dec_s[hi] = expf(gate[h]); - beta_s[hi] = beta[h]; - } - } - __syncthreads(); - if (j >= S) return; - - for (int hi = 0; hi < nh; ++hi) { - const int h = h0 + hi; - const float dec = dec_s[hi], b = beta_s[hi]; - float* col = state + (size_t) h * S + j; // (S, h_v, S) with j fastest - const size_t stride = (size_t) h_v * S; - - // pass 1: decay the state and contract it against k. Decay BEFORE the update - PROPERTY 5. - float sk = 0.0f; - for (int i = 0; i < S; ++i) { - const float s = col[(size_t) i * stride] * dec; - col[(size_t) i * stride] = s; - sk += s * ks[hi][i]; - } - const float d = (v[(size_t) h * S + j] - sk) * b; - // pass 2: the rank-1 update, then read out against q using the UPDATED state - float dot = 0.0f; - for (int i = 0; i < S; ++i) { - const float s = col[(size_t) i * stride] + ks[hi][i] * d; - col[(size_t) i * stride] = s; - dot += s * qs[hi][i]; - } - o[(size_t) h * S + j] = dot; - } -} - -/// `ggml_ssm_conv`: out[c] = sum_i inp[i][c] * kW[c*d_conv + i], inp = [conv_state | x], and the state slides. -/// One thread per channel; d_conv is 4, so the serial work per thread is a 4-tap dot and an unrolled shift. -__global__ void gdn_conv_kernel(float* __restrict__ cs, const float* __restrict__ x, - const float* __restrict__ kW, float* __restrict__ out, int C, int dc) { - const int c = blockIdx.x * blockDim.x + threadIdx.x; - if (c >= C) return; - float* st = cs + (size_t) c * (dc - 1); - const float* w = kW + (size_t) c * dc; - float acc = 0.0f; - for (int i = 0; i < dc - 1; ++i) acc += st[i] * w[i]; // kernel[0] reads the OLDEST state row - acc += x[c] * w[dc - 1]; // the new input lands in the LAST tap - out[c] = acc; - for (int i = 0; i < dc - 2; ++i) st[i] = st[i + 1]; // slide: drop the oldest, append the newest - st[dc - 2] = x[c]; -} - -/// `build_gdn_l2_norm`, one warp per row: x / sqrt(sum(x^2) + eps) over the last axis. -/// -/// The sum is accumulated in DOUBLE, as `ref/gdn.py` does (`l2_norm(q.astype(np.float64), eps)`), because the -/// reference deliberately computes this one in float64 and then casts - so matching its precision is part of -/// transcribing it. -__global__ void gdn_l2_kernel(float* __restrict__ x, int cols, float eps) { - const int row = blockIdx.x; - float* p = x + (size_t) row * cols; - double acc = 0.0; - for (int i = threadIdx.x; i < cols; i += blockDim.x) acc += (double) p[i] * (double) p[i]; - // warp reduction - for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, off); - __shared__ double ssum; - if (threadIdx.x == 0) ssum = acc; - __syncthreads(); - const float inv = (float) (1.0 / sqrt(ssum + (double) eps)); - for (int i = threadIdx.x; i < cols; i += blockDim.x) p[i] *= inv; -} - -/// y = rms_norm(o, eps) * ssm_norm * act(z), one warp per head, norm over that head's S values. `silu` 0 is -/// sigmoid(z) (Flash-Next), 1 is SiLU(z) = z * sigmoid(z) (Qwen3.6, ggml's `op_silu`: x / (1 + exp(-x))). -__global__ void gdn_out_norm_kernel(const float* __restrict__ o, const float* __restrict__ z, - const float* __restrict__ ssm_norm, float* __restrict__ y, int S, - float eps, int silu) { - const int h = blockIdx.x; - const float* po = o + (size_t) h * S; - const float* pz = z + (size_t) h * S; - float* py = y + (size_t) h * S; - double acc = 0.0; - for (int i = threadIdx.x; i < S; i += blockDim.x) acc += (double) po[i] * (double) po[i]; - for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, off); - __shared__ double ssum; - if (threadIdx.x == 0) ssum = acc; - __syncthreads(); - const float inv = (float) (1.0 / sqrt(ssum / (double) S + (double) eps)); - for (int i = threadIdx.x; i < S; i += blockDim.x) { - const float zz = pz[i]; - const float act = silu ? zz / (1.0f + expf(-zz)) : sigmoid_f(zz); - py[i] = po[i] * inv * ssm_norm[i] * act; - } -} - -} // namespace - -void gdn_step(float* state, const float* q, const float* k, const float* v, const float* gate, - const float* beta, float* o, const GdnShapes& s, void* stream) { - if (s.S <= 0 || s.h_k <= 0 || s.h_v <= 0) return; - if (s.S > 128) { - std::fprintf(stderr, "gdn_step: S = %lld exceeds the staged 128 (`ks`/`qs` are [8][128])\n", - (long long) s.S); - std::exit(1); - } - const dim3 grid((unsigned) ((s.S + JTHREADS - 1) / JTHREADS), - (unsigned) ((s.h_v + MAX_H - 1) / MAX_H)); - gdn_step_kernel<<>>(state, q, k, v, gate, beta, o, (int) s.S, - (int) s.h_k, (int) s.h_v); - if (stream == nullptr) { - const cudaError_t e = cudaDeviceSynchronize(); - if (e != cudaSuccess) { - std::fprintf(stderr, "gdn_step: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - } -} - -void gdn_conv_step(float* conv_state, const float* x, const float* kW, float* out, int64_t channels, - int64_t d_conv, void* stream) { - if (channels <= 0 || d_conv < 1) return; - const int blocks = (int) ((channels + 255) / 256); - gdn_conv_kernel<<>>(conv_state, x, kW, out, (int) channels, - (int) d_conv); - if (stream == nullptr) { - const cudaError_t e = cudaDeviceSynchronize(); - if (e != cudaSuccess) { - std::fprintf(stderr, "gdn_conv_step: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - } -} - -void gdn_l2_norm(float* x, int64_t rows, int64_t cols, float eps, void* stream) { - if (rows <= 0 || cols <= 0) return; - if (cols > 1024) { - std::fprintf(stderr, "gdn_l2_norm: cols = %lld exceeds the 1024-wide warp reduction\n", (long long) cols); - std::exit(1); - } - gdn_l2_kernel<<<(unsigned) rows, 32, 0, (cudaStream_t) stream>>>(x, (int) cols, eps); - if (stream == nullptr) { - const cudaError_t e = cudaDeviceSynchronize(); - if (e != cudaSuccess) { - std::fprintf(stderr, "gdn_l2_norm: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - } -} - -/// `beta = sigmoid(beta)`, in place, over the `h_v` per-head scalars. -/// -/// **THIS IS `build_layer_attn_linear` L889, AND LEAVING IT OUT WAS THE C1 BUG.** The reference computes -/// `beta = ggml_sigmoid(ssm_beta @ cur)` and hands the RESULT to the delta net; `gdn_step_kernel` is documented -/// as `d[h,j] = (v[h,j] - sk[h,j]) * beta[h]` and applies no sigmoid of its own, so the layer glue owes it one. -/// The engine passed the raw pre-activation, which is unbounded and signed - the delta-net write strength then -/// stops being a fraction and the whole recurrence is wrong from layer 0. -/// -/// **IT SURVIVED `gdn_parity` BECAUSE THAT TEST SUPPLIES ITS OWN `beta`.** The kernel was always right; only -/// the glue between the projection and the kernel was wrong, and `ref/gdn.py` (`beta = sigmoid(wbeta @ x)`) and -/// `ref/model.py` (`beta = G.sigmoid(proj(...))`) both get it right - so the two transcriptions agreed with -/// each other and neither was ever compared against the C++ that actually runs. -__global__ void gdn_beta_gate_kernel(float* __restrict__ beta, int n) { - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) beta[i] = sigmoid_f(beta[i]); -} - -void gdn_beta_gate(float* beta, int64_t h_v, void* stream) { - if (beta == nullptr || h_v <= 0) return; - const int n = (int) h_v; - gdn_beta_gate_kernel<<<(unsigned) ((n + 127) / 128), 128, 0, (cudaStream_t) stream>>>(beta, n); - if (stream == nullptr) { - const cudaError_t e = cudaDeviceSynchronize(); - if (e != cudaSuccess) { - std::fprintf(stderr, "gdn_beta_gate: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - } -} - -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) { - if (h_v <= 0 || S <= 0) return; - gdn_out_norm_kernel<<<(unsigned) h_v, 32, 0, (cudaStream_t) stream>>>(o, z, ssm_norm, y, (int) S, eps, - act == GdnGate::Silu ? 1 : 0); - if (stream == nullptr) { - const cudaError_t e = cudaDeviceSynchronize(); - if (e != cudaSuccess) { - std::fprintf(stderr, "gdn_out_norm: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - } -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/gr.cu b/src/kernels/cuda/gr.cu deleted file mode 100644 index 7eea7f4..0000000 --- a/src/kernels/cuda/gr.cu +++ /dev/null @@ -1,432 +0,0 @@ -// src/kernels/cuda/gr.cu - P2.S2: the gated residual / hyper-connection, `gr_read` and `gr_write`. -// -// See include/strata/kernels/gr.hpp for the semantics, for why the weights are bf16, and for the history of -// this kernel's 134x-off-the-floor first version. The short form: it was launched `<<<1, 256>>>` so that -// `xn`/`xq` fit in shared memory, which used ONE of 48 SMs and cost 262 ms/token. -// -// THE SHAPE OF THE FIX is that each projection is an ordinary GEMV and is now mapped the way the shapes want: -// -// norm hc blocks, one per residual stream (each needs its own reduction) -// down ONE WARP PER OUTPUT ROW, lanes stride the 10240 reduction axis -// gate ONE WARP PER OUTPUT ROW, lanes stride the 320 reduction axis -// mean a flat elementwise pass over n_embd -// -// WARP-PER-ROW RATHER THAN THREAD-PER-ROW, and that is the whole difference. A thread walking one row is -// coalesced with ITSELF and 32 transactions away from its warp neighbours: `w_down[k*hc_dim + i]` for fixed k -// is contiguous, but two threads on rows k and k+1 are hc_dim*2 bytes apart. With the warp on one row, lanes -// i, i+1, i+2 touch consecutive addresses in EITHER orientation - which is why this version needs no -// transposed copies and takes both matrices exactly as the manifest stores them. -// -// Layouts are the MANIFEST's: `hc_attn_down.weight` is [10240, 320] with ne0 = hc*n_embd fast, so it holds -// `w_down[k][i]` with i contiguous - `ref/gr.py`'s (hc_lr, hc*n_embd) row-major. `hc_attn_up.weight` is -// [320, 10240] so it holds `w_up[i][k]` with k contiguous - `ref/gr.py`'s (hc*n_embd, hc_lr) row-major. Both -// index with no permutation at all. -#include "strata/kernels/gr.hpp" -#include "strata/kernels/bf16_bits.hpp" -#include "strata/kernels/bf16_gemv.hpp" -#include "strata/kernels/native_gr_norm.hpp" -#include "strata/kernels/native_gr_postops.hpp" - -#include - -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int THREADS = 256; -constexpr int WARPS = THREADS / 32; -bool fp32_activations = false; -bool native_mmvf = false; - -/// The bf16 conversions live in `strata/kernels/bf16_bits.hpp`, and this file used to carry its own copies. -/// Two files with a private copy of a conversion whose failure mode is silent wrong bits is one too many - -/// and the reason the shared header exists is that `bf16` and `fp16` are NOT two spellings of one idea, so a -/// routine written for one and reused for the other is wrong in a way that still produces numbers. -/// -/// The local names are kept as thin wrappers so the body below is untouched by the swap. -__device__ __forceinline__ uint16_t f32_to_bf16_bits(float f) { return bf16_from_f32(f); } -__device__ __forceinline__ float bf16_bits_to_f32(uint16_t h) { return f32_from_bf16(h); } -__device__ __forceinline__ float activation_f32(float x) { return x; } -__device__ __forceinline__ float activation_f32(uint16_t x) { return bf16_bits_to_f32(x); } -__device__ __forceinline__ void store_activation(float* dst, int i, float x) { dst[i] = x; } -__device__ __forceinline__ void store_activation(uint16_t* dst, int i, float x) { - dst[i] = f32_to_bf16_bits(x); -} - -/// silu and sigmoid exactly as `ref/gr.py` writes them - in FLOAT, not double. -/// -/// This is the opposite of `shared_expert.cu`, which uses double, and the difference is not stylistic: -/// `ref/gr.py`'s arrays are float32, so `x / (1.0 + np.exp(-x))` evaluates in float32 under NEP 50, while -/// `ref/moe.py` works in float64. Matching the reference's PRECISION is part of transcribing it. -__device__ __forceinline__ float silu_f(float x) { return x / (1.0f + expf(-x)); } -__device__ __forceinline__ float sigmoid_f(float x) { return 1.0f / (1.0f + expf(-x)); } - -__device__ __forceinline__ double warp_sum(double v) { - for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off); - return __shfl_sync(0xFFFFFFFFu, v, 0); -} - -__device__ __forceinline__ float warp_sumf(float v) { - for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off); - return __shfl_sync(0xFFFFFFFFu, v, 0); -} - -/// The FP32 block-wide sum, for the reason the review's G5 states: this is a GeForce part and FP64 runs at a -/// small fraction of FP32, so a `double` reduction turns a bandwidth kernel into a latency kernel. -/// -/// The scratch is taken as `double*` and reinterpreted as `float*` rather than changing the callers' shared -/// arrays, because `double scratch[8]` is 64 bytes and so is at least as large as the `float[8]` this needs - -/// the cast cannot overrun, and it keeps the change to one function instead of one per caller. -__device__ float block_sumf(float v, double* scratch_raw) { - float* scratch = (float*) scratch_raw; - // The leading barrier is not decoration - see the note on `block_sum` above: the result is read straight out - // of `scratch[0]` by every thread and a later call reuses the array, so without it a fast thread can - // overwrite `scratch[0]` before a slow one has read the previous result. - __syncthreads(); - const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; - v = warp_sumf(v); - if (lane == 0) scratch[warp] = v; - __syncthreads(); - const int nw = ((int) blockDim.x + 31) >> 5; - v = (threadIdx.x < nw) ? scratch[threadIdx.x] : 0.0f; - if (warp == 0) v = warp_sumf(v); - if (threadIdx.x == 0) scratch[0] = v; - __syncthreads(); - return scratch[0]; -} - -/// Block-wide sum in DOUBLE, broadcast to every thread. -/// -/// Double because `ref/gr.py` reduces in float64 for the norm and the bottleneck, and because a block-wide -/// f32 sum of 2560 squares is a different number from the reference's; the shuffle tree here also reorders -/// the additions, so the only defence is enough precision that the order stops mattering. -/// -/// The leading `__syncthreads()` is not decoration: the result is read straight out of `scratch[0]` by every -/// thread, and a later call reuses the same array. Without a barrier on entry a fast thread can overwrite -/// `scratch[0]` before a slow one has read the previous result - a race that is invisible in most runs. -__device__ double block_sum(double v, double* scratch) { - __syncthreads(); - const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; - v = warp_sum(v); - if (lane == 0) scratch[warp] = v; - __syncthreads(); - const int nw = ((int) blockDim.x + 31) >> 5; - v = (threadIdx.x < nw) ? scratch[threadIdx.x] : 0.0; - if (warp == 0) v = warp_sum(v); - if (threadIdx.x == 0) scratch[0] = v; - __syncthreads(); - return scratch[0]; -} - -/// `hc` blocks, one per residual stream: per-stream RMSNorm, then the activated stream in both forms. -/// -/// ggml_rms_norm reduces over ne[0], and ne[0] is n_embd, so the reduction is PER STREAM. The `[n_embd, hc]` -/// gamma then scales each stream individually. -/// -/// A per-thread accumulator is only a sum when the block is narrower than the row, which is why this is a -/// block reduction: with `n_embd` equal to the thread count every thread would hold exactly one element and -/// normalise by its own square. That mistake is silent - it produces a plausible vector of the right shape - -/// and it is what `gr_parity`'s `mixed vs reference` caught at 2.0e+01 in round 196. -template -__global__ void gr_norm_kernel(const float* __restrict__ R, const float* __restrict__ w_norm, float eps, - int n_embd, float* __restrict__ xn, uint16_t* __restrict__ xq) { - __shared__ double scratch[8]; - const int c = blockIdx.x; - const float* Rc = R + (size_t) c * n_embd; - float* xnc = xn + (size_t) c * n_embd; - uint16_t* xqc = xq + (size_t) c * n_embd; - - // FP32, for the same reason as `gr_down_kernel` and `gr_inject_kernel`: this is a GeForce part, FP64 runs - // at a small fraction of FP32, and the sum of squares is a pure reduction. It was the last `double` on the - // `gr_read` path. `gr_norm` is only 0.80 ms/token, so this is hygiene rather than a headline - but it is - // 12 of the FP64 sites the review's G5 counted in this file, and the rule it states ("no FP64 on any decode - // or prefill path") is worth being able to check mechanically rather than case by case. - float ss = 0.0f; - for (int d = threadIdx.x; d < n_embd; d += blockDim.x) { - const float v = Rc[d]; - ss += v * v; - } - const float ms = block_sumf(ss, scratch) / (float) n_embd; - const float rs = rsqrtf(ms + eps); - for (int d = threadIdx.x; d < n_embd; d += blockDim.x) { - const float x = Rc[d] * rs * w_norm[(size_t) c * n_embd + d]; - xnc[d] = x; - if constexpr (!FP32_ACT) xqc[d] = f32_to_bf16_bits(x); - } -} - -/// `lo = silu((bf16(xn) @ w_down.T) / hc)`, ONE BLOCK PER OUTPUT ROW with its warps splitting the reduction. -template -__global__ void gr_down_kernel(const Activation* __restrict__ xq, const uint16_t* __restrict__ w_down, int hc_dim, - int hc_lr, int hc, Activation* __restrict__ lq) { - const int k = blockIdx.x; - if (k >= hc_lr) return; - const int lane = threadIdx.x & 31; - const int warp = threadIdx.x >> 5; - const int nw = (int) (blockDim.x >> 5); // warps per row == warps per block - const uint16_t* row = w_down + (size_t) k * hc_dim; - // **THE OCCUPANCY HERE IS 10% AND IT IS REAL, BUT FIXING IT DOES NOT PAY.** `hc_lr` is 320, one warp per - // row, 8 warps per block, so this launches 40 blocks = 320 warps: **6.7 warps per SM out of the 64 a - // Blackwell SM holds**, each lane walking 10,240 elements in 320 dependent steps. - // - // Four independent accumulators were tried to break the dependency chain and put four loads in flight per - // lane. **Measured: 39.86 ms/token of pure GPU against 39.80, i.e. no change**, with `gr_parity` green - // either way. Removed, on the rule this file already states about `#pragma unroll 4`: a hint that does not - // change the timing is a claim that is not true. - // - // The reason is that `gr_read`'s cost is not here. Its four kernels are the norm (4 blocks), this (40), - // `gr_gate_kernel` (1,280) and the mean (10), and the 1,280-block gate kernel reads 6.55 MB of weights with - // good occupancy - so `gr_read`'s ~93 us is mostly the gate kernel at its own memory rate, and the ~165 GB/s - // whole-call figure is an average over kernels that do not share a rate. - // **FP32, AND THE FP64 THAT WAS HERE COST MORE THAN EVERYTHING ELSE IN `gr_read`.** - // - // This accumulated in `double`. GeForce Blackwell executes FP64 at a small fraction of FP32 - 1/64 on - // recent parts - so a 320-step dependent FP64 chain per lane turned a memory-bound reduction into a - // latency-bound one. The `nsys` per-kernel table (round 2) measured it at **5.07 ms/token, 15.3% of all - // GPU time**, against `gr_gate_kernel`'s 1.23 ms - which REFUTES the comment that used to sit here, that - // "gr_read's ~93 us is mostly the gate kernel at its own memory rate". It was not: down + inject were - // 8.77 of gr_read's 10.8 ms, and the gate was 1.23. - // - // The justification for `double` was matching `ref/gr.py`'s float64 transcription. **The ground truth is - // llama.cpp, and llama.cpp accumulates in FP32** - so this does not move away from the oracle, it moves - // toward it, and the review's G1 lists it first. - // - // Four independent accumulators were tried here BEFORE, against the FP64 version, and measured no change - // (39.86 vs 39.80 ms/token) - because FP64 throughput was the limit, not the dependency chain. With FP32 - // the kernel becomes memory-bound: it reads ~13 MB per call across xq and w_down, which at the measured - // 641 GB/s is ~20 us against the 52 us this took. - // **THE OCCUPANCY CONCLUSION ABOVE IS STALE, AND THIS IS THE RETEST IT ASKED FOR.** - // - // "Fixing it does not pay" was measured against the FP64 version, where FP64 THROUGHPUT was the limit and - // more parallelism could not help. The kernel is FP32 now (round 282: 5.07 -> 2.38 ms/token) and the limit - // moved to memory - which is the regime where occupancy does pay, because at 6.7 warps/SM there are not - // enough bytes in flight to cover DRAM latency. The old result is not wrong; it is about a different kernel. - // - // One BLOCK per row, its 8 warps splitting the 10,240-element reduction: 320 blocks x 8 = **2,560 warps = - // 53 warps/SM instead of 6.7**, with no second kernel and no partial buffer - the eight partials meet in - // shared memory. Lanes within a warp still read consecutive addresses, because warp `w` starts at - // `w * 32` and strides by `nw * 32`. - float acc = 0.0f; - for (int i = warp * 32 + lane; i < hc_dim; i += nw * 32) - acc += activation_f32(xq[i]) * bf16_bits_to_f32(row[i]); - acc = warp_sumf(acc); - - __shared__ float part[WARPS]; - if (lane == 0) part[warp] = acc; - __syncthreads(); - if (warp == 0) { - float t = (lane < nw) ? part[lane] : 0.0f; - t = warp_sumf(t); - // NOTE: the reduction order differs from the one-warp version, so this is a NUMERICS CHANGE. C1 is the - // gate that judges it - not this comment, and not `gr_parity`, which compares against the reference on - // a fixture that a changed summation order can still pass. - if (lane == 0) store_activation(lq, k, silu_f(t / (float) hc)); - } -} - -/// `gated[i] = xn[i] * sigmoid(bf16(lo) @ w_up.T)`, one warp per output row, lanes striding hc_lr. -template -__global__ void gr_gate_kernel(const Activation* __restrict__ lq, const uint16_t* __restrict__ w_up, - const float* __restrict__ xn, int hc_dim, int hc_lr, float* __restrict__ gated) { - const int i = blockIdx.x * WARPS + (threadIdx.x >> 5); - if (i >= hc_dim) return; - const int lane = threadIdx.x & 31; - const uint16_t* row = w_up + (size_t) i * hc_lr; - float acc = 0.0f; - for (int k = lane; k < hc_lr; k += 32) - acc += activation_f32(lq[k]) * bf16_bits_to_f32(row[k]); - acc = warp_sumf(acc); - // Every lane computes the sigmoid (the shuffle broadcasts acc), so there is no second sync point and no - // branch; lane 0 stores. - if (lane == 0) gated[i] = xn[i] * sigmoid_f(acc); -} - -/// `mixed[d] = mean over c of gated[c][d]`. Flat elementwise: the mean is over the streams, which are -/// strided by n_embd, so no cross-thread reduction is needed at all. -__global__ void gr_mean_kernel(const float* __restrict__ gated, int n_embd, int hc, float* __restrict__ mixed) { - const int d = blockIdx.x * blockDim.x + threadIdx.x; - if (d >= n_embd) return; - float m = 0.0f; - for (int c = 0; c < hc; ++c) m += gated[(size_t) c * n_embd + d]; - mixed[d] = m / (float) hc; -} - -/// `inject[c] = bf16(xn) @ w_inject[c]`, one value per stream: ONE WARP PER STREAM, lanes striding hc_dim. -/// -/// This mirrors `gr_down_kernel` rather than using a block-wide reduction. `hc` is 4 at the real geometry, -/// so a block per stream would put 256 threads on a 10240-element dot and leave the reduction to do all the -/// work; a warp per stream is the same shape as the down projection and reuses its pattern exactly. The -/// whole kernel is one block of `32*hc` threads, which is small - and it is a 4-value output, so it is. -template -__global__ void gr_inject_kernel(const Activation* __restrict__ xq, const uint16_t* __restrict__ w_inject, - int hc_dim, int hc, float* __restrict__ inject) { - const int c = threadIdx.x >> 5; - if (c >= hc) return; - const int lane = threadIdx.x & 31; - const uint16_t* row = w_inject + (size_t) c * hc_dim; - // FP32, for the same reason as `gr_down_kernel` - and this one is worse. A ONE-BLOCK kernel doing four - // 10,240-element FP64 reductions measured **3.70 ms/token, 11.1% of all GPU time, from a single SM out of - // 48.** It is the fourth largest consumer of GPU time in the engine and it cannot use more than 1/48th of - // the machine. In FP32 the same reduction is a few microseconds and the block size stops mattering. - float acc = 0.0f; - for (int i = lane; i < hc_dim; i += 32) - acc += activation_f32(xq[i]) * bf16_bits_to_f32(row[i]); - acc = warp_sumf(acc); - if (lane == 0) inject[c] = acc; -} - -__global__ void gr_write_kernel(const float* __restrict__ R, const float* __restrict__ block_out, - const float* __restrict__ inject, int n_embd, int hc, float* __restrict__ out) { - // w = 2*sigmoid(inject/hc), computed once per stream in shared rather than per element. - extern __shared__ unsigned char smem_raw[]; - float* w = (float*) smem_raw; - if ((int) threadIdx.x < hc) w[threadIdx.x] = 2.0f * sigmoid_f(inject[threadIdx.x] / (float) hc); - __syncthreads(); - const long long n = (long long) hc * n_embd; - for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < n; - i += (long long) gridDim.x * blockDim.x) { - const int c = (int) (i / n_embd), d = (int) (i % n_embd); - // every stream adds the SAME block output; only the weight differs per stream - out[i] = R[i] + block_out[d] * w[c]; - } -} - -} // namespace - -void gr_set_fp32_activations(bool enabled) { fp32_activations = enabled; } -void gr_set_native_mmvf(bool enabled) { native_mmvf = enabled; } - -size_t gr_workspace_init(const GrShapes& s, void* base, GrWorkspace& out) { - const size_t hc_dim = (size_t) s.hc * (size_t) s.n_embd; - // ONE table, indexed by the same `k` that assigns the pointers below. The first version of this function - // sized three locals named `xn`, `xq`, `lq` in a DIFFERENT order from the pointer assignments - `xq` got - // hc_lr*2 while `lq` got hc_dim*4 - so for the real geometry xq was given 640 bytes where it needed - // 20,480 and every region overlapped its neighbour. - // - // What that looked like is worth recording: `inject` came out ~20% wrong, and rewriting its reduction - // from block-wide to warp-wide produced BYTE-IDENTICAL wrong answers. Two different reductions agreeing - // exactly is not a coincidence to investigate - it means the reduction is not where the bug is, and the - // inputs are. Chasing the reduction instead cost most of a round. - const size_t sz[5] = { - hc_dim * sizeof(float), // 0: xn - hc_dim * sizeof(uint16_t), // 1: xq - (size_t) s.hc_lr * sizeof(uint16_t), // 2: lq - hc_dim * sizeof(float), // 3: gated - (size_t) s.hc_lr * sizeof(float), // 4: lo (FP32 activation experiment) - }; - size_t al[5], bytes = 0; - for (int k = 0; k < 5; ++k) { - al[k] = (sz[k] + 15) & ~(size_t) 15; - bytes += al[k]; - } - out.bytes = bytes; - if (base != nullptr) { - unsigned char* p = (unsigned char*) base; - void* ptr[5]; - for (int k = 0; k < 5; ++k) { - ptr[k] = p; - p += al[k]; - } - out.xn = (float*) ptr[0]; - out.xq = (uint16_t*) ptr[1]; - out.lq = (uint16_t*) ptr[2]; - out.gated = (float*) ptr[3]; - out.lo = (float*) ptr[4]; - } - return bytes; -} - -void gr_read(const float* R, const float* w_norm, const uint16_t* w_down, const uint16_t* w_up, - const uint16_t* w_inject, float eps, const GrShapes& s, const GrWorkspace& ws, float* mixed, - float* inject, void* stream) { - if (s.n_embd <= 0 || s.hc <= 0 || s.hc_lr <= 0) return; - if (ws.xn == nullptr || ws.xq == nullptr || ws.lq == nullptr || ws.gated == nullptr || ws.lo == nullptr) { - std::fprintf(stderr, "gr_read: GrWorkspace is not initialised (see gr_workspace_init)\n"); - std::exit(1); - } - if (ws.bytes < gr_workspace_bytes(s)) { - std::fprintf(stderr, "gr_read: GrWorkspace is %zu bytes but this geometry needs %zu\n", - ws.bytes, gr_workspace_bytes(s)); - std::exit(1); - } - const int n_embd = (int) s.n_embd, hc = (int) s.hc, hc_lr = (int) s.hc_lr; - const int hc_dim = (int) (s.hc * s.n_embd); - cudaStream_t st = (cudaStream_t) stream; - - // One setting selects every projection in this call. Captured graphs retain these kernel variants. - const bool use_native = native_mmvf; - const bool use_fp32 = fp32_activations || use_native; - if (use_native) { - if ((hc_dim & 1) != 0 || (hc_lr & 1) != 0) - throw std::invalid_argument("gr_read native MMVF requires even hc*n_embd and hc_lr"); - native_gr_rms_norm_weighted(R, w_norm, ws.xn, n_embd, hc, eps, stream); - bf16_gemv_fp32_mmvf(ws.xn, w_down, ws.lo, hc_dim, hc_lr, stream); - native_gr_down_silu(ws.lo, hc_lr, hc, stream); - bf16_gemv_fp32_mmvf(ws.lo, w_up, ws.gated, hc_lr, hc_dim, stream); - // The existing null-injection contract identifies the final mixer. - // Pinned qwen4exp uses fused HC pre for layers and the unfused graph for il=-1. - native_gr_pre_gated(ws.xn, ws.gated, mixed, n_embd, hc, w_inject != nullptr, stream); - } else if (use_fp32) { - gr_norm_kernel<<>>(R, w_norm, eps, n_embd, ws.xn, ws.xq); - gr_down_kernel<<>>(ws.xn, w_down, hc_dim, hc_lr, hc, ws.lo); - gr_gate_kernel<<<(hc_dim + WARPS - 1) / WARPS, THREADS, 0, st>>>( - ws.lo, w_up, ws.xn, hc_dim, hc_lr, ws.gated); - } else { - gr_norm_kernel<<>>(R, w_norm, eps, n_embd, ws.xn, ws.xq); - gr_down_kernel<<>>(ws.xq, w_down, hc_dim, hc_lr, hc, ws.lq); - gr_gate_kernel<<<(hc_dim + WARPS - 1) / WARPS, THREADS, 0, st>>>( - ws.lq, w_up, ws.xn, hc_dim, hc_lr, ws.gated); - } - if (!use_native) - gr_mean_kernel<<<(n_embd + THREADS - 1) / THREADS, THREADS, 0, st>>>(ws.gated, n_embd, hc, mixed); - // Absent for the final mixer, and then nothing is written - computing an injection nobody reads would be - // a claim, not a convenience. - if (w_inject != nullptr) { - const int nthreads = 32 * hc; - if (use_native) - bf16_gemv_fp32_mmvf(ws.xn, w_inject, inject, hc_dim, hc, stream); - else if (use_fp32) - gr_inject_kernel<<<1, nthreads, 0, st>>>(ws.xn, w_inject, hc_dim, hc, inject); - else - gr_inject_kernel<<<1, nthreads, 0, st>>>(ws.xq, w_inject, hc_dim, hc, inject); - } - - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "gr_read launch: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - if (stream == nullptr) { - const cudaError_t se = cudaDeviceSynchronize(); - if (se != cudaSuccess) { - std::fprintf(stderr, "gr_read: %s\n", cudaGetErrorString(se)); - std::exit(1); - } - } -} - -void gr_write(const float* R, const float* block_out, const float* inject, const GrShapes& s, float* R_out, - void* stream) { - if (s.n_embd <= 0 || s.hc <= 0) return; - const long long n = (long long) s.hc * s.n_embd; - const int blocks = (int) ((n + THREADS - 1) / THREADS); - if (native_mmvf) - native_gr_post(R, block_out, inject, R_out, (int) s.n_embd, (int) s.hc, stream); - else - gr_write_kernel<<>>( - R, block_out, inject, (int) s.n_embd, (int) s.hc, R_out); - if (stream == nullptr) { - const cudaError_t e = cudaDeviceSynchronize(); - if (e != cudaSuccess) { - std::fprintf(stderr, "gr_write: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - } -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu deleted file mode 100644 index 78d47b1..0000000 --- a/src/kernels/cuda/iq_kernels.cu +++ /dev/null @@ -1,2637 +0,0 @@ -// src/kernels/cuda/iq_kernels.cu - see include/strata/kernels/iq_kernels.hpp. -// -// The dot products (vec_dot_*_q8_1), the dequantizers and the q8_1 quantizer are transcribed from llama.cpp -// (ggml/src/ggml-cuda/vecdotq.cuh, dequantize.cuh, quantize.cu at the commit in third_party/ggml/VERSION.txt; -// MIT license, third_party/ggml/LICENSE). The block structs and codebook grids come from its ggml-common.h, -// included unchanged. -#include "strata/kernels/iq_kernels.hpp" -#include "strata/kernels/dp4a.hpp" -#include "strata/kernels/q8_1_finite.hpp" - -#include -#include - -#define GGML_COMMON_DECL_CUDA -#define GGML_COMMON_IMPL_CUDA -#include "ggml-common.h" - -#include -#include -#include - -namespace strata::kernels { -namespace { - -void check(const char* what) { - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(1); } -} - -// ---------------------------------------------------------------- llama.cpp helpers (vecdotq.cuh) -__device__ __forceinline__ int get_int_b2(const void* x, const int& i32) { - const uint16_t* x16 = (const uint16_t*) x; - int x32 = x16[2 * i32 + 0] << 0; - x32 |= x16[2 * i32 + 1] << 16; - return x32; -} -__device__ __forceinline__ int get_int_b4(const void* x, const int& i32) { return ((const int*) x)[i32]; } -__device__ __forceinline__ uint32_t unpack_ksigns(const uint8_t v) { - const uint32_t p = __popc(v) & 1; - const uint32_t s = v ^ p << 7; - return s * 0x01010101; -} -__device__ __forceinline__ int2 get_int_from_table_16(const int& q4, const int8_t* table) { -#if defined(STRATA_HIP_GFX906) - // AMD: llama.cpp's HIP lookup (vecdotq.cuh) - v_perm_b32 takes 3-bit byte indices, so the low and high halves - // of the table are looked up and the index MSB picks between them: 4 perms per 8 values. - const uint32_t* v32 = reinterpret_cast(table); - const uint32_t q_even = (uint32_t) q4, q_odd = (uint32_t) q4 >> 4; - const uint32_t el = __builtin_amdgcn_perm(v32[1], v32[0], q_even & 0x07070707u); - const uint32_t ol = __builtin_amdgcn_perm(v32[1], v32[0], q_odd & 0x07070707u); - const uint32_t eh = __builtin_amdgcn_perm(v32[3], v32[2], q_even & 0x07070707u); - const uint32_t oh = __builtin_amdgcn_perm(v32[3], v32[2], q_odd & 0x07070707u); - return make_int2((int) __builtin_amdgcn_perm(eh, el, 0x03020100u | ((q_even & 0x08080808u) >> 1)), - (int) __builtin_amdgcn_perm(oh, ol, 0x03020100u | ((q_odd & 0x08080808u) >> 1))); -#else - const uint32_t* table32 = (const uint32_t*) table; - uint32_t tmp[2]; - const uint32_t low_high_selection_indices = (0x32103210 | ((q4 & 0x88888888) >> 1)); -#pragma unroll - for (uint32_t i = 0; i < 2; ++i) { - const uint32_t shift = 16 * i; - const uint32_t low = __byte_perm(table32[0], table32[1], q4 >> shift); - const uint32_t high = __byte_perm(table32[2], table32[3], q4 >> shift); - tmp[i] = __byte_perm(low, high, low_high_selection_indices >> shift); - } - return make_int2(__byte_perm(tmp[0], tmp[1], 0x6420), __byte_perm(tmp[0], tmp[1], 0x7531)); -#endif -} -#define ggml_cuda_dp4a(a, b, c) STRATA_DP4A((a), (b), (c)) - -// ---------------------------------------------------------------- the dot products (vecdotq.cuh) -__device__ __forceinline__ float vec_dot_q2_0_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, - const int& kbx, const int& iqs) { - const block_q2_0* bq2_0 = (const block_q2_0*) vbq + kbx; - const float d2 = bq2_0->d; - const int16_t* qs = (const int16_t*) bq2_0->qs + iqs * 4; - const block_q8_1* bq8_1_chunk = bq8_1 + iqs; - int sumi = 0; -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int q = qs[j]; - const int u = get_int_b4(bq8_1_chunk->qs, j * 2 + 0); - const int v = get_int_b4(bq8_1_chunk->qs, j * 2 + 1); - const int qe = __byte_perm(0x020100FF, 0x020100FF, q >> 0); - const int qo = __byte_perm(0x020100FF, 0x020100FF, q >> 2); - const int qx = __byte_perm(qe, qo, 0x5140); - const int qy = __byte_perm(qe, qo, 0x7362); - sumi = ggml_cuda_dp4a(u, qx, sumi); - sumi = ggml_cuda_dp4a(v, qy, sumi); - } - const float d8 = __low2float(bq8_1_chunk->ds); - return d2 * d8 * sumi; -} - -__device__ __forceinline__ float vec_dot_iq2_xxs_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, - const int& kbx, const int& iqs) { - const block_iq2_xxs* bq2 = (const block_iq2_xxs*) vbq + kbx; - const int q2 = get_int_b2(bq2->qs, iqs); - const uint8_t* aux8 = (const uint8_t*) &q2; - const uint32_t aux32 = get_int_b2(bq2->qs, iqs + 1); - int sumi = 0; -#pragma unroll - for (int k0 = 0; k0 < 8; k0 += 2) { - const uint2 grid_pos = ((const uint2*) iq2xxs_grid)[aux8[k0 / 2]]; - const uint32_t signs = unpack_ksigns(aux32 >> (7 * k0 / 2)); - const int signs0 = __vcmpne4(signs & 0x08040201, 0); - const int grid0 = __vsub4(grid_pos.x ^ signs0, signs0); - const int u0 = get_int_b4(bq8_1[iqs / 2].qs, k0 + 0); - sumi = ggml_cuda_dp4a(grid0, u0, sumi); - const int signs1 = __vcmpne4(signs & 0x80402010, 0); - const int grid1 = __vsub4(grid_pos.y ^ signs1, signs1); - const int u1 = get_int_b4(bq8_1[iqs / 2].qs, k0 + 1); - sumi = ggml_cuda_dp4a(grid1, u1, sumi); - } - const int ls = aux32 >> 27 | 1; - sumi = sumi * ls / 8; - const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds); - return d * sumi; -} - -__device__ __forceinline__ float vec_dot_iq2_xs_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, - const int& kbx, const int& iqs) { - const block_iq2_xs* bq2 = (const block_iq2_xs*) vbq + kbx; - const int2 q2_packed = make_int2(get_int_b2(bq2->qs, iqs + 0), get_int_b2(bq2->qs, iqs + 1)); - const uint16_t* q2 = (const uint16_t*) &q2_packed; - const int ls0 = bq2->scales[iqs / 2] & 0x0F; - const int ls1 = bq2->scales[iqs / 2] >> 4; - int sumi0 = 0, sumi1 = 0; -#pragma unroll - for (int l0 = 0; l0 < 8; l0 += 2) { - const uint2 grid_pos = ((const uint2*) iq2xs_grid)[q2[l0 / 2] & 0x1FF]; - const uint32_t signs = unpack_ksigns(q2[l0 / 2] >> 9); - const int signs0 = __vcmpne4(signs & 0x08040201, 0); - const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0); - const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0); - const int signs1 = __vcmpne4(signs & 0x80402010, 0); - const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1); - const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1); - if (l0 < 4) { - sumi0 = ggml_cuda_dp4a(grid_l, u0, sumi0); - sumi0 = ggml_cuda_dp4a(grid_h, u1, sumi0); - } else { - sumi1 = ggml_cuda_dp4a(grid_l, u0, sumi1); - sumi1 = ggml_cuda_dp4a(grid_h, u1, sumi1); - } - } - const int sumi = (sumi0 * ls0 + sumi1 * ls1 + (sumi0 + sumi1) / 2) / 4; - const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds); - return d * sumi; -} - -__device__ __forceinline__ float vec_dot_iq2_s_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, - const int& kbx, const int& iqs) { - const block_iq2_s* bq2 = (const block_iq2_s*) vbq + kbx; - const int qs_packed = get_int_b2(bq2->qs, iqs / 2); - const uint8_t* qs = (const uint8_t*) &qs_packed; - const int qh = bq2->qh[iqs / 2]; - const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2); - const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32; - const int ls0 = bq2->scales[iqs / 2] & 0x0F; - const int ls1 = bq2->scales[iqs / 2] >> 4; - int sumi0 = 0, sumi1 = 0; -#pragma unroll - for (int l0 = 0; l0 < 8; l0 += 2) { - const int* grid_pos = (const int*) (iq2s_grid + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300))); - const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000); - const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000); - const int grid_l = __vsub4(grid_pos[0] ^ signs0, signs0); - const int grid_h = __vsub4(grid_pos[1] ^ signs1, signs1); - const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0); - const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1); - if (l0 < 4) { - sumi0 = ggml_cuda_dp4a(grid_l, u0, sumi0); - sumi0 = ggml_cuda_dp4a(grid_h, u1, sumi0); - } else { - sumi1 = ggml_cuda_dp4a(grid_l, u0, sumi1); - sumi1 = ggml_cuda_dp4a(grid_h, u1, sumi1); - } - } - const int sumi = (sumi0 * ls0 + sumi1 * ls1 + (sumi0 + sumi1) / 2) / 4; - const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds); - return d * sumi; -} - -__device__ __forceinline__ float vec_dot_iq3_xxs_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, - const int& kbx, const int& iqs) { - const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx; - const int2 q3_packed = make_int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1)); - const uint8_t* q3 = (const uint8_t*) &q3_packed; - const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2); - int sumi = 0; -#pragma unroll - for (int l0 = 0; l0 < 8; l0 += 2) { - const int2 grid_pos = make_int2(iq3xxs_grid[q3[l0 + 0]], iq3xxs_grid[q3[l0 + 1]]); - const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2)); - const int signs0 = __vcmpne4(signs & 0x08040201, 0); - const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0); - const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0); - const int signs1 = __vcmpne4(signs & 0x80402010, 0); - const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1); - const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1); - sumi = ggml_cuda_dp4a(grid_l, u0, sumi); - sumi = ggml_cuda_dp4a(grid_h, u1, sumi); - } - const int ls = aux32 >> 28; - sumi = (ls * sumi + sumi / 2) / 2; - const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds); - return d * sumi; -} - -__device__ __forceinline__ float vec_dot_iq3_s_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, - const int& kbx, const int& iqs) { - const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx; - const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1)); - const uint8_t* qs = (const uint8_t*) &qs_packed; - const int qh = bq3->qh[iqs / 2]; - const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2); - const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32; - int sumi = 0; -#pragma unroll - for (int l0 = 0; l0 < 8; l0 += 2) { - const int2 grid_pos = make_int2(iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)], - iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]); - const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000); - const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000); - const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0); - const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1); - const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0); - const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1); - sumi = ggml_cuda_dp4a(grid_l, u0, sumi); - sumi = ggml_cuda_dp4a(grid_h, u1, sumi); - } - sumi *= 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F); - const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds); - return d * sumi; -} - -__device__ __forceinline__ float vec_dot_iq1_m_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, - const int& kbx, const int& iqs) { - const block_iq1_m* bq1 = (const block_iq1_m*) vbq + kbx; - const int qs_packed = get_int_b4(bq1->qs, iqs); - const uint8_t* qs = (const uint8_t*) &qs_packed; - int sumi[2] = {0, 0}; - float sumf[2] = {0.0f, 0.0f}; -#pragma unroll - for (int l0 = 0; l0 < 8; l0 += 2) { - const int qhl = bq1->qh[2 * iqs + l0 / 4] >> (4 * ((l0 / 2) % 2)); - const int grid = iq1s_grid_gpu[qs[l0 / 2] | ((qhl & 0x07) << 8)]; - const int grid0 = (grid >> 0) & 0x0F0F0F0F; - const int grid1 = (grid >> 4) & 0x0F0F0F0F; - const int u0 = get_int_b4(bq8_1[iqs].qs, l0 + 0); - const int u1 = get_int_b4(bq8_1[iqs].qs, l0 + 1); - sumi[l0 / 4] = ggml_cuda_dp4a(grid0, u0, sumi[l0 / 4]); - sumi[l0 / 4] = ggml_cuda_dp4a(grid1, u1, sumi[l0 / 4]); - const float delta = -1.0f + IQ1M_DELTA - (qhl & 0x08) * (2.0f * IQ1M_DELTA / 0x08); - int sumy = 0; - sumy = ggml_cuda_dp4a(u0, 0x01010101, sumy); - sumy = ggml_cuda_dp4a(u1, 0x01010101, sumy); - sumf[l0 / 4] += delta * sumy; - } - const uint16_t* sc = (const uint16_t*) bq1->scales; - iq1m_scale_t scale; - scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00F0) | ((sc[2] >> 4) & 0x0F00) | (sc[3] & 0xF000); - const float d = __half2float(scale.f16) * __low2float(bq8_1[iqs].ds); - const int tmp = sc[iqs / 2] >> (6 * (iqs % 2)); - const int sc0 = 2 * ((tmp >> 0) & 0x07) + 1; - const int sc1 = 2 * ((tmp >> 3) & 0x07) + 1; - return d * ((sumi[0] + sumf[0]) * sc0 + (sumi[1] + sumf[1]) * sc1); -} - -__device__ __forceinline__ float vec_dot_iq4_nl_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, - const int& kbx, const int& iqs) { - const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx; - const int* q8 = (const int*) bq8_1->qs + iqs; - int sumi = 0; -#pragma unroll - for (int l = 0; l < 2; ++l) { - const int aux_q4 = get_int_b2(bq4->qs, iqs + l); - const int2 v = get_int_from_table_16(aux_q4, kvalues_iq4nl); - sumi = ggml_cuda_dp4a(v.x, q8[l + 0], sumi); - sumi = ggml_cuda_dp4a(v.y, q8[l + 4], sumi); - } - const float d = __half2float(bq4->d) * __low2float(bq8_1->ds); - return d * sumi; -} - -// IQ4_XS: 256 values as 8 sub-blocks of 32 (6-bit scale each); one call covers one sub-block (iqs = 4 * sub-block), -// and `bq8_1` is the super-block's first q8_1 block, so the call's activation is bq8_1[iqs / 4]. The GSQ-RCO IQ3_S -// file keeps one layer's routed gate/up experts in this format. -__device__ __forceinline__ float vec_dot_iq4_xs_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, - const int& kbx, const int& iqs) { - const block_iq4_xs* bq4 = (const block_iq4_xs*) vbq + kbx; - int sumi = 0; -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int aux_q4 = get_int_b4(bq4->qs, iqs + j); - const int2 v = get_int_from_table_16(aux_q4, kvalues_iq4nl); - const int u0 = get_int_b4(bq8_1[iqs / 4].qs, j + 0); - const int u1 = get_int_b4(bq8_1[iqs / 4].qs, j + 4); - sumi = ggml_cuda_dp4a(v.x, u0, sumi); - sumi = ggml_cuda_dp4a(v.y, u1, sumi); - } - const int ls = ((bq4->scales_l[iqs / 8] >> (iqs & 0x04)) & 0x0F) | (((bq4->scales_h >> (iqs / 2)) & 0x03) << 4); - sumi *= ls - 32; - const float d = __half2float(bq4->d) * __low2float(bq8_1[iqs / 4].ds); - return d * sumi; -} - -// ---------------------------------------------------------------- Unsloth's UD-Q4_K_XL experts -// Q4_K / Q5_K gate/up and Q5_1 / Q8_0 down: llama.cpp's vec_dot_*_q8_1 (vecdotq.cuh, VDR 2 each), transcribed; the -// Q5_1 min term is the one departure (below). Via eddoursul/Strata 8029fa9 (iq_dot.cuh) and #255 (Q8_0, -// gopinath87607), which agree with llama.cpp and with each other. Q6_K (Qwen3.6's UD-Q4_K_XL down projections on -// layers 34, 38, 39, and its layer 39 gate/up is Q5_K) is llama.cpp's vec_dot_q6_K_q8_1 (VDR 1), transcribed. -constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q5_0 = 2, VDR_Q8_0 = 2, VDR_Q6_K = 1; - -__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, - const half2& dm4, const float* __restrict__ d8) { - float sumf_d = 0.0f; - float sumf_m = 0.0f; -#pragma unroll - for (int i = 0; i < QR4_K; ++i) { - const int v0i = (v[0] >> (4 * i)) & 0x0F0F0F0F; - const int v1i = (v[1] >> (4 * i)) & 0x0F0F0F0F; - const int dot1 = ggml_cuda_dp4a(v1i, u[2 * i + 1], ggml_cuda_dp4a(v0i, u[2 * i + 0], 0)); - const int dot2 = ggml_cuda_dp4a(0x01010101, u[2 * i + 1], ggml_cuda_dp4a(0x01010101, u[2 * i + 0], 0)); - sumf_d += d8[i] * (dot1 * sc[i]); - sumf_m += d8[i] * (dot2 * m[i]); // the min times the sum of the QUANTIZED activations - } - const float2 dm4f = __half22float2(dm4); - return dm4f.x * sumf_d - dm4f.y * sumf_m; -} -__device__ __forceinline__ float vec_dot_q5_K_q8_1_impl_vmmq(const int* __restrict__ vl, const int* __restrict__ vh, - const int* __restrict__ u, const uint8_t* __restrict__ sc, - const uint8_t* __restrict__ m, const half2& dm5, - const float* __restrict__ d8) { - float sumf_d = 0.0f; - float sumf_m = 0.0f; -#pragma unroll - for (int i = 0; i < QR5_K; ++i) { - const int vl0i = (vl[0] >> (4 * i)) & 0x0F0F0F0F; - const int vl1i = (vl[1] >> (4 * i)) & 0x0F0F0F0F; - const int vh0i = ((vh[0] >> i) << 4) & 0x10101010; - const int vh1i = ((vh[1] >> i) << 4) & 0x10101010; - const int v0i = vl0i | vh0i; - const int v1i = vl1i | vh1i; - const int dot1 = ggml_cuda_dp4a(v0i, u[2 * i + 0], ggml_cuda_dp4a(v1i, u[2 * i + 1], 0)); - const int dot2 = ggml_cuda_dp4a(0x01010101, u[2 * i + 0], ggml_cuda_dp4a(0x01010101, u[2 * i + 1], 0)); - sumf_d += d8[i] * (dot1 * sc[i]); - sumf_m += d8[i] * (dot2 * m[i]); - } - const float2 dm5f = __half22float2(dm5); - return dm5f.x * sumf_d - dm5f.y * sumf_m; -} -// the 6-bit scales and mins of the 32-value group pair bq8_offset / 2, branchless (llama.cpp; shared by Q4_K, Q5_K) -__device__ __forceinline__ void k_scale_min(const uint8_t* scales8, int bq8_offset, uint16_t aux[2]) { - const uint16_t* scales = (const uint16_t*) scales8; - const int j = bq8_offset / 2; - const int jm = j & 1; - const uint32_t s0 = scales[jm + 0]; - const uint32_t s2 = scales[jm + 2]; - const uint32_t s4 = scales[jm + 4]; - const uint32_t hi = (uint32_t) -(int32_t) (j >= 2); - aux[0] = (uint16_t) (((s0 & 0x3f3f) & ~hi) | ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi)); - aux[1] = (uint16_t) (((s2 & 0x3f3f) & ~hi) | ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi)); -} -__device__ __forceinline__ float vec_dot_q4_K_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, - const int& kbx, const int& iqs) { - const block_q4_K* bq4_K = (const block_q4_K*) vbq + kbx; - int v[2]; - int u[2 * QR4_K]; - float d8[QR4_K]; - const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2)); - const int* q4 = (const int*) (bq4_K->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4)); - v[0] = q4[0]; - v[1] = q4[4]; - uint16_t aux[2]; - k_scale_min(bq4_K->scales, bq8_offset, aux); - const uint8_t* sc = (const uint8_t*) aux; - const uint8_t* m = sc + 2; -#pragma unroll - for (int i = 0; i < QR4_K; ++i) { - const block_q8_1* bq8i = bq8_1 + bq8_offset + i; - d8[i] = __low2float(bq8i->ds); - const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4); - u[2 * i + 0] = q8[0]; - u[2 * i + 1] = q8[4]; - } - return vec_dot_q4_K_q8_1_impl_vmmq(v, u, sc, m, bq4_K->dm, d8); -} -__device__ __forceinline__ float vec_dot_q5_K_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, - const int& kbx, const int& iqs) { - const block_q5_K* bq5_K = (const block_q5_K*) vbq + kbx; - int vl[2]; - int vh[2]; - int u[2 * QR5_K]; - float d8[QR5_K]; - const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2)); - const int* ql = (const int*) (bq5_K->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4)); - const int* qh = (const int*) (bq5_K->qh + 4 * ((iqs / 2) % 4)); - vl[0] = ql[0]; - vl[1] = ql[4]; - vh[0] = qh[0] >> bq8_offset; - vh[1] = qh[4] >> bq8_offset; - uint16_t aux[2]; - k_scale_min(bq5_K->scales, bq8_offset, aux); - const uint8_t* sc = (const uint8_t*) aux; - const uint8_t* m = sc + 2; -#pragma unroll - for (int i = 0; i < QR5_K; ++i) { - const block_q8_1* bq8i = bq8_1 + bq8_offset + i; - d8[i] = __low2float(bq8i->ds); - const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4); - u[2 * i + 0] = q8[0]; - u[2 * i + 1] = q8[4]; - } - 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 -// mins above use; the scaled and the min term then see the same activation (eddoursul/Strata measured 1.1-1.2% -// against 1.9% relative error per expert). Result: sumi * (d5 * d8) + sumu * (m5 * d8). -// Q5_0: llama.cpp's integer chain verbatim (vecdotq.cuh vec_dot_q5_0_q8_1_impl) -- symmetric (one delta, no -// learned min), so unlike Q5_1 there is no min-term rounding choice to make: the constant -16 per-weight offset -// is accounted for via the q8_1 block's `ds.y` (sum of the ORIGINAL activations), exactly as upstream. -__device__ __forceinline__ float vec_dot_q5_0_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, - const int& kbx, const int& iqs) { - const block_q5_0* bq5_0 = (const block_q5_0*) vbq + kbx; - int sumi = 0; -#pragma unroll - for (int i = 0; i < VDR_Q5_0; ++i) { - const int vl = get_int_b2(bq5_0->qs, iqs + i); - const int vh = get_int_b2(bq5_0->qh, 0) >> (4 * (iqs + i)); - const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI5_0); - int vi0 = (vl >> 0) & 0x0F0F0F0F; - vi0 |= (vh << 4) & 0x00000010; - vi0 |= (vh << 11) & 0x00001000; - vi0 |= (vh << 18) & 0x00100000; - vi0 |= (vh << 25) & 0x10000000; - sumi = ggml_cuda_dp4a(vi0, u0, sumi); - int vi1 = (vl >> 4) & 0x0F0F0F0F; - vi1 |= (vh >> 12) & 0x00000010; - vi1 |= (vh >> 5) & 0x00001000; - vi1 |= (vh << 2) & 0x00100000; - vi1 |= (vh << 9) & 0x10000000; - sumi = ggml_cuda_dp4a(vi1, u1, sumi); - } - const float d5 = __half2float(bq5_0->d); - const float d8 = __low2float(bq8_1->ds); - const float s8 = __high2float(bq8_1->ds); - return d5 * (sumi * d8 - (16.0f * VDR_Q5_0 / QI5_0) * s8); -} -__device__ __forceinline__ float vec_dot_q5_1_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, - const int& kbx, const int& iqs) { - const block_q5_1* bq5_1 = (const block_q5_1*) vbq + kbx; - int sumi = 0, sumu = 0; -#pragma unroll - for (int i = 0; i < VDR_Q5_1; ++i) { - const int vl = get_int_b4(bq5_1->qs, iqs + i); - const int vh = get_int_b4(bq5_1->qh, 0) >> (4 * (iqs + i)); - const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI5_1); - int vi0 = (vl >> 0) & 0x0F0F0F0F; - vi0 |= (vh << 4) & 0x00000010; - vi0 |= (vh << 11) & 0x00001000; - vi0 |= (vh << 18) & 0x00100000; - vi0 |= (vh << 25) & 0x10000000; - sumi = ggml_cuda_dp4a(vi0, u0, sumi); - int vi1 = (vl >> 4) & 0x0F0F0F0F; - vi1 |= (vh >> 12) & 0x00000010; - vi1 |= (vh >> 5) & 0x00001000; - vi1 |= (vh << 2) & 0x00100000; - vi1 |= (vh << 9) & 0x10000000; - sumi = ggml_cuda_dp4a(vi1, u1, sumi); - sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu)); - } - const float2 dm5 = __half22float2(bq5_1->dm); - const float d8 = __low2float(bq8_1->ds); - return sumi * (dm5.x * d8) + sumu * (dm5.y * d8); -} -__device__ __forceinline__ float vec_dot_q8_0_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, - const int& kbx, const int& iqs) { - const block_q8_0* bq8_0 = (const block_q8_0*) vbq + kbx; - int sumi = 0; -#pragma unroll - for (int i = 0; i < VDR_Q8_0; ++i) - sumi = ggml_cuda_dp4a(get_int_b2(bq8_0->qs, iqs + i), get_int_b4(bq8_1->qs, iqs + i), sumi); - const float d8_0 = __half2float(bq8_0->d), d8_1 = __low2float(bq8_1->ds); - return d8_0 * d8_1 * ((float) sumi); -} - -// ---------------------------------------------------------------- the formats -// qk = values per block, ipb = dot calls per block (qi / vdr), step = the iqs stride between calls. -template struct Fmt; -template<> struct Fmt<16> { static constexpr int qk = 256, ipb = 8, step = 2; - __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq2_xxs_q8_1(v, y, kbx, iqs); } }; -template<> struct Fmt<17> { static constexpr int qk = 256, ipb = 8, step = 2; - __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq2_xs_q8_1(v, y, kbx, iqs); } }; -template<> struct Fmt<18> { static constexpr int qk = 256, ipb = 8, step = 2; - __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq3_xxs_q8_1(v, y, kbx, iqs); } }; -template<> struct Fmt<20> { static constexpr int qk = 32, ipb = 2, step = 2; - __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq4_nl_q8_1(v, y, kbx, iqs); } }; -template<> struct Fmt<21> { static constexpr int qk = 256, ipb = 8, step = 2; - __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq3_s_q8_1(v, y, kbx, iqs); } }; -template<> struct Fmt<23> { static constexpr int qk = 256, ipb = 8, step = 4; - __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq4_xs_q8_1(v, y, kbx, iqs); } }; -template<> struct Fmt<22> { static constexpr int qk = 256, ipb = 8, step = 2; - __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq2_s_q8_1(v, y, kbx, iqs); } }; -template<> struct Fmt<29> { static constexpr int qk = 256, ipb = 8, step = 1; - __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq1_m_q8_1(v, y, kbx, iqs); } }; -template<> struct Fmt<42> { static constexpr int qk = 64, ipb = 2, step = 1; - __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q2_0_q8_1(v, y, kbx, iqs); } }; -template<> struct Fmt<12> { static constexpr int qk = 256, ipb = QI4_K / VDR_Q4_K, step = VDR_Q4_K; - __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; - __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_0_q8_1(v, y, kbx, iqs); } }; -template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0, step = VDR_Q8_0; - __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q8_0_q8_1(v, y, kbx, iqs); } }; - -// The formats of each role, one list each so a type cannot be in one switch and missing from another. Every -// entry is a kernel template for each CUDA architecture of the build, hence two lists rather than one. The down -// kernels are generic in Fmt; 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 - for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); - return v; -} - -// One row against one q8_1 activation, the whole warp: call k = (block, part) is lane-strided. -template -__device__ __forceinline__ float row_dot(const uint8_t* row, const block_q8_1* x, int nb, int lane) { - using F = Fmt; - float s = 0.0f; - for (int k = lane; k < nb * F::ipb; k += 32) { - const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); - s += F::dot(row, x + kbx * (F::qk / 32), kbx, iqs); - } - return warp_sum(s); -} - -template -__global__ void __launch_bounds__(128) mmvq_kernel(const uint8_t* __restrict__ w, size_t row_bytes, - const block_q8_1* __restrict__ x, float* __restrict__ y, int n_in, - int n_out, int ncols) { - const int row = blockIdx.x * 4 + threadIdx.y; - if (row >= n_out) return; - const int lane = threadIdx.x; - const int nb = n_in / Fmt::qk; - const uint8_t* wr = w + (size_t) row * row_bytes; - for (int c = 0; c < ncols; ++c) { - const float s = row_dot(wr, x + (size_t) c * (n_in / 32), nb, lane); - if (lane == 0) y[(size_t) c * n_out + row] = s; - } -} - -// ---------------------------------------------------------------- decode once, apply to every column -// The kernels above call Fmt::dot once per (call, column): each column re-reads the weight words and redoes -// the grid lookups and sign unpacking. Here each dot is split, as native_mmvq.cu's multi-column traits are, into -// `load` (everything that depends only on the weight: the signed grid words, the integer scales, the fp16 block -// scale as a float) and `apply` (the activation loads, the dp4a chain in the same order, the same integer scale -// step and the same float expression). `apply(load(...))` does the dot's integer and float operations in the same -// 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 struct Split; -// Formats with a Split below take the decode-once kernels; the others (Q4_K, Q5_K, Q6_K, Q5_1, Q8_0: UD-Q4_K_XL) the -// per-entry ones, which call Fmt::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 inline constexpr bool kSplit = false; -template inline constexpr bool kStageIqGrid = (TY == 16 || TY == 17 || TY == 22 || TY == 29); - -template<> inline constexpr bool kSplit<16> = true; -template<> struct Split<16> { // IQ2_XXS - struct W { int g[8]; int ls; float dw; }; - template - __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) { - const block_iq2_xxs* bq2 = (const block_iq2_xxs*) vbq + kbx; - const int q2 = get_int_b2(bq2->qs, iqs); - const uint8_t* aux8 = (const uint8_t*) &q2; - const uint32_t aux32 = get_int_b2(bq2->qs, iqs + 1); - const uint2* grid_lut; - if constexpr (STAGE_GRID) grid_lut = (const uint2*) s_grid; - else grid_lut = (const uint2*) iq2xxs_grid; - W r; -#pragma unroll - for (int k0 = 0; k0 < 8; k0 += 2) { - const uint2 grid_pos = grid_lut[aux8[k0 / 2]]; - const uint32_t signs = unpack_ksigns(aux32 >> (7 * k0 / 2)); - const int signs0 = __vcmpne4(signs & 0x08040201, 0); - r.g[k0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0); - const int signs1 = __vcmpne4(signs & 0x80402010, 0); - r.g[k0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1); - } - r.ls = aux32 >> 27 | 1; - r.dw = __half2float(bq2->d); - return r; - } - __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { - int sumi = 0; -#pragma unroll - for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi); - sumi = sumi * r.ls / 8; - const float d = r.dw * __low2float(bq8_1[iqs / 2].ds); - return d * sumi; - } -}; -// IQ2_XS and IQ2_S share the apply: two half sums, two 4-bit scales -struct SplitLs2 { - struct W { int g[8]; int ls0, ls1; float dw; }; - __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { - int sumi0 = 0, sumi1 = 0; -#pragma unroll - for (int j = 0; j < 4; ++j) sumi0 = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi0); -#pragma unroll - for (int j = 4; j < 8; ++j) sumi1 = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi1); - const int sumi = (sumi0 * r.ls0 + sumi1 * r.ls1 + (sumi0 + sumi1) / 2) / 4; - const float d = r.dw * __low2float(bq8_1[iqs / 2].ds); - return d * sumi; - } -}; -template<> inline constexpr bool kSplit<17> = true; -template<> struct Split<17> : SplitLs2 { // IQ2_XS - template - __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) { - const block_iq2_xs* bq2 = (const block_iq2_xs*) vbq + kbx; - const int2 q2_packed = make_int2(get_int_b2(bq2->qs, iqs + 0), get_int_b2(bq2->qs, iqs + 1)); - const uint16_t* q2 = (const uint16_t*) &q2_packed; - const uint2* grid_lut; - if constexpr (STAGE_GRID) grid_lut = (const uint2*) s_grid; - else grid_lut = (const uint2*) iq2xs_grid; - W r; - r.ls0 = bq2->scales[iqs / 2] & 0x0F; - r.ls1 = bq2->scales[iqs / 2] >> 4; -#pragma unroll - for (int l0 = 0; l0 < 8; l0 += 2) { - const uint2 grid_pos = grid_lut[q2[l0 / 2] & 0x1FF]; - const uint32_t signs = unpack_ksigns(q2[l0 / 2] >> 9); - const int signs0 = __vcmpne4(signs & 0x08040201, 0); - r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0); - const int signs1 = __vcmpne4(signs & 0x80402010, 0); - r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1); - } - r.dw = __half2float(bq2->d); - return r; - } -}; -template<> inline constexpr bool kSplit<22> = true; -template<> struct Split<22> : SplitLs2 { // IQ2_S - template - __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) { - const block_iq2_s* bq2 = (const block_iq2_s*) vbq + kbx; - const int qs_packed = get_int_b2(bq2->qs, iqs / 2); - const uint8_t* qs = (const uint8_t*) &qs_packed; - const int qh = bq2->qh[iqs / 2]; - const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2); - const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32; - const uint64_t* grid_lut; - if constexpr (STAGE_GRID) grid_lut = (const uint64_t*) s_grid; - else grid_lut = iq2s_grid; - W r; - r.ls0 = bq2->scales[iqs / 2] & 0x0F; - r.ls1 = bq2->scales[iqs / 2] >> 4; -#pragma unroll - for (int l0 = 0; l0 < 8; l0 += 2) { - const int* grid_pos = (const int*) (grid_lut + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300))); - const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000); - const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000); - r.g[l0 + 0] = __vsub4(grid_pos[0] ^ signs0, signs0); - r.g[l0 + 1] = __vsub4(grid_pos[1] ^ signs1, signs1); - } - r.dw = __half2float(bq2->d); - return r; - } -}; -template<> inline constexpr bool kSplit<18> = true; -template<> struct Split<18> { // IQ3_XXS - struct W { int g[8]; int ls; float dw; }; - template - __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) { - const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx; - const int2 q3_packed = make_int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1)); - const uint8_t* q3 = (const uint8_t*) &q3_packed; - const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2); - W r; -#pragma unroll - for (int l0 = 0; l0 < 8; l0 += 2) { - const int2 grid_pos = make_int2(iq3xxs_grid[q3[l0 + 0]], iq3xxs_grid[q3[l0 + 1]]); - const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2)); - const int signs0 = __vcmpne4(signs & 0x08040201, 0); - r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0); - const int signs1 = __vcmpne4(signs & 0x80402010, 0); - r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1); - } - r.ls = aux32 >> 28; - r.dw = __half2float(bq3->d); - return r; - } - __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { - int sumi = 0; -#pragma unroll - for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi); - sumi = (r.ls * sumi + sumi / 2) / 2; - const float d = r.dw * __low2float(bq8_1[iqs / 2].ds); - return d * sumi; - } -}; -template<> inline constexpr bool kSplit<21> = true; -template<> struct Split<21> { // IQ3_S - struct W { int g[8]; int ls; float dw; }; - template - __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) { - const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx; - const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1)); - const uint8_t* qs = (const uint8_t*) &qs_packed; - const int qh = bq3->qh[iqs / 2]; - const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2); - const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32; - W r; -#pragma unroll - for (int l0 = 0; l0 < 8; l0 += 2) { - const int2 grid_pos = make_int2(iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)], - iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]); - const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000); - const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000); - r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0); - r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1); - } - r.ls = 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F); - r.dw = __half2float(bq3->d); - return r; - } - __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { - int sumi = 0; -#pragma unroll - for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi); - sumi *= r.ls; - const float d = r.dw * __low2float(bq8_1[iqs / 2].ds); - return d * sumi; - } -}; -template<> inline constexpr bool kSplit<29> = true; -template<> struct Split<29> { // IQ1_M - struct W { int g[8]; float delta[4]; int sc0, sc1; float dw; }; - template - __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) { - const block_iq1_m* bq1 = (const block_iq1_m*) vbq + kbx; - const int qs_packed = get_int_b4(bq1->qs, iqs); - const uint8_t* qs = (const uint8_t*) &qs_packed; - const uint32_t* grid_lut; - if constexpr (STAGE_GRID) grid_lut = s_grid; - else grid_lut = iq1s_grid_gpu; - W r; -#pragma unroll - for (int l0 = 0; l0 < 8; l0 += 2) { - const int qhl = bq1->qh[2 * iqs + l0 / 4] >> (4 * ((l0 / 2) % 2)); - const int grid = grid_lut[qs[l0 / 2] | ((qhl & 0x07) << 8)]; - r.g[l0 + 0] = (grid >> 0) & 0x0F0F0F0F; - r.g[l0 + 1] = (grid >> 4) & 0x0F0F0F0F; - r.delta[l0 / 2] = -1.0f + IQ1M_DELTA - (qhl & 0x08) * (2.0f * IQ1M_DELTA / 0x08); - } - const uint16_t* sc = (const uint16_t*) bq1->scales; - iq1m_scale_t scale; - scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00F0) | ((sc[2] >> 4) & 0x0F00) | (sc[3] & 0xF000); - r.dw = __half2float(scale.f16); - const int tmp = sc[iqs / 2] >> (6 * (iqs % 2)); - r.sc0 = 2 * ((tmp >> 0) & 0x07) + 1; - r.sc1 = 2 * ((tmp >> 3) & 0x07) + 1; - return r; - } - __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { - int sumi[2] = {0, 0}; - float sumf[2] = {0.0f, 0.0f}; -#pragma unroll - for (int l0 = 0; l0 < 8; l0 += 2) { - const int u0 = get_int_b4(bq8_1[iqs].qs, l0 + 0); - const int u1 = get_int_b4(bq8_1[iqs].qs, l0 + 1); - sumi[l0 / 4] = ggml_cuda_dp4a(r.g[l0 + 0], u0, sumi[l0 / 4]); - sumi[l0 / 4] = ggml_cuda_dp4a(r.g[l0 + 1], u1, sumi[l0 / 4]); - int sumy = 0; - sumy = ggml_cuda_dp4a(u0, 0x01010101, sumy); - sumy = ggml_cuda_dp4a(u1, 0x01010101, sumy); - sumf[l0 / 4] += r.delta[l0 / 2] * sumy; - } - const float d = r.dw * __low2float(bq8_1[iqs].ds); - return d * ((sumi[0] + sumf[0]) * r.sc0 + (sumi[1] + sumf[1]) * r.sc1); - } -}; -template<> inline constexpr bool kSplit<20> = true; -template<> struct Split<20> { // IQ4_NL - struct W { int2 v[2]; float dw; }; - template - __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) { - const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx; - W r; -#pragma unroll - for (int l = 0; l < 2; ++l) r.v[l] = get_int_from_table_16(get_int_b2(bq4->qs, iqs + l), kvalues_iq4nl); - r.dw = __half2float(bq4->d); - return r; - } - __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { - const int* q8 = (const int*) bq8_1->qs + iqs; - int sumi = 0; -#pragma unroll - for (int l = 0; l < 2; ++l) { - sumi = ggml_cuda_dp4a(r.v[l].x, q8[l + 0], sumi); - sumi = ggml_cuda_dp4a(r.v[l].y, q8[l + 4], sumi); - } - const float d = r.dw * __low2float(bq8_1->ds); - return d * sumi; - } -}; -template<> inline constexpr bool kSplit<23> = true; -template<> struct Split<23> { // IQ4_XS - struct W { int2 v[4]; int ls; float dw; }; - template - __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) { - const block_iq4_xs* bq4 = (const block_iq4_xs*) vbq + kbx; - W r; -#pragma unroll - for (int j = 0; j < 4; ++j) r.v[j] = get_int_from_table_16(get_int_b4(bq4->qs, iqs + j), kvalues_iq4nl); - r.ls = ((bq4->scales_l[iqs / 8] >> (iqs & 0x04)) & 0x0F) | (((bq4->scales_h >> (iqs / 2)) & 0x03) << 4); - r.dw = __half2float(bq4->d); - return r; - } - __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { - int sumi = 0; -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int u0 = get_int_b4(bq8_1[iqs / 4].qs, j + 0); - const int u1 = get_int_b4(bq8_1[iqs / 4].qs, j + 4); - sumi = ggml_cuda_dp4a(r.v[j].x, u0, sumi); - sumi = ggml_cuda_dp4a(r.v[j].y, u1, sumi); - } - sumi *= r.ls - 32; - const float d = r.dw * __low2float(bq8_1[iqs / 4].ds); - return d * sumi; - } -}; -template<> inline constexpr bool kSplit<42> = true; -template<> struct Split<42> { // Q2_0 - struct W { int qx[4], qy[4]; float d2; }; - template - __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) { - const block_q2_0* bq2_0 = (const block_q2_0*) vbq + kbx; - W r; - r.d2 = bq2_0->d; - const int16_t* qs = (const int16_t*) bq2_0->qs + iqs * 4; -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int q = qs[j]; - const int qe = __byte_perm(0x020100FF, 0x020100FF, q >> 0); - const int qo = __byte_perm(0x020100FF, 0x020100FF, q >> 2); - r.qx[j] = __byte_perm(qe, qo, 0x5140); - r.qy[j] = __byte_perm(qe, qo, 0x7362); - } - return r; - } - __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { - const block_q8_1* bq8_1_chunk = bq8_1 + iqs; - int sumi = 0; -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int u = get_int_b4(bq8_1_chunk->qs, j * 2 + 0); - const int v = get_int_b4(bq8_1_chunk->qs, j * 2 + 1); - sumi = ggml_cuda_dp4a(u, r.qx[j], sumi); - sumi = ggml_cuda_dp4a(v, r.qy[j], sumi); - } - const float d8 = __low2float(bq8_1_chunk->ds); - return r.d2 * d8 * sumi; - } -}; - -// One row against the n <= NC activations x + off[0..n) (n >= 1, warp-uniform; offsets in q8_1 blocks, 32-bit to -// spare registers), the whole warp. Per activation this is row_dot: the same calls k, lane-strided the same way, -// summed in the same order, then the same warp_sum. Only the weight side moves out of the per-activation loop. -template -__device__ __forceinline__ void row_dot_multi(const uint8_t* row, const block_q8_1* x, const int (&off)[NC], int n, - int nb, int lane, float (&s)[NC], const uint32_t* __restrict__ s_grid = nullptr) { - using F = Fmt; - using S = Split; -#pragma unroll - for (int c = 0; c < NC; ++c) s[c] = 0.0f; - for (int k = lane; k < nb * F::ipb; k += 32) { - const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); - const typename S::W w = S::template load(row, kbx, iqs, s_grid); -#pragma unroll - for (int c = 0; c < NC; ++c) - if (EXACT_N || c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs); - } -#pragma unroll - for (int c = 0; c < NC; ++c) - if (EXACT_N || c < n) s[c] = warp_sum(s[c]); -} - -// 8-lane sub-warp row dot for K = nb * ipb == 40 (TD == 20, IQ4_NL with n_ff == 640): -// 4 rows per warp (32 rows per 256-thread block), 100% active lanes, bitwise identical addition tree to row_dot_multi. -template -__device__ __forceinline__ void row_dot_40_sub8(const uint8_t* row, const block_q8_1* x, const int (&off)[NC], int n, - int t, float (&s)[NC]) { - using F = Fmt; - using S = Split; -#pragma unroll - for (int c = 0; c < NC; ++c) s[c] = 0.0f; - for (int k = t; k < 40; k += 32) { - const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); - const typename S::W w = S::load(row, kbx, iqs); -#pragma unroll - for (int c = 0; c < NC; ++c) - if (EXACT_N || c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs); - } - { - const int k = t + 16, kbx = k / F::ipb, iqs = F::step * (k % F::ipb); - const typename S::W w = S::load(row, kbx, iqs); -#pragma unroll - for (int c = 0; c < NC; ++c) { - if (EXACT_N || c < n) { - float s16 = 0.0f; - s16 += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs); - s[c] = __fadd_rn(s[c], s16); - } - } - } - float s8[NC]; -#pragma unroll - for (int c = 0; c < NC; ++c) s8[c] = 0.0f; - { - const int k = t + 8, kbx = k / F::ipb, iqs = F::step * (k % F::ipb); - const typename S::W w = S::load(row, kbx, iqs); -#pragma unroll - for (int c = 0; c < NC; ++c) - if (EXACT_N || c < n) s8[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs); - } - { - const int k = t + 24, kbx = k / F::ipb, iqs = F::step * (k % F::ipb); - const typename S::W w = S::load(row, kbx, iqs); -#pragma unroll - for (int c = 0; c < NC; ++c) { - if (EXACT_N || c < n) { - float s24 = 0.0f; - s24 += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs); - s[c] = __fadd_rn(s[c], __fadd_rn(s8[c], s24)); - } - } - } -#pragma unroll - for (int c = 0; c < NC; ++c) { - if (EXACT_N || c < n) { -#pragma unroll - for (int o = 4; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o); - } - } -} - -// 16-lane sub-warp row dot for K = nb * ipb == 20 (TD == 42, Q2_0 with n_ff == 640): -// 2 rows per warp (16 rows per 256-thread block), bitwise identical addition tree to row_dot_multi. -template -__device__ __forceinline__ void row_dot_20_sub16(const uint8_t* row, const block_q8_1* x, const int (&off)[NC], int n, - int t, float (&s)[NC]) { - using F = Fmt; - using S = Split; -#pragma unroll - for (int c = 0; c < NC; ++c) s[c] = 0.0f; - { - const int k = t, kbx = k / F::ipb, iqs = F::step * (k % F::ipb); - const typename S::W w = S::load(row, kbx, iqs); -#pragma unroll - for (int c = 0; c < NC; ++c) - if (EXACT_N || c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs); - } - float s16[NC]; -#pragma unroll - for (int c = 0; c < NC; ++c) s16[c] = 0.0f; - if (t < 4) { - const int k = t + 16, kbx = k / F::ipb, iqs = F::step * (k % F::ipb); - const typename S::W w = S::load(row, kbx, iqs); -#pragma unroll - for (int c = 0; c < NC; ++c) - if (EXACT_N || c < n) s16[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs); - } -#pragma unroll - for (int c = 0; c < NC; ++c) { - if (EXACT_N || c < n) { - s[c] = __fadd_rn(s[c], s16[c]); -#pragma unroll - for (int o = 8; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o); - } - } -} - -template> -__device__ __forceinline__ const uint32_t* stage_iq_grid(uint32_t* s_buf, int tid, int nthreads) { - if constexpr (!STAGE_GRID) { - return nullptr; - } else if constexpr (TY == 16) { - uint2* dst = (uint2*) s_buf; - const uint2* src = (const uint2*) iq2xxs_grid; - for (int i = tid; i < 256; i += nthreads) dst[i] = src[i]; - __syncthreads(); - return s_buf; - } else if constexpr (TY == 17) { - uint2* dst = (uint2*) s_buf; - const uint2* src = (const uint2*) iq2xs_grid; - for (int i = tid; i < 512; i += nthreads) dst[i] = src[i]; - __syncthreads(); - return s_buf; - } else if constexpr (TY == 22) { - uint2* dst = (uint2*) s_buf; - const uint2* src = (const uint2*) iq2s_grid; - for (int i = tid; i < 1024; i += nthreads) dst[i] = src[i]; - __syncthreads(); - return s_buf; - } else if constexpr (TY == 29) { - uint2* dst = (uint2*) s_buf; - const uint2* src = (const uint2*) iq1s_grid_gpu; - for (int i = tid; i < 1024; i += nthreads) dst[i] = src[i]; - __syncthreads(); - return s_buf; - } else { - return nullptr; - } -} - -template> -struct IqGridWords { - static constexpr int value = !STAGE_GRID ? 4 : (TY == 22 || TY == 29) ? 2048 : (TY == 17) ? 1024 : (TY == 16) ? 512 : 4; -}; - -// mmvq_kernel with the columns taken NC at a time. After warp_sum every lane holds the same sum, so lane c stores -// column c. -template> -__global__ void __launch_bounds__(128) mmvq_multi_kernel(const uint8_t* __restrict__ w, size_t row_bytes, - const block_q8_1* __restrict__ x, float* __restrict__ y, - int n_in, int n_out, int ncols) { - __shared__ alignas(16) uint32_t s_grid_buf[IqGridWords::value]; - const uint32_t* s_grid = stage_iq_grid(s_grid_buf, threadIdx.y * 32 + threadIdx.x, 128); - const int row = blockIdx.x * 4 + threadIdx.y; - if (row >= n_out) return; - const int lane = threadIdx.x; - const int nb = n_in / Fmt::qk, xb = n_in / 32; - const uint8_t* wr = w + (size_t) row * row_bytes; - for (int c0 = 0; c0 < ncols; c0 += NC) { - const int n = min(NC, ncols - c0); - int off[NC]; -#pragma unroll - for (int c = 0; c < NC; ++c) off[c] = (c0 + min(c, n - 1)) * xb; - float s[NC]; - row_dot_multi(wr, x, off, n, nb, lane, s, s_grid); -#pragma unroll - for (int c = 0; c < NC; ++c) - if (c < n && lane == c) y[(size_t) (c0 + c) * n_out + row] = s[c]; - } -} - -// ---------------------------------------------------------------- grouped native experts -constexpr int GU_ROWS = 8; // rows per block (one warp each) - -// Group g is computed by block row g % gridDim.y: rows y, y + gridDim.y, ... < *n_groups. The callers size the -// launch for the most groups a call can have (cap: every entry its own expert), but the count is only known on the -// device, and a verify window's PCIe call usually has no group at all: with one block row per possible group every -// unused one was cap x (2 n_ff / 8 + n_embd / 8) blocks that started only to return. A smaller gridDim.y strides -// instead. Each group's rows are computed by the same warp code in the same order either way, so the results do -// not depend on gridDim.y (gridDim.y = cap_groups is the one-row-per-group launch). -template -__global__ void __launch_bounds__(256) native_gu_kernel(const unsigned long long* __restrict__ grp_ptr, - const int32_t* __restrict__ grp_start, - const int32_t* __restrict__ n_groups, - const int32_t* __restrict__ ent_tok, - const block_q8_1* __restrict__ xq, NativeExpertLayout L, - float* __restrict__ gate, float* __restrict__ up) { - const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; - const int row = blockIdx.x * GU_ROWS + warp; // 0 .. 2*n_ff - if (row >= 2 * L.n_ff) return; - const bool is_up = row >= L.n_ff; - const int r = is_up ? row - (int) L.n_ff : row; - const size_t off = (is_up ? L.up_off : 0) + (size_t) r * L.gu_row; - const int nb = (int) (L.n_embd / Fmt::qk), xb = (int) (L.n_embd / 32); - const int ng = *n_groups; - for (int g = blockIdx.y; g < ng; g += gridDim.y) { - const uint8_t* wr = (const uint8_t*) grp_ptr[g] + off; - const int e0 = grp_start[g], e1 = grp_start[g + 1]; - for (int e = e0; e < e1; ++e) { - const float s = row_dot(wr, xq + (size_t) ent_tok[e] * xb, nb, lane); - if (lane == 0) (is_up ? up : gate)[(size_t) e * L.n_ff + r] = s; - } - } -} - -// native_gu_kernel with the group's entries taken GRP_NC at a time, each weight part decoded once per pass. -// A group has at most one entry per token of the window (kVerifyMaxT = 8; setup writes --spec 4, and a split window -// has halves of <= 4), so 4 takes such windows in one pass; 8 would take ~64-80 registers against ~48 (ptxas -v). -constexpr int GRP_NC = 4; - -template> -__global__ void __launch_bounds__(256) native_gu_multi_kernel(const unsigned long long* __restrict__ grp_ptr, - const int32_t* __restrict__ grp_start, - const int32_t* __restrict__ n_groups, - const int32_t* __restrict__ ent_tok, - const block_q8_1* __restrict__ xq, NativeExpertLayout L, - float* __restrict__ gate, float* __restrict__ up) { - const int ng = *n_groups; - if (blockIdx.y >= ng) return; - __shared__ alignas(16) uint32_t s_grid_buf[IqGridWords::value]; - const uint32_t* s_grid = stage_iq_grid(s_grid_buf, threadIdx.x, 256); - const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; - const int row = blockIdx.x * GU_ROWS + warp; // 0 .. 2*n_ff - if (row >= 2 * L.n_ff) return; - const bool is_up = row >= L.n_ff; - const int r = is_up ? row - (int) L.n_ff : row; - const size_t w_off = (is_up ? L.up_off : 0) + (size_t) r * L.gu_row; - const int nb = (int) (L.n_embd / Fmt::qk), xb = (int) (L.n_embd / 32); - float* dst = is_up ? up : gate; - for (int g = blockIdx.y; g < ng; g += gridDim.y) { // the group stride, as native_gu_kernel - const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off; - const int e0 = grp_start[g], e1 = grp_start[g + 1]; - for (int e = e0; e < e1; e += GRP_NC) { - const int n = min(GRP_NC, e1 - e); - if (n == 1) { - const int off1[1] = { ent_tok[e] * xb }; - float s1[1]; - row_dot_multi(wr, xq, off1, 1, nb, lane, s1, s_grid); - if (lane == 0) dst[(size_t) e * L.n_ff + r] = s1[0]; - } else if (n == 2) { - const int off2[2] = { ent_tok[e] * xb, ent_tok[e + 1] * xb }; - float s2[2]; - row_dot_multi(wr, xq, off2, 2, nb, lane, s2, s_grid); - if (lane < 2) dst[(size_t) (e + lane) * L.n_ff + r] = s2[lane]; - } else { - int off[GRP_NC]; -#pragma unroll - for (int c = 0; c < GRP_NC; ++c) off[c] = ent_tok[e + min(c, n - 1)] * xb; - float s[GRP_NC]; - row_dot_multi(wr, xq, off, n, nb, lane, s, s_grid); -#pragma unroll - for (int c = 0; c < GRP_NC; ++c) - if (c < n && lane == c) dst[(size_t) (e + c) * L.n_ff + r] = s[c]; - } - } - } -} - -__global__ void swiglu_entries_kernel(const float* __restrict__ gate, const float* __restrict__ up, float* __restrict__ h, - long long n) { - const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n) return; - const float g = gate[i]; - h[i] = (g / (1.0f + __expf(-g))) * up[i]; -} - -template -__global__ void __launch_bounds__(256) native_down_kernel(const unsigned long long* __restrict__ grp_ptr, - const int32_t* __restrict__ grp_start, - const int32_t* __restrict__ n_groups, - const int32_t* __restrict__ ent_dst, - const block_q8_1* __restrict__ hq, NativeExpertLayout L, - float* __restrict__ out) { - const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; - const int r = blockIdx.x * 8 + warp; - if (r >= L.n_embd) return; - const size_t off = L.down_off + (size_t) r * L.d_row; - const int nb = (int) (L.n_ff / Fmt::qk), hb = (int) (L.n_ff / 32); - const int ng = *n_groups; - for (int g = blockIdx.y; g < ng; g += gridDim.y) { // as native_gu_kernel - const uint8_t* wr = (const uint8_t*) grp_ptr[g] + off; - const int e0 = grp_start[g], e1 = grp_start[g + 1]; - for (int e = e0; e < e1; ++e) { - const float s = row_dot(wr, hq + (size_t) e * hb, nb, lane); - if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s; - } - } -} - -// native_down_kernel with the entries taken GRP_NC at a time -template -__global__ void __launch_bounds__(256) native_down_multi_kernel(const unsigned long long* __restrict__ grp_ptr, - const int32_t* __restrict__ grp_start, - const int32_t* __restrict__ n_groups, - const int32_t* __restrict__ ent_dst, - const block_q8_1* __restrict__ hq, NativeExpertLayout L, - float* __restrict__ out) { - const int ng = *n_groups; - if (blockIdx.y >= ng) return; - __shared__ uint32_t s_hq_buf[GRP_NC * 20 * 9]; - const int nb = (int) (L.n_ff / Fmt::qk), hb = (int) (L.n_ff / 32); - if constexpr (TD == 20) { - if (hb == 20) { - const int r = blockIdx.x * 32 + (threadIdx.x >> 3); - const int t = threadIdx.x & 7; - const bool valid_r = (r < L.n_embd); - const size_t w_off = L.down_off + (size_t) (valid_r ? r : 0) * L.d_row; - const block_q8_1* s_hq = reinterpret_cast(s_hq_buf); - for (int g = blockIdx.y; g < ng; g += gridDim.y) { - const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off; - const int e0 = grp_start[g], e1 = grp_start[g + 1]; - for (int e = e0; e < e1; e += GRP_NC) { - const int n = min(GRP_NC, e1 - e); - const uint32_t* src = reinterpret_cast(hq + (size_t) e * 20); - const int words = n * (20 * 9); - __syncthreads(); - for (int i = threadIdx.x; i < words; i += 256) s_hq_buf[i] = src[i]; - __syncthreads(); - if (valid_r) { - if (n == 1) { - const int off1[1] = { 0 }; - float s1[1]; - row_dot_40_sub8(wr, s_hq, off1, 1, t, s1); - if (t == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0]; - } else if (n == 2) { - const int off2[2] = { 0, 20 }; - float s2[2]; - row_dot_40_sub8(wr, s_hq, off2, 2, t, s2); - if (t < 2) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s2[t]; - } else { - int off[GRP_NC]; -#pragma unroll - for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * 20; - float s[GRP_NC]; - row_dot_40_sub8(wr, s_hq, off, n, t, s); -#pragma unroll - for (int c = 0; c < GRP_NC; ++c) - if (c < n && t == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c]; - } - } - } - } - return; - } - } else if constexpr (TD == 42) { - if (hb == 20) { - const int r = blockIdx.x * 16 + (threadIdx.x >> 4); - const int t = threadIdx.x & 15; - const bool valid_r = (r < L.n_embd); - const size_t w_off = L.down_off + (size_t) (valid_r ? r : 0) * L.d_row; - const block_q8_1* s_hq = reinterpret_cast(s_hq_buf); - for (int g = blockIdx.y; g < ng; g += gridDim.y) { - const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off; - const int e0 = grp_start[g], e1 = grp_start[g + 1]; - for (int e = e0; e < e1; e += GRP_NC) { - const int n = min(GRP_NC, e1 - e); - const uint32_t* src = reinterpret_cast(hq + (size_t) e * 20); - const int words = n * (20 * 9); - __syncthreads(); - for (int i = threadIdx.x; i < words; i += 256) s_hq_buf[i] = src[i]; - __syncthreads(); - if (valid_r) { - if (n == 1) { - const int off1[1] = { 0 }; - float s1[1]; - row_dot_20_sub16(wr, s_hq, off1, 1, t, s1); - if (t == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0]; - } else if (n == 2) { - const int off2[2] = { 0, 20 }; - float s2[2]; - row_dot_20_sub16(wr, s_hq, off2, 2, t, s2); - if (t < 2) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s2[t]; - } else { - int off[GRP_NC]; -#pragma unroll - for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * 20; - float s[GRP_NC]; - row_dot_20_sub16(wr, s_hq, off, n, t, s); -#pragma unroll - for (int c = 0; c < GRP_NC; ++c) - if (c < n && t == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c]; - } - } - } - } - return; - } - } - const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; - const int r = blockIdx.x * 8 + warp; - const bool valid_r = (r < L.n_embd); - const size_t w_off = L.down_off + (size_t) (valid_r ? r : 0) * L.d_row; - for (int g = blockIdx.y; g < ng; g += gridDim.y) { // the group stride, as native_gu_kernel - const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off; - const int e0 = grp_start[g], e1 = grp_start[g + 1]; - if (hb == 20) { - const block_q8_1* s_hq = reinterpret_cast(s_hq_buf); - for (int e = e0; e < e1; e += GRP_NC) { - const int n = min(GRP_NC, e1 - e); - const uint32_t* src = reinterpret_cast(hq + (size_t) e * 20); - const int words = n * (20 * 9); - __syncthreads(); - for (int i = threadIdx.x; i < words; i += 256) s_hq_buf[i] = src[i]; - __syncthreads(); - if (valid_r) { - if (n == 1) { - const int off1[1] = { 0 }; - float s1[1]; - row_dot_multi(wr, s_hq, off1, 1, nb, lane, s1); - if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0]; - } else if (n == 2) { - const int off2[2] = { 0, 20 }; - float s2[2]; - row_dot_multi(wr, s_hq, off2, 2, nb, lane, s2); - if (lane < 2) out[(size_t) ent_dst[e + lane] * L.n_embd + r] = s2[lane]; - } else { - int off[GRP_NC]; -#pragma unroll - for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * 20; - float s[GRP_NC]; - row_dot_multi(wr, s_hq, off, n, nb, lane, s); -#pragma unroll - for (int c = 0; c < GRP_NC; ++c) - if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c]; - } - } - } - } else if (valid_r) { - for (int e = e0; e < e1; e += GRP_NC) { - const int n = min(GRP_NC, e1 - e); - int off[GRP_NC]; -#pragma unroll - for (int c = 0; c < GRP_NC; ++c) off[c] = (e + min(c, n - 1)) * hb; - float s[GRP_NC]; - row_dot_multi(wr, hq, off, n, nb, lane, s); -#pragma unroll - for (int c = 0; c < GRP_NC; ++c) - if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c]; - } - } - } -} - -// ---------------------------------------------------------------- q8_1 (quantize.cu) -// value i of a q8_1 row set (the warp holds block i / 32, lane = i % 32) -__device__ __forceinline__ void q8_1_store(const float xi, block_q8_1* __restrict__ y, const long long i) { - float amax = fabsf(xi), sum = xi; -#pragma unroll - for (int o = 16; o > 0; o >>= 1) { - amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); - sum += __shfl_xor_sync(0xffffffffu, sum, o); - } - const float d = q8_1_finite(amax / 127.0f); // #606: q8_1_finite.hpp - the same bits for every finite block - const int8_t q = q8_1_quant(xi, d, amax); - const long long ib = i / 32, iqs = i % 32; - y[ib].qs[iqs] = q; - if (iqs == 0) y[ib].ds = q8_1_ds(d, sum); -} - -__global__ void quantize_q8_1_kernel(const float* __restrict__ x, block_q8_1* __restrict__ y, long long n) { - const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n) return; - q8_1_store(x[i], y, i); -} - -// swiglu_entries_kernel and quantize_q8_1_kernel in one pass, over the call's own entries only: -// [grp_start[0], grp_start[*n_groups]) (a call's entries are contiguous; the verify window's PCIe call starts after -// its VRAM call) instead of all cap_entries twice - nothing reads the others: the down kernel reads its groups'. -// n_ff is a multiple of 32, so a warp is one q8_1 block and the bounds are warp-uniform. The values are the two -// kernels': the SwiGLU product is rounded on its own - it must not contract into the first add of q8_1_store's block -// sum, as it could not when it went through memory (CUDA: __fmul_rn; HIP's __fmul_rn is a plain product, so there -// the product is written here under contract(off)) - then q8_1_store unchanged: the same blocks, bit for bit. -__global__ void __launch_bounds__(256) swiglu_q8_1_entries_kernel(const float* __restrict__ gate, - const float* __restrict__ up, - const int32_t* __restrict__ grp_start, - const int32_t* __restrict__ n_groups, int n_ff, - block_q8_1* __restrict__ hq) { -#if defined(__HIPCC__) -#pragma clang fp contract(off) -#endif - const long long lo = (long long) grp_start[0] * n_ff, hi = (long long) grp_start[*n_groups] * n_ff; - for (long long i = lo + (long long) blockIdx.x * blockDim.x + threadIdx.x; i < hi; - i += (long long) gridDim.x * blockDim.x) { - const float g = gate[i]; -#if defined(__HIPCC__) - const float h = (g / (1.0f + __expf(-g))) * up[i]; -#else - const float h = __fmul_rn(g / (1.0f + __expf(-g)), up[i]); -#endif - q8_1_store(h, hq, i); - } -} - -// ---------------------------------------------------------------- dequant (dequantize.cuh) -template __device__ __forceinline__ dst_t cvt(float v); -template<> __device__ __forceinline__ float cvt(float v) { return v; } -template<> __device__ __forceinline__ __half cvt<__half>(float v) { return __float2half(v); } - -template -__device__ void dq_iq2_xxs(const void* vx, int64_t ibs, dst_t* yy, int tid) { - const block_iq2_xxs* x = (const block_iq2_xxs*) vx; - const int64_t il = tid / 8, ib = tid % 8; - dst_t* y = yy + 32 * ib + 8 * il; - const uint16_t* q2 = x[ibs].qs + 4 * ib; - const uint8_t* aux8 = (const uint8_t*) q2; - const uint8_t* grid = (const uint8_t*) (iq2xxs_grid + aux8[il]); - const uint32_t aux32 = q2[2] | (q2[3] << 16); - const float d = (float) x[ibs].d * (0.5f + (aux32 >> 28)) * 0.25f; - const uint8_t signs = ksigns_iq2xs[(aux32 >> 7 * il) & 127]; - for (int j = 0; j < 8; ++j) y[j] = cvt(d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f)); -} -template -__device__ void dq_iq2_xs(const void* vx, int64_t ibs, dst_t* yy, int tid) { - const block_iq2_xs* x = (const block_iq2_xs*) vx; - const int64_t il = tid / 8, ib = tid % 8; - dst_t* y = yy + 32 * ib + 8 * il; - const uint16_t* q2 = x[ibs].qs + 4 * ib; - const uint8_t* grid = (const uint8_t*) (iq2xs_grid + (q2[il] & 511)); - const float d = (float) x[ibs].d * (0.5f + ((x[ibs].scales[ib] >> 4 * (il / 2)) & 0xf)) * 0.25f; - const uint8_t signs = ksigns_iq2xs[q2[il] >> 9]; - for (int j = 0; j < 8; ++j) y[j] = cvt(d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f)); -} -template -__device__ void dq_iq2_s(const void* vx, int64_t ibs, dst_t* yy, int tid) { - const block_iq2_s* x = (const block_iq2_s*) vx; - const int64_t il = tid / 8, ib = tid % 8; - dst_t* y = yy + 32 * ib + 8 * il; - const uint8_t* grid = (const uint8_t*) (iq2s_grid + (x[ibs].qs[4 * ib + il] | ((x[ibs].qh[ib] << (8 - 2 * il)) & 0x300))); - const float d = (float) x[ibs].d * (0.5f + ((x[ibs].scales[ib] >> 4 * (il / 2)) & 0xf)) * 0.25f; - const uint8_t signs = x[ibs].qs[QK_K / 8 + 4 * ib + il]; - for (int j = 0; j < 8; ++j) y[j] = cvt(d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f)); -} -template -__device__ void dq_iq3_xxs(const void* vx, int64_t ibs, dst_t* yy, int tid) { - const block_iq3_xxs* x = (const block_iq3_xxs*) vx; - const int64_t il = tid / 8, ib = tid % 8; - dst_t* y = yy + 32 * ib + 8 * il; - const uint8_t* q3 = x[ibs].qs + 8 * ib; - const uint16_t* gas = (const uint16_t*) (x[ibs].qs + QK_K / 4) + 2 * ib; - const uint8_t* grid1 = (const uint8_t*) (iq3xxs_grid + q3[2 * il + 0]); - const uint8_t* grid2 = (const uint8_t*) (iq3xxs_grid + q3[2 * il + 1]); - const uint32_t aux32 = gas[0] | (gas[1] << 16); - const float d = (float) x[ibs].d * (0.5f + (aux32 >> 28)) * 0.5f; - const uint8_t signs = ksigns_iq2xs[(aux32 >> 7 * il) & 127]; - for (int j = 0; j < 4; ++j) { - y[j + 0] = cvt(d * grid1[j] * (signs & kmask_iq2xs[j + 0] ? -1.f : 1.f)); - y[j + 4] = cvt(d * grid2[j] * (signs & kmask_iq2xs[j + 4] ? -1.f : 1.f)); - } -} -template -__device__ void dq_iq3_s(const void* vx, int64_t ibs, dst_t* yy, int tid) { - const block_iq3_s* x = (const block_iq3_s*) vx; - const int64_t il = tid / 8, ib = tid % 8; - dst_t* y = yy + 32 * ib + 8 * il; - const uint8_t* qs = x[ibs].qs + 8 * ib; - const uint8_t* grid1 = (const uint8_t*) (iq3s_grid + (qs[2 * il + 0] | ((x[ibs].qh[ib] << (8 - 2 * il)) & 256))); - const uint8_t* grid2 = (const uint8_t*) (iq3s_grid + (qs[2 * il + 1] | ((x[ibs].qh[ib] << (7 - 2 * il)) & 256))); - const float d = (float) x[ibs].d * (1 + 2 * ((x[ibs].scales[ib / 2] >> 4 * (ib % 2)) & 0xf)); - const uint8_t signs = x[ibs].signs[4 * ib + il]; - for (int j = 0; j < 4; ++j) { - y[j + 0] = cvt(d * grid1[j] * (signs & kmask_iq2xs[j + 0] ? -1.f : 1.f)); - y[j + 4] = cvt(d * grid2[j] * (signs & kmask_iq2xs[j + 4] ? -1.f : 1.f)); - } -} -template -__device__ void dq_iq1_m(const void* vx, int64_t ibs, dst_t* yy, int tid) { - const block_iq1_m* x = (const block_iq1_m*) vx; - const int64_t il = tid / 8, ib = tid % 8; - dst_t* y = yy + 32 * ib + 8 * il; - const uint16_t* sc = (const uint16_t*) x[ibs].scales; - iq1m_scale_t scale; - scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) | ((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000); - const int64_t ib16 = 2 * ib + il / 2; - const float d = (float) scale.f16 * (2 * ((sc[ib16 / 4] >> 3 * (ib16 % 4)) & 0x7) + 1); - const float delta = x[ibs].qh[2 * ib + il / 2] & (0x08 << 4 * (il % 2)) ? -1 - IQ1M_DELTA : -1 + IQ1M_DELTA; - uint32_t grid32[2]; - const int8_t* q = (const int8_t*) grid32; - grid32[0] = iq1s_grid_gpu[x[ibs].qs[4 * ib + il] | (((x[ibs].qh[2 * ib + il / 2] >> 4 * (il % 2)) & 7) << 8)]; - grid32[1] = (grid32[0] >> 4) & 0x0f0f0f0f; - grid32[0] &= 0x0f0f0f0f; - for (int j = 0; j < 8; ++j) y[j] = cvt(d * (q[j] + delta)); -} -template -__device__ void dq_iq4_nl(const void* vx, int64_t ibs, dst_t* yy, int tid) { - const block_iq4_nl* x = (const block_iq4_nl*) vx + ibs * (QK_K / QK4_NL); - const int64_t il = tid / 8, ib = tid % 8; - dst_t* y = yy + 32 * ib + 4 * il; - const uint8_t* q4 = x[ib].qs + 4 * il; - const float d = (float) x[ib].d; - for (int j = 0; j < 4; ++j) { - y[j + 0] = cvt(d * kvalues_iq4nl[q4[j] & 0xf]); - y[j + 16] = cvt(d * kvalues_iq4nl[q4[j] >> 4]); - } -} -// Q3_K (the Q2_0 file's token_embd): llama.cpp's dequantize_block_q3_K, its 64 threads folded onto 32 -template -__device__ void dq_q3_k(const void* vx, int64_t ibs, dst_t* yy, int tid) { - const block_q3_K* x = (const block_q3_K*) vx + ibs; - for (int tt = tid; tt < 64; tt += 32) { - const int r = tt / 4, t2 = r / 2, is0 = r % 2; - const int l0 = 16 * is0 + 4 * (tt % 4); - const int n = t2 / 4, j = t2 - 4 * n; - const uint8_t m = (uint8_t) (1 << (4 * n + j)); - const int is = 8 * n + 2 * j + is0; - const int shift = 2 * j; - const int8_t us = is < 4 ? (int8_t) ((x->scales[is - 0] & 0xF) | (((x->scales[is + 8] >> 0) & 3) << 4)) : - is < 8 ? (int8_t) ((x->scales[is - 0] & 0xF) | (((x->scales[is + 4] >> 2) & 3) << 4)) : - is < 12 ? (int8_t) ((x->scales[is - 8] >> 4) | (((x->scales[is + 0] >> 4) & 3) << 4)) : - (int8_t) ((x->scales[is - 8] >> 4) | (((x->scales[is - 4] >> 6) & 3) << 4)); - const float dl = (float) x->d * (us - 32); - dst_t* y = yy + 128 * n + 32 * j; - const uint8_t* q = x->qs + 32 * n; - const uint8_t* hm = x->hmask; - for (int l = l0; l < l0 + 4; ++l) y[l] = cvt(dl * ((int8_t) ((q[l] >> shift) & 3) - ((hm[l] & m) ? 0 : 4))); - } -} -template -__device__ void dq_iq4_xs(const void* vx, int64_t ibs, dst_t* yy, int tid) { - const block_iq4_xs* x = (const block_iq4_xs*) vx + ibs; - const int il = tid / 8, ib = tid % 8; - dst_t* y = yy + 32 * ib + 4 * il; - const uint8_t* q4 = x->qs + 16 * ib + 4 * il; - const float d = (float) x->d * ((((x->scales_l[ib / 2] >> 4 * (ib % 2)) & 0xf) | (((x->scales_h >> 2 * ib) & 3) << 4)) - 32); - for (int j = 0; j < 4; ++j) { - y[j + 0] = cvt(d * kvalues_iq4nl[q4[j] & 0xf]); - y[j + 16] = cvt(d * kvalues_iq4nl[q4[j] >> 4]); - } -} -template -__device__ void dq_q2_0(const void* vx, int64_t ibs, dst_t* yy, int tid) { - // one "superblock" = 256 values = 4 blocks of 64; thread tid writes 8 values - const block_q2_0* x = (const block_q2_0*) vx + ibs * 4; - const int b = tid / 8, part = tid % 8; // block 0..3, 8 values each - const float d = (float) x[b].d; - for (int j = 0; j < 8; ++j) { - const int i = part * 8 + j; - const int code = (x[b].qs[i / 4] >> ((i % 4) * 2)) & 3; -#if defined(__HIPCC__) && defined(__gfx1012__) && HIP_VERSION_MAJOR < 7 - // HIP 5.7 on RDNA1 folds the half path's negative scale times +0 - // to +0. Preserve the scale's sign, as the FP32/CPU paths do. - if constexpr (std::is_same_v) { - if (code == 1) { - yy[b * 64 + i] = __ushort_as_half(__half_as_ushort(x[b].d) & 0x8000u); - continue; - } - } -#endif - yy[b * 64 + i] = cvt(d * (float) (code - 1)); - } -} - -// llama.cpp's dequantize_q4_K / dequantize_q5_K (dequantize.cuh; q5_K's 64 threads folded onto 32) and the 32-value -// blocks of Q5_1 / Q8_0, 8 of them per 256-value "superblock" (thread tid writes 8 values of block tid % 8). -__device__ __forceinline__ void get_scale_min_k4(int j, const uint8_t* q, uint8_t& d, uint8_t& m) { - if (j < 4) { - d = q[j] & 63; m = q[j + 4] & 63; - } else { - d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4); - m = (q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4); - } -} -template -__device__ void dq_q4_k(const void* vx, int64_t ibs, dst_t* yy, int tid) { - const block_q4_K* x = (const block_q4_K*) vx; - const int64_t il = tid / 8, ir = tid % 8, is = 2 * il; - const int n = 4; - dst_t* y = yy + 64 * il + n * ir; - const float dall = __low2half(x[ibs].dm); - const float dmin = __high2half(x[ibs].dm); - const uint8_t* q = x[ibs].qs + 32 * il + n * ir; - uint8_t sc, m; - get_scale_min_k4((int) is + 0, x[ibs].scales, sc, m); - const float d1 = dall * sc, m1 = dmin * m; - get_scale_min_k4((int) is + 1, x[ibs].scales, sc, m); - const float d2 = dall * sc, m2 = dmin * m; - for (int l = 0; l < n; ++l) { - y[l + 0] = cvt(d1 * (q[l] & 0xF) - m1); - y[l + 32] = cvt(d2 * (q[l] >> 4) - m2); - } -} -template -__device__ void dq_q5_k(const void* vx, int64_t ibs, dst_t* yy, int tid) { - const block_q5_K* x = (const block_q5_K*) vx; - for (int tt = tid; tt < 64; tt += 32) { - const int il = tt / 16, ir = tt % 16, is = 2 * il; - dst_t* y = yy + 64 * il + 2 * ir; - const float dall = __low2half(x[ibs].dm); - const float dmin = __high2half(x[ibs].dm); - const uint8_t* ql = x[ibs].qs + 32 * il + 2 * ir; - const uint8_t* qh = x[ibs].qh + 2 * ir; - uint8_t sc, m; - get_scale_min_k4(is + 0, x[ibs].scales, sc, m); - const float d1 = dall * sc, m1 = dmin * m; - get_scale_min_k4(is + 1, x[ibs].scales, sc, m); - const float d2 = dall * sc, m2 = dmin * m; - uint8_t hm = (uint8_t) (1 << (2 * il)); - y[0] = cvt(d1 * ((ql[0] & 0xF) + (qh[0] & hm ? 16 : 0)) - m1); - y[1] = cvt(d1 * ((ql[1] & 0xF) + (qh[1] & hm ? 16 : 0)) - m1); - hm <<= 1; - y[32] = cvt(d2 * ((ql[0] >> 4) + (qh[0] & hm ? 16 : 0)) - m2); - y[33] = cvt(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 -__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(d * sc[0] * ((int8_t) ((ql[0] & 0xF) | (((qh >> 0) & 3) << 4)) - 32)); - y[32] = cvt(d * sc[2] * ((int8_t) ((ql[32] & 0xF) | (((qh >> 2) & 3) << 4)) - 32)); - y[64] = cvt(d * sc[4] * ((int8_t) ((ql[0] >> 4) | (((qh >> 4) & 3) << 4)) - 32)); - y[96] = cvt(d * sc[6] * ((int8_t) ((ql[32] >> 4) | (((qh >> 6) & 3) << 4)) - 32)); - } -} -template -__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 - const block_q5_0* x = (const block_q5_0*) vx + ibs * (QK_K / QK5_0); - const int ib = tid % 8, il = tid / 8; - const float d = __half2float(x[ib].d); - uint32_t qh; - memcpy(&qh, x[ib].qh, sizeof(qh)); - dst_t* y = yy + 32 * ib; - for (int j = 0; j < 4; ++j) { - const int iqs = 4 * il + j; - const int xh_0 = ((qh >> (iqs + 0)) << 4) & 0x10; - const int xh_1 = ((qh >> (iqs + 12))) & 0x10; - y[iqs] = cvt(((float) ((x[ib].qs[iqs] & 0xf) | xh_0) - 16.0f) * d); - y[iqs + 16] = cvt(((float) ((x[ib].qs[iqs] >> 4) | xh_1) - 16.0f) * d); - } -} -template -__device__ void dq_q5_1(const void* vx, int64_t ibs, dst_t* yy, int tid) { - const block_q5_1* x = (const block_q5_1*) vx + ibs * (QK_K / QK5_1); - const int ib = tid % 8, il = tid / 8; - const float2 dm = __half22float2(x[ib].dm); - uint32_t qh; - memcpy(&qh, x[ib].qh, sizeof(qh)); - dst_t* y = yy + 32 * ib; - for (int j = 0; j < 4; ++j) { - const int iqs = 4 * il + j; // llama.cpp's dequantize_q5_1 for value pairs iqs, iqs + 16 - const int xh_0 = ((qh >> (iqs + 0)) << 4) & 0x10; - const int xh_1 = ((qh >> (iqs + 12))) & 0x10; - y[iqs] = cvt((float) ((x[ib].qs[iqs] & 0xf) | xh_0) * dm.x + dm.y); - y[iqs + 16] = cvt((float) ((x[ib].qs[iqs] >> 4) | xh_1) * dm.x + dm.y); - } -} -template -__device__ void dq_q8_0(const void* vx, int64_t ibs, dst_t* yy, int tid) { - const block_q8_0* x = (const block_q8_0*) vx + ibs * (QK_K / QK8_0); - const int ib = tid % 8, il = tid / 8; - const float d = __half2float(x[ib].d); - dst_t* y = yy + 32 * ib + 8 * il; - for (int j = 0; j < 8; ++j) y[j] = cvt((float) x[ib].qs[8 * il + j] * d); -} - -// BF16 (the token embedding as the checkpoint ships it, tools/embd_bf16_pack.py): 8 values per thread. -template -__device__ void dq_bf16(const void* vx, int64_t ibs, dst_t* yy, int tid) { - const uint16_t* x = (const uint16_t*) vx + ibs * 256 + tid * 8; - for (int j = 0; j < 8; ++j) yy[tid * 8 + j] = cvt(__uint_as_float((uint32_t) x[j] << 16)); -} - -// Every type below must also be in is_iq() (BF16: embed_type_supported): the host entry points refuse the others, -// so the default is unreachable. -template -__device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs, dst_t* y, int tid) { - switch (ty) { - case 16: dq_iq2_xxs(vx, ibs, y, tid); break; - case 17: dq_iq2_xs(vx, ibs, y, tid); break; - case 18: dq_iq3_xxs(vx, ibs, y, tid); break; - case 20: dq_iq4_nl(vx, ibs, y, tid); break; - case 21: dq_iq3_s(vx, ibs, y, tid); break; - case 22: dq_iq2_s(vx, ibs, y, tid); break; - case 29: dq_iq1_m(vx, ibs, y, tid); break; - case 23: dq_iq4_xs(vx, ibs, y, tid); break; - case 11: dq_q3_k(vx, ibs, y, tid); break; - 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; - case 30: dq_bf16(vx, ibs, y, tid); break; - default: break; - } -} - -// flat: superblock i -> y + 256 i -template -__global__ void dequant_flat_kernel(int ty, const void* __restrict__ vx, dst_t* __restrict__ y) { - const int64_t i = blockIdx.x; - dq_dispatch(ty, vx, i, y + i * QK_K, threadIdx.x); -} -// gate/up: superblock i of a role matrix (n_embd/256 per row) -> interleaved row 2r + parity -__global__ void dequant_gu_kernel(int ty, const void* __restrict__ gate, const void* __restrict__ up, int64_t per_row, - __half* __restrict__ y) { - const int64_t i = blockIdx.x; - const int parity = blockIdx.y; - const int64_t r = i / per_row, c = i % per_row; - dq_dispatch<__half>(ty, parity ? up : gate, i, y + ((2 * r + parity) * per_row + c) * QK_K, threadIdx.x); -} - -// the types dq_dispatch dequantizes -bool is_iq(int t) { - return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11 || - t == 12 || t == 13 || t == 14 || t == 7 || t == 6 || t == 8; -} -// values per block of the types the grouped expert kernels take (0 = none) -int gu_qk(int t) { - switch (t) { -#define STRATA_QK(T) case T: return Fmt::qk; - STRATA_GU_FMTS(STRATA_QK) -#undef STRATA_QK - default: return 0; - } -} -int d_qk(int t) { - switch (t) { -#define STRATA_QK(T) case T: return Fmt::qk; - STRATA_D_FMTS(STRATA_QK) -#undef STRATA_QK - default: return 0; - } -} - -bool env_on(const char* name) { - const char* v = std::getenv(name); - return v != nullptr && v[0] != '\0' && v[0] != '0'; -} -// STRATA_OLD_IQ_MMVQ=1 keeps the per-column kernels (bitwise equal to the new ones; kept for A/B timing) -bool g_old_kernels = env_on("STRATA_OLD_IQ_MMVQ"); -// STRATA_IQ_STAGE_GRID=0 disables staging 64-bit i-quant codebook tables into shared memory -bool g_stage_grid = [] { - const char* v = std::getenv("STRATA_IQ_STAGE_GRID"); - return v == nullptr || v[0] == '\0' || v[0] != '0'; -}(); -// The single-matrix mmvq (128-thread blocks, one per 4 rows) pays the 2-8 KB staging per block: on the RTX 5070 its -// IQ2_XS / IQ2_S / IQ1_M calls were 10-20% slower staged at 3-8 columns (iq_multi_parity --bench), while the grouped -// expert kernels gain. So mmvq stages only with STRATA_IQ_STAGE_GRID_MMVQ=1 (bitwise the same either way). -bool g_stage_grid_mmvq = g_stage_grid && [] { - const char* v = std::getenv("STRATA_IQ_STAGE_GRID_MMVQ"); - return v != nullptr && v[0] == '1'; -}(); - -template -void launch_mmvq(const uint8_t* W, size_t rb, const block_q8_1* X, float* y, int n_in, int n_out, int ncols, - cudaStream_t s) { - const dim3 grid((unsigned) ((n_out + 3) / 4)), block(32, 4); - if constexpr (!kSplit) mmvq_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); - else if (g_old_kernels) mmvq_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); - else if constexpr (kStageIqGrid) { - if (!g_stage_grid_mmvq) { - if (ncols <= 1) mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); - else if (ncols == 2) mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); - else if (ncols <= 4) mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); - else mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); - return; - } - if (ncols <= 1) mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); - else if (ncols == 2) mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); - else if (ncols <= 4) mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); - else mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); - } else { - if (ncols <= 1) mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); - else if (ncols == 2) mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); - else if (ncols <= 4) mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); - else mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); // 8 at a time past 8 - } -} - -template -void launch_gu(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start, - const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X, const NativeExpertLayout& L, - float* gate, float* up) { - if constexpr (!kSplit) native_gu_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); - else if (g_old_kernels) native_gu_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); - else if constexpr (kStageIqGrid) { - if (!g_stage_grid) { - native_gu_multi_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); - return; - } - native_gu_multi_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); - } else native_gu_multi_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); -} - -template -void launch_down(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start, - const int32_t* n_groups, const int32_t* ent_dst, const block_q8_1* hq, const NativeExpertLayout& L, - float* out) { - if constexpr (!kSplit) native_down_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); - else if (g_old_kernels) native_down_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); - else native_down_multi_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); -} - -} // namespace - -void iq_set_old_kernels(bool old) { g_old_kernels = old; } -bool iq_old_kernels() { return g_old_kernels; } - -bool iq_supported(int t) noexcept { return is_iq(t); } -bool embed_type_supported(int t) noexcept { return is_iq(t) || t == 30; } - -size_t iq_row_bytes(int t, int64_t n) noexcept { - switch (t) { - case 16: return (size_t) (n / 256) * sizeof(block_iq2_xxs); - case 17: return (size_t) (n / 256) * sizeof(block_iq2_xs); - case 18: return (size_t) (n / 256) * sizeof(block_iq3_xxs); - case 20: return (size_t) (n / 32) * sizeof(block_iq4_nl); - case 21: return (size_t) (n / 256) * sizeof(block_iq3_s); - case 22: return (size_t) (n / 256) * sizeof(block_iq2_s); - case 29: return (size_t) (n / 256) * sizeof(block_iq1_m); - case 23: return (size_t) (n / 256) * sizeof(block_iq4_xs); - case 11: return (size_t) (n / 256) * sizeof(block_q3_K); - 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); - case 30: return (size_t) n * 2; // BF16: the token embedding only (iq_embed_rows, iq_dequant_f32) - default: return 0; - } -} - -void quantize_q8_1_rows(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream) { - const long long n = (long long) n_rows * n_cols; - if (n <= 0) return; - quantize_q8_1_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, (cudaStream_t) stream>>>(x, (block_q8_1*) y, n); - check("quantize_q8_1_rows"); -} - -void iq_mmvq(int t, const void* w, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) { - const size_t rb = iq_row_bytes(t, n_in); - cudaStream_t s = (cudaStream_t) stream; - const auto* W = (const uint8_t*) w; - const auto* X = (const block_q8_1*) x_q8_1; - switch (t) { -#define STRATA_MMVQ(T) case T: launch_mmvq(W, rb, X, y, n_in, n_out, ncols, s); break; - STRATA_MMVQ_FMTS(STRATA_MMVQ) -#undef STRATA_MMVQ - default: std::fprintf(stderr, "iq_mmvq: type %d is not supported\n", t); std::exit(1); - } - check("iq_mmvq"); -} - -void iq_dequant_f16(int t, const void* src, int64_t n, uint16_t* dst, void* stream) { - if (n % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_f16: bad arguments\n"); std::exit(1); } - dequant_flat_kernel<__half><<<(unsigned) (n / 256), 32, 0, (cudaStream_t) stream>>>(t, src, (__half*) dst); - check("iq_dequant_f16"); -} - -namespace { -__global__ void embed_rows_kernel(int ty, const uint8_t* __restrict__ table, size_t row_bytes, - const int32_t* __restrict__ tokens, int64_t n_embd, float* __restrict__ y) { - const int t = blockIdx.y; - const int64_t b = blockIdx.x; - const uint8_t* row = table + (size_t) tokens[t] * row_bytes; - dq_dispatch(ty, row, b, y + (size_t) t * n_embd + b * QK_K, threadIdx.x); -} -} // namespace - -void iq_embed_rows(int t, const void* table, size_t row_bytes, const int32_t* tokens, int64_t n_tok, int64_t n_embd, - float* out, void* stream) { - if (n_tok <= 0) return; - if (n_embd % 256 != 0 || !embed_type_supported(t)) { std::fprintf(stderr, "iq_embed_rows: bad arguments\n"); std::exit(1); } - embed_rows_kernel<<>>( - t, (const uint8_t*) table, row_bytes, tokens, n_embd, out); - check("iq_embed_rows"); -} - -void iq_dequant_f32(int t, const void* src, int64_t n, float* dst, void* stream) { - if (n % 256 != 0 || !embed_type_supported(t)) { std::fprintf(stderr, "iq_dequant_f32: bad arguments\n"); std::exit(1); } - dequant_flat_kernel<<<(unsigned) (n / 256), 32, 0, (cudaStream_t) stream>>>(t, src, dst); - check("iq_dequant_f32"); -} - -void iq_dequant_gu_f16(int t, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst, void* stream) { - // checked like the other entry points: an unknown type used to leave `dst` unwritten, a wrong prompt and no error - if (n_embd % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_gu_f16: type %d / %lld\n", t, (long long) n_embd); std::exit(1); } - const int64_t per_row = n_embd / 256; - dequant_gu_kernel<<>>(t, gate, up, per_row, - (__half*) dst); - check("iq_dequant_gu_f16"); -} - -bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept { - const int qg = gu_qk(gu_type), qd = d_qk(d_type); - return qg > 0 && qd > 0 && is_iq(gu_type) && is_iq(d_type) && n_embd % qg == 0 && n_ff % qd == 0 && - n_embd % 256 == 0 && (n_ff * n_embd) % 256 == 0; -} - -NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) { - NativeExpertLayout L; - L.gu_type = gu_type; - L.d_type = d_type; - L.n_embd = n_embd; - L.n_ff = n_ff; - L.gu_row = iq_row_bytes(gu_type, n_embd); - L.d_row = iq_row_bytes(d_type, n_ff); - L.up_off = (size_t) n_ff * L.gu_row; - L.down_off = 2 * L.up_off; - L.bytes = L.down_off + (size_t) n_embd * L.d_row; - return L; -} - -size_t native_expert_scratch_bytes(int64_t cap, int64_t n_ff) { - const size_t f = (size_t) cap * (size_t) n_ff * sizeof(float); - return 3 * ((f + 255) & ~(size_t) 255) + (((size_t) cap * (size_t) (n_ff / 32) * sizeof(block_q8_1) + 255) & ~(size_t) 255); -} - - -#if defined(STRATA_HIP_GFX906) -// ---- AMD layouts for the grouped native experts (STRATA_EXP_MODE; 0 = the CUDA one above). -// 1 (W64): a row per 64-lane wavefront - 4x the wavefronts, ~1-2 calls per lane, a 64-lane butterfly. -// 2 (R2): a 32-lane logical warp computes TWO rows in one loop - two independent load chains in flight. -// Either way a (row, entry) sum does not depend on the window size. -template -__device__ __forceinline__ float row_dot64(const uint8_t* row, const block_q8_1* x, int nb, int lane) { - using F = Fmt; - float s = 0.0f; - for (int k = lane; k < nb * F::ipb; k += 64) { - const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); - s += F::dot(row, x + kbx * (F::qk / 32), kbx, iqs); - } -#pragma unroll - for (int o = 32; o > 0; o >>= 1) s += __shfl_xor(s, o, 64); - return s; -} -template -__device__ __forceinline__ void row_dot2(const uint8_t* r0, const uint8_t* r1, const block_q8_1* x, int nb, int lane, - float& o0, float& o1) { - using F = Fmt; - float s0 = 0.0f, s1 = 0.0f; - for (int k = lane; k < nb * F::ipb; k += 32) { - const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); - const block_q8_1* xk = x + kbx * (F::qk / 32); - const float a = F::dot(r0, xk, kbx, iqs); - const float b = F::dot(r1, xk, kbx, iqs); - s0 += a; - s1 += b; - } - o0 = warp_sum(s0); - o1 = warp_sum(s1); -} -template -__device__ __forceinline__ void row_dotn(const uint8_t* const* r, const block_q8_1* x, int nb, int lane, float* o) { - using F = Fmt; - float acc[NR]; -#pragma unroll - for (int i = 0; i < NR; ++i) acc[i] = 0.0f; - for (int k = lane; k < nb * F::ipb; k += 32) { - const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); - const block_q8_1* xk = x + kbx * (F::qk / 32); - float d[NR]; -#pragma unroll - for (int i = 0; i < NR; ++i) d[i] = F::dot(r[i], xk, kbx, iqs); -#pragma unroll - for (int i = 0; i < NR; ++i) acc[i] += d[i]; - } -#pragma unroll - for (int i = 0; i < NR; ++i) o[i] = warp_sum(acc[i]); -} -template -__global__ void __launch_bounds__(256) native_gu_amd_kernel(const unsigned long long* __restrict__ grp_ptr, - const int32_t* __restrict__ grp_start, - const int32_t* __restrict__ n_groups, - const int32_t* __restrict__ ent_tok, - const block_q8_1* __restrict__ xq, NativeExpertLayout L, - float* __restrict__ gate, float* __restrict__ up) { - const int g = blockIdx.y; - if (g >= *n_groups) return; - const uint8_t* blob = (const uint8_t*) grp_ptr[g]; - const int nb = (int) (L.n_embd / Fmt::qk), xb = (int) (L.n_embd / 32); - const int e0 = grp_start[g], e1 = grp_start[g + 1]; - const int nrow = 2 * (int) L.n_ff; - auto wrow = [&](int row) -> const uint8_t* { - const bool is_up = row >= L.n_ff; - return blob + (is_up ? L.up_off : 0) + (size_t) (is_up ? row - (int) L.n_ff : row) * L.gu_row; - }; - auto put = [&](int row, int e, float v) { - const bool is_up = row >= L.n_ff; - (is_up ? up : gate)[(size_t) e * L.n_ff + (is_up ? row - (int) L.n_ff : row)] = v; - }; - if constexpr (MODE == 1) { - const int lane = threadIdx.x & 63, row = blockIdx.x * 4 + (threadIdx.x >> 6); - if (row >= nrow) return; - const uint8_t* wr = wrow(row); - for (int e = e0; e < e1; ++e) { - const float v = row_dot64(wr, xq + (size_t) ent_tok[e] * xb, nb, lane); - if (lane == 0) put(row, e, v); - } - } else if constexpr (MODE == 4) { - const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; - const int row0 = blockIdx.x * 32 + warp; - if (row0 >= nrow) return; - const uint8_t* w[4]; -#pragma unroll - for (int i = 0; i < 4; ++i) w[i] = wrow(row0 + 8 * i < nrow ? row0 + 8 * i : row0); - for (int e = e0; e < e1; ++e) { - float o[4]; - row_dotn(w, xq + (size_t) ent_tok[e] * xb, nb, lane, o); - if (lane == 0) -#pragma unroll - for (int i = 0; i < 4; ++i) if (row0 + 8 * i < nrow) put(row0 + 8 * i, e, o[i]); - } - } else { - const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; - const int row0 = blockIdx.x * 16 + warp, row1 = row0 + 8; - if (row0 >= nrow) return; - const bool two = row1 < nrow; - const uint8_t* w0 = wrow(row0); - const uint8_t* w1 = wrow(two ? row1 : row0); - for (int e = e0; e < e1; ++e) { - float a, b; - row_dot2(w0, w1, xq + (size_t) ent_tok[e] * xb, nb, lane, a, b); - if (lane == 0) { put(row0, e, a); if (two) put(row1, e, b); } - } - } -} -template -__global__ void __launch_bounds__(256) native_down_amd_kernel(const unsigned long long* __restrict__ grp_ptr, - const int32_t* __restrict__ grp_start, - const int32_t* __restrict__ n_groups, - const int32_t* __restrict__ ent_dst, - const block_q8_1* __restrict__ hq, NativeExpertLayout L, - float* __restrict__ out) { - const int g = blockIdx.y; - if (g >= *n_groups) return; - const uint8_t* blob = (const uint8_t*) grp_ptr[g]; - const int nb = (int) (L.n_ff / Fmt::qk), hb = (int) (L.n_ff / 32); - const int e0 = grp_start[g], e1 = grp_start[g + 1]; - const int nrow = (int) L.n_embd; - if constexpr (MODE == 1) { - const int lane = threadIdx.x & 63, r = blockIdx.x * 4 + (threadIdx.x >> 6); - if (r >= nrow) return; - const uint8_t* wr = blob + L.down_off + (size_t) r * L.d_row; - for (int e = e0; e < e1; ++e) { - const float v = row_dot64(wr, hq + (size_t) e * hb, nb, lane); - if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = v; - } - } else if constexpr (MODE == 4) { - const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; - const int r0 = blockIdx.x * 32 + warp; - if (r0 >= nrow) return; - const uint8_t* w[4]; -#pragma unroll - for (int i = 0; i < 4; ++i) w[i] = blob + L.down_off + (size_t) (r0 + 8 * i < nrow ? r0 + 8 * i : r0) * L.d_row; - for (int e = e0; e < e1; ++e) { - float o[4]; - row_dotn(w, hq + (size_t) e * hb, nb, lane, o); - if (lane == 0) -#pragma unroll - for (int i = 0; i < 4; ++i) if (r0 + 8 * i < nrow) out[(size_t) ent_dst[e] * L.n_embd + r0 + 8 * i] = o[i]; - } - } else { - const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; - const int r0 = blockIdx.x * 16 + warp, r1 = r0 + 8; - if (r0 >= nrow) return; - const bool two = r1 < nrow; - const uint8_t* w0 = blob + L.down_off + (size_t) r0 * L.d_row; - const uint8_t* w1 = blob + L.down_off + (size_t) (two ? r1 : r0) * L.d_row; - for (int e = e0; e < e1; ++e) { - float a, b; - row_dot2(w0, w1, hq + (size_t) e * hb, nb, lane, a, b); - if (lane == 0) { - out[(size_t) ent_dst[e] * L.n_embd + r0] = a; - if (two) out[(size_t) ent_dst[e] * L.n_embd + r1] = b; - } - } - } -} -// ---- 5 (LDS): gate/up of the grid formats (IQ2_S, IQ3_XXS, IQ3_S) with the codebook grid and the group's q8_1 -// activations in LDS. The bench showed gate/up compute-bound, not bandwidth-bound (T = 2 costs ~1.8x T = 1 on the -// same weights, 110-130 GB/s): each call issues its grid lookups and eight activation loads through the vector -// memory path after the weight load. Same calls, same lane-strided k, same R2 row pairs, same warp_sum: the -// output is bitwise the mode-2 one. -template struct GridOf; -template<> struct GridOf<22> { using T = uint64_t; static constexpr int N = 1024; __device__ static const T* src() { return iq2s_grid; } }; -template<> struct GridOf<18> { using T = uint32_t; static constexpr int N = 256; __device__ static const T* src() { return iq3xxs_grid; } }; -template<> struct GridOf<21> { using T = uint32_t; static constexpr int N = 512; __device__ static const T* src() { return iq3s_grid; } }; -template<> struct GridOf<23> { using T = uint32_t; static constexpr int N = 1; __device__ static const T* src() { return iq3s_grid; } }; // IQ4_XS: no grid - -// SG = 1 (mode 6): the signs without byte-SIMD ops, which gfx906 lacks (strata_vcmpne4 / strata_vsub4 unpack to -// ~12 word ops each). m = the sign nibble as 0x00/0xff bytes; (g ^ m) is g or -g-1 per byte, so -// dp4a(g ^ m, u) - dp4a(m, u) = sum(s g u) exactly - the same integers, the same floats. -__device__ __forceinline__ int nib_mask(uint32_t n) { - const uint32_t b = __umul24(n & 0xFu, 0x204081u) & 0x01010101u; - return (int) ((b << 8) - b); -} -template struct DotG; -template struct DotG<22, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs, - const uint64_t* grid) { - const block_iq2_s* bq2 = (const block_iq2_s*) vbq + kbx; - const int qs_packed = get_int_b2(bq2->qs, iqs / 2); - const uint8_t* qs = (const uint8_t*) &qs_packed; - const int qh = bq2->qh[iqs / 2]; - const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2); - const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32; - const int ls0 = bq2->scales[iqs / 2] & 0x0F; - const int ls1 = bq2->scales[iqs / 2] >> 4; - int sumi0 = 0, sumi1 = 0; -#pragma unroll - for (int l0 = 0; l0 < 8; l0 += 2) { - const int* grid_pos = (const int*) (grid + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300))); - const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0); - const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1); - int& acc = l0 < 4 ? sumi0 : sumi1; - if constexpr (SG == 1) { - const int m0 = nib_mask(signs_packed_8[l0 / 2]), m1 = nib_mask(signs_packed_8[l0 / 2] >> 4); - acc = ggml_cuda_dp4a(grid_pos[0] ^ m0, u0, acc); - acc = ggml_cuda_dp4a(grid_pos[1] ^ m1, u1, acc); - acc -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0)); - } else { - const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000); - const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000); - const int grid_l = __vsub4(grid_pos[0] ^ signs0, signs0); - const int grid_h = __vsub4(grid_pos[1] ^ signs1, signs1); - acc = ggml_cuda_dp4a(grid_l, u0, acc); - acc = ggml_cuda_dp4a(grid_h, u1, acc); - } - } - const int sumi = (sumi0 * ls0 + sumi1 * ls1 + (sumi0 + sumi1) / 2) / 4; - const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds); - return d * sumi; -} }; -template struct DotG<18, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs, - const uint32_t* grid) { - const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx; - const int2 q3_packed = make_int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1)); - const uint8_t* q3 = (const uint8_t*) &q3_packed; - const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2); - int sumi = 0; -#pragma unroll - for (int l0 = 0; l0 < 8; l0 += 2) { - const int2 grid_pos = make_int2(grid[q3[l0 + 0]], grid[q3[l0 + 1]]); - const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2)); - const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0); - const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1); - if constexpr (SG == 1) { - const int m0 = nib_mask(signs), m1 = nib_mask(signs >> 4); - sumi = ggml_cuda_dp4a(grid_pos.x ^ m0, u0, sumi); - sumi = ggml_cuda_dp4a(grid_pos.y ^ m1, u1, sumi); - sumi -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0)); - } else { - const int signs0 = __vcmpne4(signs & 0x08040201, 0); - const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0); - const int signs1 = __vcmpne4(signs & 0x80402010, 0); - const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1); - sumi = ggml_cuda_dp4a(grid_l, u0, sumi); - sumi = ggml_cuda_dp4a(grid_h, u1, sumi); - } - } - const int ls = aux32 >> 28; - sumi = (ls * sumi + sumi / 2) / 2; - const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds); - return d * sumi; -} }; -template struct DotG<21, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs, - const uint32_t* grid) { - const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx; - const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1)); - const uint8_t* qs = (const uint8_t*) &qs_packed; - const int qh = bq3->qh[iqs / 2]; - const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2); - const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32; - int sumi = 0; -#pragma unroll - for (int l0 = 0; l0 < 8; l0 += 2) { - const int2 grid_pos = make_int2(grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)], - grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]); - const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0); - const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1); - if constexpr (SG == 1) { - const int m0 = nib_mask(signs_packed_8[l0 / 2]), m1 = nib_mask(signs_packed_8[l0 / 2] >> 4); - sumi = ggml_cuda_dp4a(grid_pos.x ^ m0, u0, sumi); - sumi = ggml_cuda_dp4a(grid_pos.y ^ m1, u1, sumi); - sumi -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0)); - } else { - const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000); - const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000); - const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0); - const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1); - sumi = ggml_cuda_dp4a(grid_l, u0, sumi); - sumi = ggml_cuda_dp4a(grid_h, u1, sumi); - } - } - sumi *= 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F); - const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds); - return d * sumi; -} }; - -template struct DotG<23, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs, - const uint32_t*) { return vec_dot_iq4_xs_q8_1(vbq, bq8_1, kbx, iqs); } }; - -constexpr int LDS_RB = 64; // gate/up rows per block (4 R2 passes of 16) -constexpr int LDS_NT = 4; // entries whose activations sit in LDS at once - -template -__global__ void __launch_bounds__(256) native_gu_lds_kernel(const unsigned long long* __restrict__ grp_ptr, - const int32_t* __restrict__ grp_start, - const int32_t* __restrict__ n_groups, - const int32_t* __restrict__ ent_tok, - const block_q8_1* __restrict__ xq, NativeExpertLayout L, - float* __restrict__ gate, float* __restrict__ up) { - using GT = typename GridOf::T; - using F = Fmt; - __shared__ GT sgrid[GridOf::N]; - extern __shared__ int sx_raw[]; // LDS_NT tokens x xb blocks of q8_1 (36 bytes = 9 ints each) - const int g = blockIdx.y; - if (g >= *n_groups) return; // uniform over the block - const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; - const GT* gsrc = GridOf::src(); - for (int i = tid; i < GridOf::N; i += 256) sgrid[i] = gsrc[i]; - const uint8_t* blob = (const uint8_t*) grp_ptr[g]; - const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32); - const int e0 = grp_start[g], e1 = grp_start[g + 1]; - const int nrow = 2 * (int) L.n_ff; - const block_q8_1* sx = (const block_q8_1*) sx_raw; - auto wrow = [&](int row) -> const uint8_t* { - const bool is_up = row >= L.n_ff; - return blob + (is_up ? L.up_off : 0) + (size_t) (is_up ? row - (int) L.n_ff : row) * L.gu_row; - }; - auto put = [&](int row, int e, float v) { - const bool is_up = row >= L.n_ff; - (is_up ? up : gate)[(size_t) e * L.n_ff + (is_up ? row - (int) L.n_ff : row)] = v; - }; - for (int c0 = e0; c0 < e1; c0 += LDS_NT) { - const int cn = min(LDS_NT, e1 - c0); - __syncthreads(); - for (int j = 0; j < cn; ++j) { - const int* src = (const int*) (xq + (size_t) ent_tok[c0 + j] * xb); - for (int i = tid; i < xb * 9; i += 256) sx_raw[j * xb * 9 + i] = src[i]; - } - __syncthreads(); - for (int p = 0; p < LDS_RB / 16; ++p) { - const int row0 = blockIdx.x * LDS_RB + p * 16 + warp, row1 = row0 + 8; - if (row0 >= nrow) break; - const bool two = row1 < nrow; - const uint8_t* w0 = wrow(row0); - const uint8_t* w1 = wrow(two ? row1 : row0); - if constexpr (TI) { // mode 7: the tokens inside the k loop - one weight load per k for all of them - auto pass = [&](auto ntc) { - constexpr int NTC = decltype(ntc)::value; - float s0[NTC], s1[NTC]; -#pragma unroll - for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; } - for (int k = lane; k < nb * F::ipb; k += 32) { - const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); -#pragma unroll - for (int j = 0; j < NTC; ++j) { - const block_q8_1* xk = sx + (size_t) j * xb + kbx * (F::qk / 32); - const float a = DotG::f(w0, xk, kbx, iqs, sgrid); - const float b = DotG::f(w1, xk, kbx, iqs, sgrid); - s0[j] += a; - s1[j] += b; - } - } -#pragma unroll - for (int j = 0; j < NTC; ++j) { - const float a = warp_sum(s0[j]), b = warp_sum(s1[j]); - if (lane == 0) { put(row0, c0 + j, a); if (two) put(row1, c0 + j, b); } - } - }; - switch (cn) { - case 1: pass(std::integral_constant{}); break; - case 2: pass(std::integral_constant{}); break; - case 3: pass(std::integral_constant{}); break; - default: pass(std::integral_constant{}); break; - } - continue; - } - for (int j = 0; j < cn; ++j) { - const block_q8_1* x = sx + (size_t) j * xb; - float s0 = 0.0f, s1 = 0.0f; - for (int k = lane; k < nb * F::ipb; k += 32) { - const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); - const block_q8_1* xk = x + kbx * (F::qk / 32); - const float a = DotG::f(w0, xk, kbx, iqs, sgrid); - const float b = DotG::f(w1, xk, kbx, iqs, sgrid); - s0 += a; - s1 += b; - } - s0 = warp_sum(s0); - s1 = warp_sum(s1); - if (lane == 0) { put(row0, c0 + j, s0); if (two) put(row1, c0 + j, s1); } - } - } - } -} - -// ---- 7 (down): the group's q8_1 h rows in LDS, the tokens inside the k loop, the R2 row pairs of mode 2 - -// the same per-(row, entry) sums in the same order: bitwise the mode-2 output. -template -__global__ void __launch_bounds__(256) native_down_lds_kernel(const unsigned long long* __restrict__ grp_ptr, - const int32_t* __restrict__ grp_start, - const int32_t* __restrict__ n_groups, - const int32_t* __restrict__ ent_dst, - const block_q8_1* __restrict__ hq, NativeExpertLayout L, - float* __restrict__ out) { - using F = Fmt; - extern __shared__ int sh_raw[]; // LDS_NT entries x hb blocks of q8_1 - const int g = blockIdx.y; - if (g >= *n_groups) return; - const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; - const uint8_t* blob = (const uint8_t*) grp_ptr[g]; - const int nb = (int) (L.n_ff / F::qk), hb = (int) (L.n_ff / 32); - const int e0 = grp_start[g], e1 = grp_start[g + 1]; - const int nrow = (int) L.n_embd; - const block_q8_1* sh = (const block_q8_1*) sh_raw; - for (int c0 = e0; c0 < e1; c0 += LDS_NT) { - const int cn = min(LDS_NT, e1 - c0); - __syncthreads(); - { - const int* src = (const int*) (hq + (size_t) c0 * hb); // the chunk's entries are contiguous - for (int i = tid; i < cn * hb * 9; i += 256) sh_raw[i] = src[i]; - } - __syncthreads(); - for (int p = 0; p < LDS_RB / 16; ++p) { - const int r0 = blockIdx.x * LDS_RB + p * 16 + warp, r1 = r0 + 8; - if (r0 >= nrow) break; - const bool two = r1 < nrow; - const uint8_t* w0 = blob + L.down_off + (size_t) r0 * L.d_row; - const uint8_t* w1 = blob + L.down_off + (size_t) (two ? r1 : r0) * L.d_row; - auto pass = [&](auto ntc) { - constexpr int NTC = decltype(ntc)::value; - float s0[NTC], s1[NTC]; -#pragma unroll - for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; } - for (int k = lane; k < nb * F::ipb; k += 32) { - const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); -#pragma unroll - for (int j = 0; j < NTC; ++j) { - const block_q8_1* xk = sh + (size_t) j * hb + kbx * (F::qk / 32); - const float a = F::dot(w0, xk, kbx, iqs); - const float b = F::dot(w1, xk, kbx, iqs); - s0[j] += a; - s1[j] += b; - } - } -#pragma unroll - for (int j = 0; j < NTC; ++j) { - const float a = warp_sum(s0[j]), b = warp_sum(s1[j]); - if (lane == 0) { - out[(size_t) ent_dst[c0 + j] * L.n_embd + r0] = a; - if (two) out[(size_t) ent_dst[c0 + j] * L.n_embd + r1] = b; - } - } - }; - switch (cn) { - case 1: pass(std::integral_constant{}); break; - case 2: pass(std::integral_constant{}); break; - case 3: pass(std::integral_constant{}); break; - default: pass(std::integral_constant{}); break; - } - } - } -} - -// ---- 8: mode 7's gate/up with SwiGLU and the q8_1 quantization in the epilogue. A block takes h rows -// [r0, r0 + 32): gate rows r0.. and up rows r0.. (64 weight rows, the same per-(row, entry) sums as mode 7), so -// one 32-lane warp per entry holds exactly one q8_1 block of h and runs quantize_q8_1_kernel's own code on it - -// bitwise the separate kernels' hq, two launches fewer per call. -template -__global__ void __launch_bounds__(256) native_gu_fused_kernel(const unsigned long long* __restrict__ grp_ptr, - const int32_t* __restrict__ grp_start, - const int32_t* __restrict__ n_groups, - const int32_t* __restrict__ ent_tok, - const block_q8_1* __restrict__ xq, NativeExpertLayout L, - block_q8_1* __restrict__ hq) { - using GT = typename GridOf::T; - using F = Fmt; - __shared__ GT sgrid[GridOf::N]; - __shared__ float res[LDS_NT][64]; - extern __shared__ int sx_raw[]; - const int g = blockIdx.y; - if (g >= *n_groups) return; - const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; - const GT* gsrc = GridOf::src(); - for (int i = tid; i < GridOf::N; i += 256) sgrid[i] = gsrc[i]; - const uint8_t* blob = (const uint8_t*) grp_ptr[g]; - const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32), hb = (int) (L.n_ff / 32); - const int e0 = grp_start[g], e1 = grp_start[g + 1]; - const int r0 = blockIdx.x * 32; - const block_q8_1* sx = (const block_q8_1*) sx_raw; - auto wrow = [&](int i) -> const uint8_t* { // i < 32: gate row r0 + i, else up row r0 + i - 32 - return blob + (i < 32 ? (size_t) 0 : L.up_off) + (size_t) (r0 + (i & 31)) * L.gu_row; - }; - for (int c0 = e0; c0 < e1; c0 += LDS_NT) { - const int cn = min(LDS_NT, e1 - c0); - __syncthreads(); - for (int j = 0; j < cn; ++j) { - const int* src = (const int*) (xq + (size_t) ent_tok[c0 + j] * xb); - for (int i = tid; i < xb * 9; i += 256) sx_raw[j * xb * 9 + i] = src[i]; - } - __syncthreads(); - for (int p = 0; p < 4; ++p) { - const int i0 = p * 16 + warp, i1 = i0 + 8; - const uint8_t* w0 = wrow(i0); - const uint8_t* w1 = wrow(i1); - auto pass = [&](auto ntc) { - constexpr int NTC = decltype(ntc)::value; - float s0[NTC], s1[NTC]; -#pragma unroll - for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; } - for (int k = lane; k < nb * F::ipb; k += 32) { - const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); -#pragma unroll - for (int j = 0; j < NTC; ++j) { - const block_q8_1* xk = sx + (size_t) j * xb + kbx * (F::qk / 32); - const float a = DotG::f(w0, xk, kbx, iqs, sgrid); - const float b = DotG::f(w1, xk, kbx, iqs, sgrid); - s0[j] += a; - s1[j] += b; - } - } -#pragma unroll - for (int j = 0; j < NTC; ++j) { - const float a = warp_sum(s0[j]), b = warp_sum(s1[j]); - if (lane == 0) { res[j][i0] = a; res[j][i1] = b; } - } - }; - switch (cn) { - case 1: pass(std::integral_constant{}); break; - case 2: pass(std::integral_constant{}); break; - case 3: pass(std::integral_constant{}); break; - default: pass(std::integral_constant{}); break; - } - } - __syncthreads(); - if (warp < cn) { // swiglu_entries_kernel + quantize_q8_1_kernel, one block of 32 h values per entry - const float gg = res[warp][lane], uu = res[warp][32 + lane]; - const float xi = (gg / (1.0f + __expf(-gg))) * uu; - float amax = fabsf(xi), sum = xi; -#pragma unroll - for (int o = 16; o > 0; o >>= 1) { - amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); - sum += __shfl_xor_sync(0xffffffffu, sum, o); - } - const float d = amax / 127.0f; - const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); - block_q8_1* y = hq + (size_t) (c0 + warp) * hb + blockIdx.x; - y->qs[lane] = q; - if (lane == 0) y->ds = make_half2(d, sum); - } - } -} - -int g_exp_mode = -1; // native_expert_set_mode (the bench); -1 = STRATA_EXP_MODE, default 7 -int exp_mode() { - static const int m = [] { const char* v = std::getenv("STRATA_EXP_MODE"); return v ? std::atoi(v) : 7; }(); - return g_exp_mode >= 0 ? g_exp_mode : m; -} -#endif -int g_exp_phase = 0; // the bench: 0 all, 1 gate/up + swiglu + quantize only, 2 down only - -void native_expert_set_mode(int mode, int phase) { -#if defined(STRATA_HIP_GFX906) - g_exp_mode = mode; -#else - (void) mode; -#endif - g_exp_phase = phase; -} - -namespace { -bool g_grouped_v1 = env_on("STRATA_GROUPED_V1"); -} // namespace - -void native_grouped_set_v1(bool v1) { g_grouped_v1 = v1; } - -void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long* grp_ptr, const int32_t* grp_start, - const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups, - int64_t cap_entries, const void* x_q8_1, void* scratch, float* out, void* stream, - int64_t grid_groups) { - if (cap_groups <= 0 || cap_entries <= 0) return; - if (L.n_ff % 32 != 0) { std::fprintf(stderr, "native_expert_grouped: n_ff %lld\n", (long long) L.n_ff); std::exit(1); } - cudaStream_t s = (cudaStream_t) stream; - const size_t f = (size_t) cap_entries * (size_t) L.n_ff * sizeof(float), fa = (f + 255) & ~(size_t) 255; - float* gate = (float*) scratch; - float* up = (float*) ((uint8_t*) scratch + fa); - float* h = (float*) ((uint8_t*) scratch + 2 * fa); - block_q8_1* hq = (block_q8_1*) ((uint8_t*) scratch + 3 * fa); - const auto* X = (const block_q8_1*) x_q8_1; - const bool v1 = g_grouped_v1; - const int64_t gy = (v1 || grid_groups <= 0 || grid_groups > cap_groups) ? cap_groups : grid_groups; - const dim3 ggu((unsigned) ((2 * L.n_ff + GU_ROWS - 1) / GU_ROWS), (unsigned) gy); -#if defined(STRATA_HIP_GFX906) - const int em0 = exp_mode(); -#endif -#if defined(STRATA_HIP_GFX906) - const bool fused_gu = em0 == 8 && (L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23) && - L.n_ff % 32 == 0; - if (fused_gu && g_exp_phase != 2) { - const dim3 gl((unsigned) (L.n_ff / 32), (unsigned) cap_groups); - const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1); - switch (L.gu_type) { - case 18: native_gu_fused_kernel<18><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break; - case 21: native_gu_fused_kernel<21><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break; - case 23: native_gu_fused_kernel<23><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break; - default: native_gu_fused_kernel<22><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break; - } - check("native_expert_grouped/gu fused"); - } - if (g_exp_phase != 2 && !fused_gu) { -#else - if (g_exp_phase != 2) { -#endif -#if defined(STRATA_HIP_GFX906) - const bool lds_gu = (em0 == 5 || em0 == 6 || em0 == 7 || em0 == 8) && (L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23); - if (lds_gu) { - const dim3 gl((unsigned) ((2 * L.n_ff + LDS_RB - 1) / LDS_RB), (unsigned) cap_groups); - const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1); - switch (L.gu_type) { - case 18: if (em0 >= 7) native_gu_lds_kernel<18, 1, true><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<18, 1><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<18, 0><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; - case 21: if (em0 >= 7) native_gu_lds_kernel<21, 1, true><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<21, 1><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<21, 0><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; - case 23: if (em0 >= 7) native_gu_lds_kernel<23, 1, true><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<23, 1><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; - default: if (em0 >= 7) native_gu_lds_kernel<22, 1, true><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<22, 1><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<22, 0><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; - } - } else { - const int em = exp_mode() >= 5 ? 2 : exp_mode(); - const dim3 ggu_amd((unsigned) ((2 * L.n_ff + (em == 1 ? 3 : em == 4 ? 31 : 15)) / (em == 1 ? 4 : em == 4 ? 32 : 16)), (unsigned) cap_groups); -#define STRATA_GU_AMD(T) \ - case T: if (em == 1) native_gu_amd_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); \ - else if (em == 4) native_gu_amd_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); \ - else native_gu_amd_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; - // the AMD layouts cover the IQ packs' gate/up types; Unsloth's Q4_K / Q5_K take the CUDA layout below - const bool amd_gu = L.gu_type == 16 || L.gu_type == 17 || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || - L.gu_type == 23 || L.gu_type == 29 || L.gu_type == 42; - if ((em == 1 || em == 2 || em == 4) && amd_gu) { - switch (L.gu_type) { - STRATA_GU_AMD(16) STRATA_GU_AMD(17) STRATA_GU_AMD(18) STRATA_GU_AMD(21) STRATA_GU_AMD(22) STRATA_GU_AMD(23) - STRATA_GU_AMD(29) STRATA_GU_AMD(42) - } - } else -#undef STRATA_GU_AMD -#endif - switch (L.gu_type) { -#define STRATA_GU(T) case T: launch_gu(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; - STRATA_GU_FMTS(STRATA_GU) -#undef STRATA_GU - default: std::fprintf(stderr, "native_expert_grouped: gate/up type %d\n", L.gu_type); std::exit(1); - } -#if defined(STRATA_HIP_GFX906) - } -#endif - check("native_expert_grouped/gu"); - const long long nh = (long long) cap_entries * L.n_ff; -#if defined(STRATA_HIP_GFX906) - // gfx906: the separate SwiGLU and q8_1 passes stay the default (the A/B baseline); the RDNA one-pass - // kernel (bitwise the same) with STRATA_HIP_SWIGLU_FUSED=1 - static const bool sw_fused = env_on("STRATA_HIP_SWIGLU_FUSED"); - const bool sw_v1 = v1 || !sw_fused; -#else - const bool sw_v1 = v1; -#endif - if (sw_v1) { - swiglu_entries_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, nh); - quantize_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(h, hq, nh); - } else { - swiglu_q8_1_entries_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, grp_start, n_groups, - (int) L.n_ff, hq); - } - check("native_expert_grouped/swiglu"); - } - if (g_exp_phase == 1) return; - const int d_rows = (!g_old_kernels && L.n_ff == 640) ? (L.d_type == 20 ? 32 : (L.d_type == 42 ? 16 : 8)) : 8; - const dim3 gd((unsigned) ((L.n_embd + d_rows - 1) / d_rows), (unsigned) gy); -#if defined(STRATA_HIP_GFX906) - if ((em0 == 7 || em0 == 8) && (L.d_type == 20 || L.d_type == 42)) { - const dim3 gl((unsigned) ((L.n_embd + LDS_RB - 1) / LDS_RB), (unsigned) cap_groups); - const size_t sh = (size_t) LDS_NT * (size_t) (L.n_ff / 32) * sizeof(block_q8_1); - if (L.d_type == 20) native_down_lds_kernel<20><<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); - else native_down_lds_kernel<42><<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); - check("native_expert_grouped/down"); - return; - } - const int em = exp_mode() >= 5 ? 2 : exp_mode(); - const dim3 gd_amd((unsigned) ((L.n_embd + (em == 1 ? 3 : em == 4 ? 31 : 15)) / (em == 1 ? 4 : em == 4 ? 32 : 16)), (unsigned) cap_groups); -#define STRATA_D_AMD(T) \ - case T: if (em == 1) native_down_amd_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); \ - else if (em == 4) native_down_amd_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); \ - else native_down_amd_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break; - // the AMD layouts cover the IQ packs' down types; the others (Unsloth's Q4_K / Q5_K / Q5_1 / Q8_0) take the - // CUDA layout below - if ((em == 1 || em == 2 || em == 4) && (L.d_type == 20 || L.d_type == 23 || L.d_type == 42)) { - switch (L.d_type) { - STRATA_D_AMD(20) STRATA_D_AMD(23) STRATA_D_AMD(42) - } - } else -#undef STRATA_D_AMD -#endif - switch (L.d_type) { -#define STRATA_DOWN(T) case T: launch_down(gd, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break; - STRATA_D_FMTS(STRATA_DOWN) -#undef STRATA_DOWN - default: std::fprintf(stderr, "native_expert_grouped: down type %d\n", L.d_type); std::exit(1); - } - check("native_expert_grouped/down"); -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/kv_q4.cu b/src/kernels/cuda/kv_q4.cu deleted file mode 100644 index b7de61f..0000000 --- a/src/kernels/cuda/kv_q4.cu +++ /dev/null @@ -1,231 +0,0 @@ -// src/kernels/cuda/kv_q4.cu - see include/strata/kernels/kv_q4.hpp. Q4_0 KV with Walsh-Hadamard rotation -// (from PR #21 by code-martin; KV-streaming integration and the deterministic group maximum added on merge). -#include "strata/kernels/kv_q4.hpp" -#include "strata/kernels/f16_bits.hpp" -#include "strata/kernels/kv_stream.hpp" - -#include -#include -#include -#include - -namespace strata::kernels { -namespace { - -void check(const char* what) { - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "kv_q4: %s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -// Fast Walsh-Hadamard Transform for N = 256: one warp per row, 8 values per lane in registers. -// Orthonormal (scale 1/sqrt(256) = 1/16), so it is its own inverse. -__global__ void fwht256_kernel(const float* __restrict__ src, float* __restrict__ dst, int64_t n_rows, float scale) { - constexpr int warp_size = 32; - constexpr int N = 256; - constexpr int el_w = N / warp_size; // 8 - - const int64_t r = (int64_t) blockIdx.x * blockDim.y + threadIdx.y; - if (r >= n_rows) return; - - const float* row_src = src + r * N; - float* row_dst = dst + r * N; - - float reg[el_w]; - const int lane = threadIdx.x; - -#pragma unroll - for (int i = 0; i < el_w; ++i) reg[i] = row_src[i * warp_size + lane] * scale; - - // the low 5 index bits live across lanes -#pragma unroll - for (int h = 1; h < warp_size; h *= 2) { -#pragma unroll - for (int j = 0; j < el_w; ++j) { - const float val = reg[j]; - const float val2 = __shfl_xor_sync(0xffffffffu, val, h, warp_size); - reg[j] = (lane & h) == 0 ? val + val2 : val2 - val; - } - } - // the high 3 bits across each lane's registers -#pragma unroll - for (int h = warp_size; h < N; h *= 2) { - const int step = h / warp_size; -#pragma unroll - for (int j = 0; j < el_w; j += 2 * step) { -#pragma unroll - for (int k = 0; k < step; ++k) { - const float x = reg[j + k]; - const float y = reg[j + k + step]; - reg[j + k] = x + y; - reg[j + k + step] = x - y; - } - } - } -#pragma unroll - for (int i = 0; i < el_w; ++i) row_dst[i * warp_size + lane] = reg[i]; -} - -// One 32-value group in one warp (lane = element), ggml's q4_0: d = (the value of largest |x|) / -8, -// q = clamp(trunc(x / d + 8.5), 0, 15). Returns the scale bits; `byte` is lane t's packed byte for t < 16 -// (element t in the low nibble, t + 16 in the high one). Ties in |x| resolve to the larger value in EVERY lane, -// so all lanes agree on d (a plain `a > amax` could leave lanes with opposite signs and one block two scales). -__device__ __forceinline__ uint16_t q4_group(float x, int lane, uint8_t& byte) { - float amax = fabsf(x), mval = x; -#pragma unroll - for (int o = 16; o > 0; o >>= 1) { - const float a = __shfl_xor_sync(0xffffffffu, amax, o); - const float v = __shfl_xor_sync(0xffffffffu, mval, o); - if (a > amax || (a == amax && v > mval)) { amax = a; mval = v; } - } - const float d = mval / -8.0f; - const float id = d != 0.0f ? 1.0f / d : 0.0f; - int q = __float2int_rz(x * id + 8.5f); - const uint8_t qc = (uint8_t) (q < 0 ? 0 : (q > 15 ? 15 : q)); - const uint8_t qhi = __shfl_down_sync(0xffffffffu, qc, 16); - byte = (uint8_t) (qc | (qhi << 4)); - (void) lane; - return f16_from_f32(d); -} - -__device__ __forceinline__ void q4_store(uint8_t* pool, long long row, int b, int lane, uint16_t d, uint8_t byte) { - block_q4_0* blk = reinterpret_cast(pool + row * (long long) sizeof(block_q4_0) * 8) + b; - if (lane == 0) blk->d = d; - if (lane < 16) blk->qs[lane] = byte; -} - -// One block = one 32-value group of one KV head of K (blockIdx.z = 0) or V (1); 32 threads. KV streaming: the VRAM -// page only if the block is resident (table >= 0), the host copy always (identity layout) when there is one. -__global__ void kv_append_q4_kernel(uint8_t* __restrict__ k_q4, uint8_t* __restrict__ v_q4, - const int32_t* __restrict__ table, const int32_t* __restrict__ step, - const float* __restrict__ kcur, const float* __restrict__ vcur, - int kv_heads, int head_dim, int page_size, KvHostPools host) { - const long long pos = (long long) __ldg(step + kStepPos); - const int h = blockIdx.x, b = blockIdx.y, t = threadIdx.x; - const bool is_v = blockIdx.z == 1; - const float x = (is_v ? vcur : kcur)[h * head_dim + b * QK4_0 + t]; - uint8_t byte; - const uint16_t d = q4_group(x, t, byte); - const long long page = (long long) table[pos / page_size]; - if (page >= 0) q4_store(is_v ? v_q4 : k_q4, (page * kv_heads + h) * page_size + (pos % page_size), b, t, d, byte); - if (host.k_q4 != nullptr) - q4_store(is_v ? host.v_q4 : host.k_q4, ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size), b, t, - d, byte); -} - -// The prompt path: grid (T, kv_heads, groups), K then V; also into the staging pool (identity layout) when given. -__global__ void kv_append_q4_batch_kernel(uint8_t* __restrict__ k_q4, uint8_t* __restrict__ v_q4, - const int32_t* __restrict__ table, int64_t pos0, - const float* __restrict__ K, const float* __restrict__ V, - int kv_heads, int head_dim, int page_size, int is_v_grid, KvHostPools host, - KvHostPools stage) { - const long long t = blockIdx.x; - const long long pos = pos0 + t; - const int h = blockIdx.y, b = blockIdx.z, th = threadIdx.x; - const bool is_v = is_v_grid != 0; - const float x = (is_v ? V : K)[t * (kv_heads * head_dim) + h * head_dim + b * QK4_0 + th]; - uint8_t byte; - const uint16_t d = q4_group(x, th, byte); - const long long page = (long long) table[pos / page_size]; - const long long row_id = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size); - if (page >= 0) q4_store(is_v ? v_q4 : k_q4, (page * kv_heads + h) * page_size + (pos % page_size), b, th, d, byte); - if (host.k_q4 != nullptr) q4_store(is_v ? host.v_q4 : host.k_q4, row_id, b, th, d, byte); - if (stage.k_q4 != nullptr) q4_store(is_v ? stage.v_q4 : stage.k_q4, row_id, b, th, d, byte); -} - -// Gather step[kStepWidth] cells into FP16 scratch (the non-fused attention paths) -__global__ void kv_gather_q4_kernel(const uint8_t* __restrict__ k_q4, const uint8_t* __restrict__ v_q4, - const int32_t* __restrict__ table, const int32_t* __restrict__ ids, - const int32_t* __restrict__ step, int kv_heads, int head_dim, int page_size, - uint16_t* __restrict__ k_scratch, uint16_t* __restrict__ v_scratch) { - const long long n_ids = (long long) __ldg(step + kStepWidth); - const int blocks_per_head = head_dim / QK4_0; // 8 - const int bytes_per_head = blocks_per_head * sizeof(block_q4_0); // 144 - const long long total_blocks = n_ids * kv_heads * blocks_per_head; - - const long long blk_idx = (long long) blockIdx.x * blockDim.y + threadIdx.y; - if (blk_idx >= total_blocks) return; - - const int t = threadIdx.x; - const long long id = blk_idx / (kv_heads * blocks_per_head); - const int rem = (int) (blk_idx % (kv_heads * blocks_per_head)); - const int h = rem / blocks_per_head; - const int b = rem % blocks_per_head; - - const int cell = ids[id]; - const long long page = (long long) table[cell / page_size]; - const long long row = (page * kv_heads + h) * page_size + (cell % page_size); - - const block_q4_0* k_blk = reinterpret_cast(k_q4 + row * bytes_per_head) + b; - const block_q4_0* v_blk = reinterpret_cast(v_q4 + row * bytes_per_head) + b; - const float kd = f32_from_f16(k_blk->d); - const float vd = f32_from_f16(v_blk->d); - const int j = t < 16 ? t : (t - 16); - const uint8_t k_byte = k_blk->qs[j]; - const uint8_t v_byte = v_blk->qs[j]; - const int kq = (t < 16) ? ((k_byte & 0x0F) - 8) : ((k_byte >> 4) - 8); - const int vq = (t < 16) ? ((v_byte & 0x0F) - 8) : ((v_byte >> 4) - 8); - const long long dst_offset = ((id * kv_heads + h) * head_dim) + (b * QK4_0 + t); - k_scratch[dst_offset] = f16_from_f32((float) kq * kd); - v_scratch[dst_offset] = f16_from_f32((float) vq * vd); -} - -void need_256(const QsaShapes& s, const char* what) { - if (s.head_dim != 256) { - std::fprintf(stderr, "%s: head_dim must be 256 (the Hadamard transform's size)\n", what); - std::exit(1); - } -} - -} // namespace - -void fwht256_cuda(const float* src, float* dst, int64_t n_rows, void* stream) { - if (n_rows <= 0) return; - const int rows_per_block = 4; - const int64_t num_blocks = (n_rows + rows_per_block - 1) / rows_per_block; - fwht256_kernel<<>>( - src, dst, n_rows, 1.0f / 16.0f); - check("fwht256 launch"); -} - -void kv_append_q4_step(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, const int32_t* step, - const float* kcur, const float* vcur, const QsaShapes& s, void* stream, - const KvHostPools* host) { - need_256(s, "kv_append_q4"); - const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / QK4_0), 2); - kv_append_q4_kernel<<>>( - k_q4, v_q4, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size, - host ? *host : KvHostPools{}); - check("kv_append_q4 launch"); -} - -void kv_append_q4(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, int64_t pos0, int64_t T, const float* K, - const float* V, const QsaShapes& s, void* stream, const KvHostPools* host, const KvHostPools* stage) { - if (T <= 0) return; - need_256(s, "kv_append_q4"); - const dim3 grid((unsigned) T, (unsigned) s.n_head_kv, (unsigned) (s.head_dim / QK4_0)); - cudaStream_t cs = (cudaStream_t) stream; - const KvHostPools h = host ? *host : KvHostPools{}, st = stage ? *stage : KvHostPools{}; - for (int is_v = 0; is_v < 2; ++is_v) - kv_append_q4_batch_kernel<<>>(k_q4, v_q4, page_table, pos0, K, V, (int) s.n_head_kv, - (int) s.head_dim, (int) s.page_size, is_v, h, st); - check("kv_append_q4 batch launch"); -} - -void kv_gather_q4_step(const uint8_t* k_q4, const uint8_t* v_q4, const int32_t* page_table, const int32_t* ids, - const int32_t* step, int64_t max_ids, const QsaShapes& s, uint16_t* k_scratch, - uint16_t* v_scratch, void* stream) { - if (max_ids <= 0) return; - const int blocks_per_head = (int) (s.head_dim / QK4_0); - const int64_t total_blocks = max_ids * s.n_head_kv * blocks_per_head; - const int rows_per_block = 4; - const unsigned num_blocks = (unsigned) ((total_blocks + rows_per_block - 1) / rows_per_block); - kv_gather_q4_kernel<<>>( - k_q4, v_q4, page_table, ids, step, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size, k_scratch, - v_scratch); - check("kv_gather_q4 launch"); -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/kv_q8.cu b/src/kernels/cuda/kv_q8.cu deleted file mode 100644 index fb2ccec..0000000 --- a/src/kernels/cuda/kv_q8.cu +++ /dev/null @@ -1,127 +0,0 @@ -// src/kernels/cuda/kv_q8.cu - see include/strata/kernels/kv_q8.hpp. -#include "strata/kernels/kv_q8.hpp" -#include "strata/kernels/f16_bits.hpp" - -#include - -#include -#include - -namespace strata::kernels { -namespace { - -void check(const char* what) { - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "kv_q8: %s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -void validate(const QsaShapes& s, const char* what) { - if (s.head_dim % KV_Q8_GROUP != 0 || s.n_head_kv <= 0 || s.page_size <= 0) { - std::fprintf(stderr, "kv_q8: %s: head_dim %lld must be a multiple of %d\n", what, (long long) s.head_dim, - KV_Q8_GROUP); - std::exit(1); - } -} - -// One block = one 64-value group of one KV head of K (blockIdx.z = 0) or V (1); 64 threads, one value each. -__global__ void kv_append_q8_kernel(int8_t* __restrict__ k_q, int8_t* __restrict__ v_q, - uint16_t* __restrict__ k_scale, uint16_t* __restrict__ v_scale, - const int32_t* __restrict__ table, const int32_t* __restrict__ step, - const float* __restrict__ kcur, const float* __restrict__ vcur, int kv_heads, - int head_dim, int page_size, KvHostPools host) { - const long long pos = (long long) __ldg(step + kStepPos); - const int h = blockIdx.x, g = blockIdx.y, t = threadIdx.x; - const bool is_v = blockIdx.z == 1; - const int groups = head_dim / KV_Q8_GROUP; - const float x = (is_v ? vcur : kcur)[h * head_dim + g * KV_Q8_GROUP + t]; - // max |x| over the 64 values: two warps, then combine through shared memory in a fixed order - float a = fabsf(x); - for (int o = 16; o > 0; o >>= 1) a = fmaxf(a, __shfl_xor_sync(0xffffffffu, a, o)); - __shared__ float warp_max[2]; - if ((t & 31) == 0) warp_max[t >> 5] = a; - __syncthreads(); - const float amax = fmaxf(warp_max[0], warp_max[1]); - const uint16_t sbits = f16_from_f32(amax / 127.0f); - const float sf = f32_from_f16(sbits); // quantize against the STORED scale - int q = 0; - if (sf > 0.0f) { - q = __float2int_rn(x / sf); - q = q < -127 ? -127 : (q > 127 ? 127 : q); - } - // KV streaming: the host copy (identity layout) always, the VRAM page only if the block is resident - const long long page = (long long) table[pos / page_size]; - if (page >= 0) { - const long long row = (page * kv_heads + h) * page_size + (pos % page_size); - (is_v ? v_q : k_q)[row * head_dim + g * KV_Q8_GROUP + t] = (int8_t) q; - if (t == 0) (is_v ? v_scale : k_scale)[row * groups + g] = sbits; - } - if (host.k_q != nullptr) { - const long long row = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size); - (is_v ? host.v_q : host.k_q)[row * head_dim + g * KV_Q8_GROUP + t] = (int8_t) q; - if (t == 0) (is_v ? host.v_scale : host.k_scale)[row * groups + g] = sbits; - } -} - -// One thread = 4 consecutive values of one cell and head (as the FP16 gather does with uint2). -__global__ void kv_gather_q8_kernel(const int8_t* __restrict__ k_q, const int8_t* __restrict__ v_q, - const uint16_t* __restrict__ k_scale, const uint16_t* __restrict__ v_scale, - const int32_t* __restrict__ table, const int32_t* __restrict__ ids, - const int32_t* __restrict__ step, int kv_heads, int head_dim, int page_size, - uint16_t* __restrict__ k_scratch, uint16_t* __restrict__ v_scratch) { - const long long n_ids = (long long) __ldg(step + kStepWidth); - const int per = head_dim / 4; - const long long total = n_ids * kv_heads * per; - const long long i = blockIdx.x * (long long) blockDim.x + threadIdx.x; - if (i >= total) return; - const long long id = i / (kv_heads * (long long) per); - const int rem = (int) (i % (kv_heads * (long long) per)); - const int h = rem / per, q4 = rem - h * per; - const int cell = ids[id]; - const long long page = (long long) table[cell / page_size]; - const long long row = (page * kv_heads + h) * page_size + (cell % page_size); - const int d = q4 * 4; - const int groups = head_dim / KV_Q8_GROUP; - const float ks = f32_from_f16(k_scale[row * groups + d / KV_Q8_GROUP]); - const float vs = f32_from_f16(v_scale[row * groups + d / KV_Q8_GROUP]); - const char4 kc = reinterpret_cast(k_q + row * head_dim)[q4]; - const char4 vc = reinterpret_cast(v_q + row * head_dim)[q4]; - ushort4 ko, vo; - ko.x = f16_from_f32((float) kc.x * ks); ko.y = f16_from_f32((float) kc.y * ks); - ko.z = f16_from_f32((float) kc.z * ks); ko.w = f16_from_f32((float) kc.w * ks); - vo.x = f16_from_f32((float) vc.x * vs); vo.y = f16_from_f32((float) vc.y * vs); - vo.z = f16_from_f32((float) vc.z * vs); vo.w = f16_from_f32((float) vc.w * vs); - const long long dst = (id * kv_heads + h) * (long long) per + q4; - reinterpret_cast(k_scratch)[dst] = ko; - reinterpret_cast(v_scratch)[dst] = vo; -} - -} // namespace - -void kv_append_q8_step(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, const int32_t* page_table, - const int32_t* step, const float* kcur, const float* vcur, const QsaShapes& s, void* stream, - const KvHostPools* host) { - validate(s, "kv_append_q8"); - const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / KV_Q8_GROUP), 2); - kv_append_q8_kernel<<>>( - k_q, v_q, k_scale, v_scale, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim, - (int) s.page_size, host ? *host : KvHostPools{}); - check("kv_append_q8 launch"); -} - -void kv_gather_q8_step(const int8_t* k_q, const int8_t* v_q, const uint16_t* k_scale, const uint16_t* v_scale, - const int32_t* page_table, const int32_t* ids, const int32_t* step, int64_t max_ids, - const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream) { - validate(s, "kv_gather_q8"); - if (max_ids <= 0) return; - const long long total = max_ids * s.n_head_kv * (s.head_dim / 4); - const unsigned blocks = (unsigned) ((total + 255) / 256); - kv_gather_q8_kernel<<>>( - k_q, v_q, k_scale, v_scale, page_table, ids, step, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size, - k_scratch, v_scratch); - check("kv_gather_q8 launch"); -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/kv_stream.cu b/src/kernels/cuda/kv_stream.cu deleted file mode 100644 index 914a836..0000000 --- a/src/kernels/cuda/kv_stream.cu +++ /dev/null @@ -1,276 +0,0 @@ -// src/kernels/cuda/kv_stream.cu - see include/strata/kernels/kv_stream.hpp. -#include "strata/kernels/kv_stream.hpp" -#include "strata/kernels/kv_q4.hpp" -#include "strata/kernels/kv_q8.hpp" - -#include - -#include -#include -#include - -namespace strata::kernels { -namespace { - -void check(const char* what) { - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "kv_stream: %s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -constexpr int RT = 1024; // the resolve block - -// The per-block byte runs of the (up to four) pool arrays: block b of array i is bytes [b * len, (b + 1) * len). -struct Runs { - const uint8_t* src[4]; - uint8_t* dst[4]; - int len[4]; - int n; -}; - -Runs runs_of(const QsaAttnPools& slots, const KvHostPools& host, int fmt, const QsaShapes& s) { - const int rows = (int) (s.n_head_kv * s.page_size); - Runs r{}; - if (fmt == kKvQ4) { - const int bytes = rows * (int) kv_q4_bytes_per_head((int) s.head_dim); - r.src[0] = (const uint8_t*) host.k_q4; r.dst[0] = (uint8_t*) slots.k_q4; r.len[0] = bytes; - r.src[1] = (const uint8_t*) host.v_q4; r.dst[1] = (uint8_t*) slots.v_q4; r.len[1] = bytes; - r.n = 2; - } else if (fmt == kKvInt8) { - const int codes = rows * (int) s.head_dim, scales = rows * (int) (s.head_dim / KV_Q8_GROUP) * 2; - r.src[0] = (const uint8_t*) host.k_q; r.dst[0] = (uint8_t*) slots.k_q; r.len[0] = codes; - r.src[1] = (const uint8_t*) host.v_q; r.dst[1] = (uint8_t*) slots.v_q; r.len[1] = codes; - r.src[2] = (const uint8_t*) host.k_scale; r.dst[2] = (uint8_t*) slots.k_scale; r.len[2] = scales; - r.src[3] = (const uint8_t*) host.v_scale; r.dst[3] = (uint8_t*) slots.v_scale; r.len[3] = scales; - r.n = 4; - } else { - const int bytes = rows * (int) s.head_dim * 2; - r.src[0] = (const uint8_t*) host.k_pool; r.dst[0] = (uint8_t*) slots.k_pool; r.len[0] = bytes; - r.src[1] = (const uint8_t*) host.v_pool; r.dst[1] = (uint8_t*) slots.v_pool; r.len[1] = bytes; - r.n = 2; - } - return r; -} - -// Block-wide exclusive prefix sum of one int per thread (RT threads); `total` is the sum over the block. -__device__ int block_scan(int v, int* warp_sums, int& total) { - const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; - int x = v; - for (int o = 1; o < 32; o <<= 1) { - const int y = __shfl_up_sync(0xffffffffu, x, o); - if (lane >= o) x += y; - } - if (lane == 31) warp_sums[w] = x; - __syncthreads(); - if (w == 0) { - int t = warp_sums[lane]; - for (int o = 1; o < 32; o <<= 1) { - const int y = __shfl_up_sync(0xffffffffu, t, o); - if (lane >= o) t += y; - } - warp_sums[lane] = t; - } - __syncthreads(); - total = warp_sums[31]; - const int excl = x - v + (w > 0 ? warp_sums[w - 1] : 0); - __syncthreads(); - return excl; -} - -__global__ void __launch_bounds__(RT) resolve_kernel(KvStreamMap m, const int32_t* __restrict__ ids, - const int32_t* __restrict__ steps, int n_q, int cap, int page_size) { - __shared__ int s_nmiss, s_lookups, s_cut; - __shared__ int warp_sums[32]; - const int epoch = m.ctl[0] + 1; - if (threadIdx.x == 0) { s_nmiss = 0; s_lookups = 0; } - __syncthreads(); - // 1. hits take this epoch and their reference bit; a missing block is claimed exactly once (-1 -> -2) - int lookups = 0; - for (int q = 0; q < n_q; ++q) { - const int width = steps[q * kStepCount + kStepWidth]; - const int32_t* qi = ids + (long long) q * cap; - for (int i = threadIdx.x; i < width; i += RT) { - const int b = qi[i] / page_size; - if (i > 0 && qi[i - 1] / page_size == b) continue; // ids are ascending: one lookup per block - ++lookups; - const int sl = m.page_table[b]; - if (sl >= 0) { - m.slot_stamp[sl] = epoch; - m.slot_ref[sl] = 1; - } else if (sl == -1 && atomicCAS(&m.page_table[b], -1, -2) == -1) { - m.miss_block[atomicAdd(&s_nmiss, 1)] = b; - } - } - } - atomicAdd(&s_lookups, lookups); - __syncthreads(); - // 2. one victim per miss: a clock sweep from the hand. A slot this call uses (stamp == epoch) is never taken; - // a referenced one loses its bit as the hand passes it and is taken on the next pass. - const int need = s_nmiss, n = (int) m.n_slots; - int hand = m.ctl[1], got = 0; - for (int scanned = 0; got < need && scanned < 3 * n; scanned += RT) { - const int j = (int) (((long long) hand + threadIdx.x) % n); - const bool mine = m.slot_stamp[j] == epoch; - const bool cand = !mine && (m.slot_block[j] < 0 || m.slot_ref[j] == 0); - int total = 0; - const int rank = block_scan(cand ? 1 : 0, warp_sums, total); - const int want = need - got; - if (threadIdx.x == 0) s_cut = RT; - __syncthreads(); - if (cand && rank == want - 1) s_cut = threadIdx.x + 1; // the hand stops just past the last slot taken - __syncthreads(); - const int cut = s_cut; - if (cand && rank < want) { - m.miss_slot[got + rank] = j; - m.slot_stamp[j] = epoch; // taken: a sweep that wraps around must not take it twice - } else if (threadIdx.x < cut && !mine) { - m.slot_ref[j] = 0; - } - got += total < want ? total : want; - hand = (int) (((long long) hand + cut) % n); - __syncthreads(); - } - // 3. re-point the table; the copy kernel fills the slots - const int placed = got < need ? got : need; - for (int k = threadIdx.x; k < need; k += RT) { - const int b = m.miss_block[k]; - if (k >= placed) { m.page_table[b] = -1; continue; } // overflow: never happens with a legal n_slots - const int sl = m.miss_slot[k]; - const int old = m.slot_block[sl]; - if (old >= 0) m.page_table[old] = -1; - m.slot_block[sl] = b; - m.slot_stamp[sl] = epoch; - m.slot_ref[sl] = 1; - m.page_table[b] = sl; - } - if (threadIdx.x == 0) { - m.ctl[0] = epoch; - m.ctl[1] = hand; - m.ctl[2] = placed; - if (placed < need) m.ctl[3] = 1; - unsigned long long* c = reinterpret_cast(m.ctl + 4); - c[0] += (unsigned long long) placed; - c[1] += (unsigned long long) s_lookups; - c[2] += 1ull; - } -} - -// One block per missed block (grid-stride): copy its runs from the host copy into its slot, 16 B per thread. -__global__ void copy_kernel(KvStreamMap m, Runs r) { - const int need = m.ctl[2]; - for (int k = blockIdx.x; k < need; k += gridDim.x) { - const long long b = m.miss_block[k], sl = m.miss_slot[k]; - for (int a = 0; a < r.n; ++a) { - const uint4* src = reinterpret_cast(r.src[a] + b * r.len[a]); - uint4* dst = reinterpret_cast(r.dst[a] + sl * r.len[a]); - for (int i = threadIdx.x; i < r.len[a] / 16; i += blockDim.x) dst[i] = src[i]; - } - } -} - -__global__ void reset_kernel(KvStreamMap m) { - const long long i0 = (long long) blockIdx.x * blockDim.x + threadIdx.x, st = (long long) gridDim.x * blockDim.x; - for (long long i = i0; i < m.n_blocks; i += st) m.page_table[i] = -1; - for (long long i = i0; i < m.n_slots; i += st) { - m.slot_block[i] = -1; - m.slot_stamp[i] = -1; - m.slot_ref[i] = 0; - } - if (i0 < kKvCtlInts) m.ctl[i0] = 0; -} - -__global__ void ring_kernel(int32_t* table, long long n_blocks, long long n_slots) { - for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < n_blocks; - i += (long long) gridDim.x * blockDim.x) - table[i] = (int32_t) (i % n_slots); -} - -} // namespace - -uint64_t kv_block_bytes(const QsaShapes& s, int fmt) { - const uint64_t rows = (uint64_t) (s.n_head_kv * s.page_size); - if (fmt == kKvQ4) return rows * kv_q4_bytes_per_head((int) s.head_dim) * 2; - return fmt == kKvInt8 ? rows * (uint64_t) s.head_dim * 2 + rows * (uint64_t) (s.head_dim / KV_Q8_GROUP) * 2 * 2 - : rows * (uint64_t) s.head_dim * 2 * 2; -} - -void kv_stream_reset(const KvStreamMap& m, void* stream) { - reset_kernel<<<128, 256, 0, (cudaStream_t) stream>>>(m); - check("reset"); -} - -void kv_stream_resolve(const KvStreamMap& m, const QsaAttnPools& slots, const KvHostPools& host, int fmt, - const int32_t* ids, const int32_t* steps, int64_t n_q, int64_t cap, const QsaShapes& s, - void* stream) { - if (n_q <= 0) return; - if (s.n_head_kv * s.page_size * (s.head_dim / KV_Q8_GROUP) * 2 % 16 != 0) { - std::fprintf(stderr, "kv_stream: a block's scale run must be a multiple of 16 bytes\n"); - std::exit(1); - } - // one sweep step looks at RT consecutive slots `(hand + thread) % n_slots`; with fewer slots than RT two - // threads see the same slot and may both take it for two different misses. The engine never streams with fewer - // than qsa_kv_resident_min() / page_size = 5,120 slots, so this is a guard, not a limit. - if (m.n_slots < RT) { - std::fprintf(stderr, "kv_stream: %lld slots is fewer than the resolve block (%d): the clock sweep would take a " - "slot twice\n", (long long) m.n_slots, RT); - std::exit(1); - } - resolve_kernel<<<1, RT, 0, (cudaStream_t) stream>>>(m, ids, steps, (int) n_q, (int) cap, (int) s.page_size); - check("resolve"); - copy_kernel<<<96, 128, 0, (cudaStream_t) stream>>>(m, runs_of(slots, host, fmt, s)); - check("copy"); -} - -void kv_ring_table(int32_t* page_table, int64_t n_blocks, int64_t n_slots, void* stream) { - ring_kernel<<<64, 256, 0, (cudaStream_t) stream>>>(page_table, n_blocks, n_slots); - check("ring table"); -} - -void kv_ring_restore(const QsaAttnPools& slots, const KvHostPools& host, int fmt, int64_t b0, int64_t b1, - int64_t n_slots, const QsaShapes& s, void* stream) { - const Runs r = runs_of(slots, host, fmt, s); - for (int64_t b = b0; b < b1;) { - const int64_t sl = b % n_slots, run = std::min(b1 - b, n_slots - sl); // up to the ring's end - for (int a = 0; a < r.n; ++a) - if (cudaMemcpyAsync(r.dst[a] + sl * r.len[a], r.src[a] + b * r.len[a], (size_t) (run * r.len[a]), - cudaMemcpyDefault, (cudaStream_t) stream) != cudaSuccess) - check("ring restore"); - b += run; - } -} - -void kv_stage_from_host(const QsaAttnPools& stage, const KvHostPools& host, int fmt, int64_t n_blocks, - const QsaShapes& s, void* stream) { - if (n_blocks <= 0) return; - const Runs r = runs_of(stage, host, fmt, s); - for (int a = 0; a < r.n; ++a) - if (cudaMemcpyAsync(r.dst[a], r.src[a], (size_t) (n_blocks * r.len[a]), cudaMemcpyDefault, - (cudaStream_t) stream) != cudaSuccess) - check("stage"); -} - -void kv_unstage_to_host(const QsaAttnPools& stage, const KvHostPools& host, int fmt, int64_t b0, int64_t b1, - const QsaShapes& s, void* stream) { - if (b1 <= b0) return; - const Runs r = runs_of(stage, host, fmt, s); // src: the host copy, dst: the staging pool (identity layout both) - for (int a = 0; a < r.n; ++a) - if (cudaMemcpyAsync((void*) (r.src[a] + b0 * r.len[a]), r.dst[a] + b0 * r.len[a], (size_t) ((b1 - b0) * r.len[a]), - cudaMemcpyDefault, (cudaStream_t) stream) != cudaSuccess) - check("unstage"); -} - -KvStreamCounters kv_stream_counters(const KvStreamMap& m) { - int32_t c[kKvCtlInts] = {}; - KvStreamCounters r; - if (m.ctl == nullptr || cudaMemcpy(c, m.ctl, sizeof(c), cudaMemcpyDeviceToHost) != cudaSuccess) return r; - const unsigned long long* u = reinterpret_cast(c + 4); - r.misses = u[0]; - r.lookups = u[1]; - r.calls = u[2]; - r.overflow = c[3] != 0; - return r; -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/native_bf16.cu b/src/kernels/cuda/native_bf16.cu deleted file mode 100644 index fdbdc94..0000000 --- a/src/kernels/cuda/native_bf16.cu +++ /dev/null @@ -1,199 +0,0 @@ -#include "strata/kernels/bf16_gemv.hpp" -#include "strata/kernels/bf16_bits.hpp" - -#include -#include -#include -#include - -namespace strata::kernels { -namespace { - -// The FP32-activation MMVF implementation below is adapted from llama.cpp -// 3cf03257f219afbe7334045ff7c6a06ac68c627d, ggml/src/ggml-cuda/{mmvf.cu,common.cuh}. -// Scope: ordinary contiguous BF16 matrix, one FP32 activation vector, no fusion/ids/channels. -// -// MIT License -// Copyright (c) 2023-2026 The ggml authors -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -__device__ __forceinline__ float mmvf_warp_sum(float value) { -#pragma unroll - for (int offset = 16; offset > 0; offset >>= 1) - value += __shfl_xor_sync(0xffffffffu, value, offset, 32); - return value; -} - -template -__global__ void bf16_f32_mmvf_kernel(const float* __restrict__ x, const uint16_t* __restrict__ w, - float* __restrict__ y, int n_in) { - const int t = threadIdx.x; - const uint16_t* row = w + (size_t) blockIdx.x * n_in; - const uint32_t* weights2 = reinterpret_cast(row); - const float2* inputs2 = reinterpret_cast(x); - __shared__ float partials[32]; - if constexpr (BLOCK_SIZE > 32) { - if (t < 32) partials[t] = 0.0f; - __syncthreads(); - } - float acc = 0.0f; - for (int pair = t; pair < n_in / 2; pair += BLOCK_SIZE) { - const uint32_t weight = weights2[pair]; - const float2 input = inputs2[pair]; - // Match the two ordered multiply-adds in ggml_cuda_mad, not a pair sum followed by one add. - acc = __fmaf_rn(f32_from_bf16((uint16_t) weight), input.x, acc); - acc = __fmaf_rn(f32_from_bf16((uint16_t) (weight >> 16)), input.y, acc); - } - acc = mmvf_warp_sum(acc); - if constexpr (BLOCK_SIZE > 32) { - // All lanes have the same reduced value; one store avoids a same-value shared-memory race. - if ((t & 31) == 0) partials[t / 32] = acc; - __syncthreads(); - if (t < 32) acc = mmvf_warp_sum(partials[t]); - } - if (t == 0) y[blockIdx.x] = acc; -} - -// the same kernel for up to 8 activation rows - the weight row is read ONCE and every -// token keeps its own accumulator with exactly the single-row kernel's order (pairs, two ordered FMAs, the same warp -// and block reductions), so each output is bit-identical to a bf16_f32_mmvf_kernel launch of its own. -template -__global__ void bf16_f32_mmvf_multi_kernel(const float* __restrict__ x, int64_t ldx, const uint16_t* __restrict__ w, - float* __restrict__ y, int64_t ldy, int n_in, int n_tok) { - const int t = threadIdx.x; - const uint16_t* row = w + (size_t) blockIdx.x * n_in; - const uint32_t* weights2 = reinterpret_cast(row); - __shared__ float partials[NT][32]; - if constexpr (BLOCK_SIZE > 32) { - if (t < 32) -#pragma unroll - for (int k = 0; k < NT; ++k) partials[k][t] = 0.0f; - __syncthreads(); - } - float acc[NT]; -#pragma unroll - for (int k = 0; k < NT; ++k) acc[k] = 0.0f; - for (int pair = t; pair < n_in / 2; pair += BLOCK_SIZE) { - const uint32_t weight = weights2[pair]; - const float w0 = f32_from_bf16((uint16_t) weight), w1 = f32_from_bf16((uint16_t) (weight >> 16)); -#pragma unroll - for (int k = 0; k < NT; ++k) { - if (k < n_tok) { - const float2 input = reinterpret_cast(x + (size_t) k * ldx)[pair]; - acc[k] = __fmaf_rn(w0, input.x, acc[k]); - acc[k] = __fmaf_rn(w1, input.y, acc[k]); - } - } - } -#pragma unroll - for (int k = 0; k < NT; ++k) acc[k] = mmvf_warp_sum(acc[k]); - if constexpr (BLOCK_SIZE > 32) { - if ((t & 31) == 0) -#pragma unroll - for (int k = 0; k < NT; ++k) partials[k][t / 32] = acc[k]; - __syncthreads(); - if (t < 32) -#pragma unroll - for (int k = 0; k < NT; ++k) acc[k] = mmvf_warp_sum(partials[k][t]); - } - if (t == 0) -#pragma unroll - for (int k = 0; k < NT; ++k) - if (k < n_tok) y[(size_t) k * ldy + blockIdx.x] = acc[k]; -} - -int mmvf_block_size(int64_t n_in) { - int best = 32; - int64_t best_iterations = (n_in + 63) / 64; - for (int candidate = 64; candidate <= 256; candidate += 32) { - const int64_t iterations = (n_in + 2 * candidate - 1) / (2 * candidate); - if (iterations < best_iterations) { - best_iterations = iterations; - best = candidate; - } - } - return best; -} - -} // namespace - -void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy, - int64_t n_in, int64_t n_out, int n_tok, void* stream) { - if (n_tok == 1 && ldy >= n_out) { bf16_gemv_fp32_mmvf(x, w, y, n_in, n_out, stream); return; } - if (n_tok < 1 || n_tok > 8 || n_in <= 0 || (n_in & 1) != 0 || n_out <= 0 || (ldx & 1) != 0 || x == nullptr || - w == nullptr || y == nullptr || (reinterpret_cast(x) & 7u) != 0) - throw std::invalid_argument("bf16_gemv_fp32_mmvf_multi: 1..8 rows, even n_in/ldx, aligned pointers"); - const cudaStream_t st = (cudaStream_t) stream; -#define STRATA_MMVF_M(N) case N: \ - if (n_tok <= 4) bf16_f32_mmvf_multi_kernel<<<(unsigned) n_out, N, 0, st>>>(x, ldx, w, y, ldy, (int) n_in, n_tok); \ - else bf16_f32_mmvf_multi_kernel<<<(unsigned) n_out, N, 0, st>>>(x, ldx, w, y, ldy, (int) n_in, n_tok); break - switch (mmvf_block_size(n_in)) { - STRATA_MMVF_M(32); STRATA_MMVF_M(64); STRATA_MMVF_M(96); STRATA_MMVF_M(128); - STRATA_MMVF_M(160); STRATA_MMVF_M(192); STRATA_MMVF_M(224); STRATA_MMVF_M(256); - } -#undef STRATA_MMVF_M - const cudaError_t result = cudaGetLastError(); - if (result != cudaSuccess) - throw std::runtime_error(std::string("bf16_gemv_fp32_mmvf_multi launch: ") + cudaGetErrorString(result)); -} - -void bf16_gemv_fp32_mmvf(const float* x, const uint16_t* w, float* y, - int64_t n_in, int64_t n_out, void* stream) { - if (n_in <= 0 || (n_in & 1) != 0 || n_in > std::numeric_limits::max() || - n_out <= 0 || n_out > std::numeric_limits::max()) - throw std::invalid_argument("bf16_gemv_fp32_mmvf: require positive even n_in and positive n_out <= INT_MAX"); - if (x == nullptr || w == nullptr || y == nullptr || - (reinterpret_cast(x) & 7u) != 0 || - (reinterpret_cast(w) & 3u) != 0 || - (reinterpret_cast(y) & 3u) != 0) - throw std::invalid_argument("bf16_gemv_fp32_mmvf: null or misaligned pointer"); - const cudaStream_t st = (cudaStream_t) stream; -#define STRATA_MMVF_CASE(N) case N: \ - bf16_f32_mmvf_kernel<<<(unsigned) n_out, N, 0, st>>>(x, w, y, (int) n_in); break - switch (mmvf_block_size(n_in)) { - STRATA_MMVF_CASE(32); - STRATA_MMVF_CASE(64); - STRATA_MMVF_CASE(96); - STRATA_MMVF_CASE(128); - STRATA_MMVF_CASE(160); - STRATA_MMVF_CASE(192); - STRATA_MMVF_CASE(224); - STRATA_MMVF_CASE(256); - } -#undef STRATA_MMVF_CASE - const cudaError_t result = cudaGetLastError(); - if (result != cudaSuccess) - throw std::runtime_error(std::string("bf16_gemv_fp32_mmvf launch: ") + cudaGetErrorString(result)); -} - - - -void bf16_gemv_fp32_mmvf_cols(const float* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, int ncols, - void* stream) { - // columns contiguous: the existing multi-row kernel (weight read once, each output bitwise its one-row call), - // up to 8 rows per launch - for (int c0 = 0; c0 < ncols; c0 += 8) { - const int nc = ncols - c0 < 8 ? ncols - c0 : 8; - if (nc == 1) bf16_gemv_fp32_mmvf(x + (size_t) c0 * n_in, w, y + (size_t) c0 * n_out, n_in, n_out, stream); - else bf16_gemv_fp32_mmvf_multi(x + (size_t) c0 * n_in, n_in, w, y + (size_t) c0 * n_out, n_out, n_in, n_out, nc, - stream); - } -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/native_flash_attn.cu b/src/kernels/cuda/native_flash_attn.cu deleted file mode 100644 index 5a4f36d..0000000 --- a/src/kernels/cuda/native_flash_attn.cu +++ /dev/null @@ -1,212 +0,0 @@ -// Specialized from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d, -// ggml/src/ggml-cuda/{fattn-vec.cuh,fattn-common.cuh,common.cuh}. -// MIT License -// Copyright (c) 2023-2026 The ggml authors -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -#include "strata/kernels/native_flash_attn.hpp" -#include -#include -#include -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { -template __device__ __forceinline__ float warp_sum(float x) { -#pragma unroll - for (int offset = Width / 2; offset; offset >>= 1) - x += __shfl_xor_sync(0xffffffffu, x, offset, Width); - return x; -} -__device__ __forceinline__ float warp_max(float x) { -#pragma unroll - for (int offset = 16; offset; offset >>= 1) - x = fmaxf(x, __shfl_xor_sync(0xffffffffu, x, offset, 32)); - return x; -} - -// D=256,ncols=1,F16/F16; 128 threads, nthreads_KQ=nthreads_V=8, -// four values (float2) per load, four V columns per iteration. Padded length256 -// gives ntiles_KV=ceil(256/D)=1, so the pinned launcher selects grid.y=1. -__launch_bounds__(128, 1) -__global__ void attend(const float* __restrict__ q, const half* __restrict__ k, - const half* __restrict__ v, const int32_t* __restrict__ step, - int max_context, int padded_length, float scale, float* __restrict__ out, int32_t* __restrict__ status, - const half* __restrict__ mask) { - const int lane = threadIdx.x, warp = threadIdx.y, tid = warp * 32 + lane; - const int head = blockIdx.x, kv = head / 12; - const int width = step[kStepWidth], nkv = step[kStepNKv]; - const bool valid = width >= 1 && width <= max_context && nkv == width && - step[kStepPos] == width - 1 && step[kStepNBid] == width / 4; - if (head == 0 && tid == 0) - *status = valid ? kNativeFlashAttnSuccess : kNativeFlashAttnUnsupportedStep; - if (!valid) { - out[head * 256 + tid] = __int_as_float(0x7fc00000); - out[head * 256 + tid + 128] = __int_as_float(0x7fc00000); - return; - } - float2 qreg[16]; - float2 vkq[16] = {}; - __shared__ float tile[4 * 4 * 256]; - __shared__ float max_shared[32], sum_shared[32]; - float maximum = -FLT_MAX / 2.0f, sum = 0.0f; -#pragma unroll - for (int i0 = 0; i0 < 128; i0 += 32) { - const int i = i0 + (lane % 8) * 4; -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int d = 2 * (i + j); - qreg[i0 / 8 + j] = make_float2(q[head * 256 + d] * scale, - q[head * 256 + d + 1] * scale); - } - } - for (int base = 0; base < padded_length; base += 128) { - float score = 0.0f, next_max = maximum; -#pragma unroll - for (int row = 0; row < 8; ++row) { - const int cell = base + warp * 32 + (lane & ~7) + row; - float dot = 0.0f; -#pragma unroll - for (int i0 = 0; i0 < 128; i0 += 32) { - const int i = i0 + (lane % 8) * 4; -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int d = 2 * (i + j); - const float a = cell < width ? __half2float(k[(cell * 2 + kv) * 256 + d]) : 0.0f; - const float b = cell < width ? __half2float(k[(cell * 2 + kv) * 256 + d + 1]) : 0.0f; - dot += a * qreg[i0 / 8 + j].x; - dot += b * qreg[i0 / 8 + j].y; - } - } - dot = warp_sum<8>(dot); - dot += cell < width ? (mask ? __half2float(mask[cell]) : 0.0f) : __int_as_float(0xff800000u); - next_max = fmaxf(next_max, dot + (3.0f * 0.6931f)); - if (lane % 8 == row) score = dot; - } -#pragma unroll - for (int offset = 8; offset < 32; offset <<= 1) - next_max = fmaxf(next_max, __shfl_xor_sync(0xffffffffu, next_max, offset, 32)); - const float rescale = expf(maximum - next_max); - maximum = next_max; - score = expf(score - maximum); - sum = sum * rescale + score; - tile[tid] = score; - __syncwarp(); -#pragma unroll - for (int k0 = 0; k0 < 32; k0 += 4) { - const int local = warp * 32 + k0 + lane / 8, cell = base + local; - const float weight = tile[local]; -#pragma unroll - for (int i0 = 0; i0 < 128; i0 += 32) { - const int i = i0 + (lane % 8) * 4; -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int d = 2 * (i + j); - const float a = cell < width ? __half2float(v[(cell * 2 + kv) * 256 + d]) : 0.0f; - const float b = cell < width ? __half2float(v[(cell * 2 + kv) * 256 + d + 1]) : 0.0f; - // The pinned sm120a binary contracts the old-accumulator - // rescale with the FIRST addition: fma(rescale,old,round(V*w)). - // Later columns use fma(V,w,acc). Explicit intrinsics retain - // that order despite this adapter's masked-load branches. - if (k0 == 0) { - vkq[i0 / 8 + j].x = __fmaf_rn(rescale, vkq[i0 / 8 + j].x, __fmul_rn(a, weight)); - vkq[i0 / 8 + j].y = __fmaf_rn(rescale, vkq[i0 / 8 + j].y, __fmul_rn(b, weight)); - } else { - vkq[i0 / 8 + j].x = __fmaf_rn(a, weight, vkq[i0 / 8 + j].x); - vkq[i0 / 8 + j].y = __fmaf_rn(b, weight, vkq[i0 / 8 + j].y); - } - } - } - } - } - if (warp == 0) { max_shared[lane] = -FLT_MAX / 2.0f; sum_shared[lane] = 0.0f; } - __syncthreads(); - if (lane == 0) max_shared[warp] = maximum; - __syncthreads(); - const float global_max = warp_max(max_shared[lane]); - const float rescale = expf(maximum - global_max); -#pragma unroll - for (int i = 0; i < 16; ++i) { - vkq[i].x = __fmul_rn(vkq[i].x, rescale); - vkq[i].y = __fmul_rn(vkq[i].y, rescale); - } -#pragma unroll - for (int i0 = 0; i0 < 128; i0 += 32) { - const int start = warp * 4 * 256 + (lane / 8) * 256 + 2 * (i0 + (lane % 8) * 4); -#pragma unroll - for (int j = 0; j < 4; ++j) { - tile[start + 2 * j] = vkq[i0 / 8 + j].x; - tile[start + 2 * j + 1] = vkq[i0 / 8 + j].y; - } - } - sum *= rescale; - sum = warp_sum<32>(sum); - if (lane == 0) sum_shared[warp] = sum; - __syncthreads(); - sum = warp_sum<32>(sum_shared[lane]); -#pragma unroll - for (int i0 = 0; i0 < 256; i0 += 128) { - float result = 0.0f; -#pragma unroll - for (int w = 0; w < 4; ++w) { -#pragma unroll - for (int group = 0; group < 4; ++group) - result += tile[w * 4 * 256 + group * 256 + i0 + tid]; - } - out[head * 256 + i0 + tid] = result / sum; - } -} -struct Span { const void* p; std::size_t n, alignment; }; -void validate_spans(const Span* spans, int count) { - for (int i = 0; i < count; ++i) { - const auto a = reinterpret_cast(spans[i].p); - if (!a || a % spans[i].alignment || spans[i].n > UINTPTR_MAX - a) - throw std::invalid_argument("native FlashAttention requires nonnull aligned bounded spans"); - for (int j = 0; j < i; ++j) { - const auto b = reinterpret_cast(spans[j].p); - if (a < b + spans[j].n && b < a + spans[i].n) - throw std::invalid_argument("native FlashAttention requires disjoint buffers"); - } - } -} -} // namespace - -void native_flash_attn_short_step(const float* q, const uint16_t* k, const uint16_t* v, - const int32_t* step, int64_t capacity, int max_context, - const QsaShapes& shapes, float* output, int32_t* status, - const uint16_t* mask, void* stream) { - if (!stream || shapes.n_head != 24 || shapes.n_head_kv != 2 || shapes.head_dim != 256 || - shapes.idx_block != 4 || shapes.idx_top_k < 256 || capacity < 256 || - uint64_t(capacity) > std::numeric_limits::max() / 1024 || - max_context < 1 || max_context > 256) - throw std::invalid_argument("native FlashAttention supports only Q24x256/KV2x256, capacity>=256 and context1..256 on an explicit stream"); - const std::size_t kv_bytes = std::size_t(capacity) * 1024; - const Span spans[] = {{q, 24 * 256 * 4, 4}, {k, kv_bytes, 2}, {v, kv_bytes, 2}, - {step, kStepCount * 4, 4}, {output, 24 * 256 * 4, 4}, - {status, 4, 4}, {mask, 256 * 2, 2}}; - validate_spans(spans, mask ? 7 : 6); - attend<<<24, dim3(32, 4), 0, static_cast(stream)>>>(q, reinterpret_cast(k), - reinterpret_cast(v), step, max_context, 256, 0.0625f, output, status, reinterpret_cast(mask)); - const auto result = cudaGetLastError(); - if (result != cudaSuccess) - throw std::runtime_error(std::string("native FlashAttention launch: ") + cudaGetErrorString(result)); -} -} // namespace strata::kernels diff --git a/src/kernels/cuda/native_gdn.cu b/src/kernels/cuda/native_gdn.cu deleted file mode 100644 index 6661d50..0000000 --- a/src/kernels/cuda/native_gdn.cu +++ /dev/null @@ -1,122 +0,0 @@ -// Arithmetic adapted from gated_delta_net.cu at pinned llama.cpp -// 3cf03257f219afbe7334045ff7c6a06ac68c627d. Only state addressing differs: -// each warp owns one Strata (head,column) and retains its four rows in registers. -// Compile with --use_fast_math to match the pinned CUDA implementation. -// -// MIT License -// Copyright (c) 2023-2026 The ggml authors -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -#include "strata/kernels/native_gdn.hpp" -#include -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { -std::atomic enabled{false}; -constexpr int S = 128; - -__device__ __forceinline__ float warp_sum(float value) { -#pragma unroll - for (int offset = 16; offset > 0; offset >>= 1) - value += __shfl_xor_sync(0xffffffff, value, offset, 32); - return value; -} - -__global__ void __launch_bounds__(128, 2) -step(float* __restrict__ state, const float* __restrict__ q, const float* __restrict__ k, - const float* __restrict__ v, const float* __restrict__ gate, const float* __restrict__ beta, - float* __restrict__ output, int h_k, int h_v, float scale) { - const int head = blockIdx.x; - const int lane = threadIdx.x; - const int col = blockIdx.z * blockDim.y + threadIdx.y; - const int q_head = head % h_k; - float s_shard[4], k_reg[4], q_reg[4]; -#pragma unroll - for (int r = 0; r < 4; ++r) { - const int i = r * 32 + lane; - s_shard[r] = state[(size_t(i) * h_v + head) * S + col]; - k_reg[r] = k[q_head * S + i]; - q_reg[r] = q[q_head * S + i]; - } - const float g_val = expf(gate[head]); - float kv_shard = 0.0f; -#pragma unroll - for (int r = 0; r < 4; ++r) kv_shard += s_shard[r] * k_reg[r]; - const float kv_col = warp_sum(kv_shard); - const float delta_col = (v[head * S + col] - g_val * kv_col) * beta[head]; - float attn_partial = 0.0f; -#pragma unroll - for (int r = 0; r < 4; ++r) { - s_shard[r] = g_val * s_shard[r] + k_reg[r] * delta_col; - attn_partial += s_shard[r] * q_reg[r]; - } - const float attn_col = warp_sum(attn_partial); - if (lane == 0) output[head * S + col] = attn_col * scale; -#pragma unroll - for (int r = 0; r < 4; ++r) { - const int i = r * 32 + lane; - state[(size_t(i) * h_v + head) * S + col] = s_shard[r]; - } -} - -bool valid_span(const void* pointer, size_t bytes) { - const auto address = reinterpret_cast(pointer); - return pointer && address % sizeof(float) == 0 && bytes <= UINTPTR_MAX - address; -} -bool overlap(const void* a, size_t an, const void* b, size_t bn) { - const auto ap = reinterpret_cast(a), bp = reinterpret_cast(b); - return ap < bp + bn && bp < ap + an; -} -} - -void native_gdn_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); } -bool native_gdn_enabled() { return enabled.load(std::memory_order_relaxed); } - -void native_gdn_step(float* state, const float* q, const float* k, const float* v, - const float* gate, const float* beta, float* output, - const GdnShapes& shape, void* stream) { - if (!stream || shape.S != S || shape.h_k <= 0 || shape.h_v <= 0 || - shape.h_v > 65535 || shape.h_v % shape.h_k != 0) - throw std::invalid_argument("native GDN requires a stream, S=128 and positive divisible head counts <=65535"); - const size_t state_bytes = size_t(S) * S * size_t(shape.h_v) * sizeof(float); - const size_t qk_bytes = size_t(S) * size_t(shape.h_k) * sizeof(float); - const size_t output_bytes = size_t(S) * size_t(shape.h_v) * sizeof(float); - const size_t head_bytes = size_t(shape.h_v) * sizeof(float); - if (!valid_span(state, state_bytes) || !valid_span(output, output_bytes) || - overlap(state, state_bytes, output, output_bytes)) - throw std::invalid_argument("native GDN requires aligned, disjoint state and output spans"); - const void* inputs[] = {q, k, v, gate, beta}; - const size_t bytes[] = {qk_bytes, qk_bytes, output_bytes, head_bytes, head_bytes}; - for (int i = 0; i < 5; ++i) { - if (!valid_span(inputs[i], bytes[i]) || overlap(state, state_bytes, inputs[i], bytes[i]) || - overlap(output, output_bytes, inputs[i], bytes[i])) - throw std::invalid_argument("native GDN requires aligned input spans disjoint from state and output"); - } - const float scale = 1.0f / sqrtf(float(S)); - step<<(stream)>>>( - state, q, k, v, gate, beta, output, int(shape.h_k), int(shape.h_v), scale); - const auto error = cudaGetLastError(); - if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); -} -} // namespace strata::kernels diff --git a/src/kernels/cuda/native_gdn_preprocess.cu b/src/kernels/cuda/native_gdn_preprocess.cu deleted file mode 100644 index b11e004..0000000 --- a/src/kernels/cuda/native_gdn_preprocess.cu +++ /dev/null @@ -1,202 +0,0 @@ -// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d: -// ggml/src/ggml-cuda/{norm.cu,common.cuh,unary.cu,unary.cuh,ssm-conv.cu,scale.cu}. -// Compile with --use_fast_math, as the pinned backend does. -// -// MIT License -// Copyright (c) 2023-2026 The ggml authors -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -#include "strata/kernels/native_gdn_preprocess.hpp" -#include -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { -constexpr int S = 128; - -__device__ __forceinline__ float warp_sum(float value) { -#pragma unroll - for (int offset = 16; offset > 0; offset >>= 1) - value += __shfl_xor_sync(0xffffffffu, value, offset, 32); - return value; -} -__device__ __forceinline__ float norm_sum(float value, float* sums) { - const int lane = threadIdx.x % 32; - value = warp_sum(value); - if (lane == 0) sums[threadIdx.x / 32] = value; - __syncthreads(); - value = lane < 8 ? sums[lane] : 0.0f; - return warp_sum(value); -} -__device__ __forceinline__ float sigmoid(float value) { return 1.0f / (1.0f + expf(-value)); } - -__global__ void conv_silu(float* __restrict__ history, const float* __restrict__ input, - const float* __restrict__ weights, float* __restrict__ raw_output, - float* __restrict__ silu_output, int channels) { - const int c = blockIdx.x * blockDim.x + threadIdx.x; - if (c >= channels) return; - float values[4] = {history[c * 3], history[c * 3 + 1], history[c * 3 + 2], input[c]}; - float sum = 0.0f; -#pragma unroll - for (int tap = 0; tap < 4; ++tap) sum += values[tap] * weights[c * 4 + tap]; - // The native SSM kernel adds its zero bias even when there is no bias input. - sum = __fadd_rn(sum, 0.0f); - raw_output[c] = sum; - silu_output[c] = sum / (1.0f + expf(-sum)); -#pragma unroll - for (int tap = 0; tap < 3; ++tap) history[c * 3 + tap] = values[tap + 1]; -} - -__global__ void l2_norm(float* input, float epsilon, float scale_after) { - const int col = threadIdx.x; - input += size_t(blockIdx.x) * S; - const float value = col < S ? input[col] : 0.0f; - float partial = 0.0f; - if (col < S) partial += value * value; - __shared__ float sums[32]; - partial = norm_sum(partial, sums); - const float scale = rsqrtf(partial / S + epsilon); - if (col < S) { - // Preserve the FP32 store boundary between RMSNorm and ggml_scale. - const float normalized = __fmul_rn(scale, value); - input[col] = __fmaf_rn(normalized, scale_after, 0.0f); - } -} - -__global__ void beta_sigmoid(float* beta, int count) { - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i < count) beta[i] = sigmoid(beta[i]); -} -__global__ void gate_softplus(const float* __restrict__ alpha, const float* __restrict__ dt, - const float* __restrict__ ssm_a, float* __restrict__ gate, int count) { - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i >= count) return; - const float value = __fadd_rn(alpha[i], dt[i]); - const float softplus = value > 20.0f ? value : log1pf(expf(value)); // 1 + e^v loses e^v below ~1e-7 - gate[i] = softplus * ssm_a[i]; -} - -__global__ void out_norm(const float* __restrict__ input, const float* __restrict__ z, - 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; - float partial = 0.0f; - if (col < S) partial += value * value; - __shared__ float sums[32]; - partial = norm_sum(partial, sums); - const float scale = rsqrtf(partial / S + epsilon); - if (col < S) { - // RMSNorm+gamma is one pinned fused operator, followed by sigmoid*mul (qwen4exp) or silu*mul (qwen35moe, - // ggml-cuda unary.cu op_silu: x / (1 + expf(-x))). - const float weighted = __fmul_rn(__fmul_rn(scale, value), gamma[col]); - const float zz = z[offset + col]; - output[offset + col] = weighted * (silu ? zz / (1.0f + expf(-zz)) : sigmoid(zz)); - } -} - -struct Span { const void* pointer; size_t bytes; }; -void valid(Span span) { - const auto address = reinterpret_cast(span.pointer); - if (!span.pointer || address % sizeof(float) || span.bytes > UINTPTR_MAX - address) - throw std::invalid_argument("native GDN preprocessing requires aligned nonnull valid spans"); -} -void disjoint(Span a, Span b) { - const auto ap = reinterpret_cast(a.pointer), bp = reinterpret_cast(b.pointer); - if (ap < bp + b.bytes && bp < ap + a.bytes) - throw std::invalid_argument("native GDN preprocessing requires disjoint writable spans"); -} -void count_and_stream(int64_t count, void* stream) { - if (!stream || count <= 0 || count > 65535) - throw std::invalid_argument("native GDN preprocessing requires a stream and count in [1,65535]"); -} -void norm_geometry(int64_t rows, int64_t cols, float epsilon, void* stream) { - count_and_stream(rows, stream); - if (cols != S || !std::isfinite(epsilon) || epsilon < 0.0f) - throw std::invalid_argument("native GDN norm requires width 128 and finite nonnegative epsilon"); -} -void check_launch() { - const auto error = cudaGetLastError(); - if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); -} -} - -void native_gdn_conv_silu(float* history, const float* input, const float* weights, - float* raw_output, float* silu_output, int64_t channels, - int64_t d_conv, void* stream) { - count_and_stream(channels, stream); - if (d_conv != 4) throw std::invalid_argument("native GDN convolution requires four taps"); - const size_t bytes = size_t(channels) * sizeof(float); - const Span writable[] = {{history, 3 * bytes}, {raw_output, bytes}, {silu_output, bytes}}; - const Span inputs[] = {{input, bytes}, {weights, 4 * bytes}}; - for (auto span : writable) valid(span); - for (auto span : inputs) valid(span); - for (int i = 0; i < 3; ++i) { - for (int j = 0; j < i; ++j) disjoint(writable[i], writable[j]); - for (auto span : inputs) disjoint(writable[i], span); - } - conv_silu<<(stream)>>>( - history, input, weights, raw_output, silu_output, int(channels)); - check_launch(); -} -void native_gdn_l2_norm(float* input, int64_t rows, int64_t cols, float epsilon, void* stream) { - norm_geometry(rows, cols, epsilon, stream); - valid({input, size_t(rows) * S * sizeof(float)}); - l2_norm<<(stream)>>>(input, epsilon / S, 1.0f / sqrtf(float(S))); - check_launch(); -} -void native_gdn_beta_gate(float* beta, int64_t heads, void* stream) { - count_and_stream(heads, stream); - valid({beta, size_t(heads) * sizeof(float)}); - beta_sigmoid<<(stream)>>>(beta, int(heads)); - check_launch(); -} -void native_gdn_gate(const float* alpha, const float* dt, const float* ssm_a, - float* gate, int64_t heads, void* stream) { - count_and_stream(heads, stream); - const size_t bytes = size_t(heads) * sizeof(float); - const Span output{gate, bytes}; - valid(output); - for (auto input : {Span{alpha, bytes}, Span{dt, bytes}, Span{ssm_a, bytes}}) { - valid(input); - disjoint(output, input); - } - gate_softplus<<(stream)>>>(alpha, dt, ssm_a, gate, int(heads)); - check_launch(); -} -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) { - norm_geometry(heads, cols, epsilon, stream); - const size_t bytes = size_t(heads) * S * sizeof(float); - const Span writable{destination, bytes}; - valid(writable); - for (auto input : {Span{output, bytes}, Span{z, bytes}, Span{gamma, S * sizeof(float)}}) { - valid(input); - disjoint(writable, input); - } - out_norm<<(stream)>>>(output, z, gamma, destination, epsilon, - act == GdnGate::Silu ? 1 : 0); - check_launch(); -} -} // namespace strata::kernels diff --git a/src/kernels/cuda/native_gr_norm.cu b/src/kernels/cuda/native_gr_norm.cu deleted file mode 100644 index 5abe013..0000000 --- a/src/kernels/cuda/native_gr_norm.cu +++ /dev/null @@ -1,102 +0,0 @@ -// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d: -// ggml/src/ggml-cuda/{norm.cu,common.cuh}. Scope: contiguous weighted F32 RMSNorm. -// -// MIT License -// Copyright (c) 2023-2026 The ggml authors -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -#include "strata/kernels/native_gr_norm.hpp" - -#include -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { - -__device__ __forceinline__ float norm_warp_sum(float value) { -#pragma unroll - for (int offset = 16; offset > 0; offset >>= 1) { - value += __shfl_xor_sync(0xffffffffu, value, offset, 32); - } - return value; -} - -template -__global__ void weighted_rms_norm(const float* __restrict__ input, - const float* __restrict__ gamma, - float* __restrict__ output, int n_cols, float epsilon) { - const int tid = threadIdx.x; - const std::size_t row_offset = std::size_t(blockIdx.x) * n_cols; - input += row_offset; - gamma += row_offset; - output += row_offset; - float partial = 0.0f; - for (int col = tid; col < n_cols; col += BlockSize) { - const float value = input[col]; - partial += value * value; - } - - // Pinned block_reduce: every warp repeats the final XOR - // reduction. There is no warp-0-only broadcast or downward-shuffle tree. - __shared__ float sums[32]; - partial = norm_warp_sum(partial); - const int lane = tid % 32; - if (lane == 0) sums[tid / 32] = partial; - __syncthreads(); - partial = 0.0f; - if (lane < BlockSize / 32) partial = sums[lane]; - partial = norm_warp_sum(partial); - - const float mean = partial / n_cols; - const float scale = rsqrtf(mean + epsilon); - for (int col = tid; col < n_cols; col += BlockSize) { - output[col] = scale * input[col] * gamma[col]; - } -} - -void check_pointer(const void* p) { - if (!p || reinterpret_cast(p) % alignof(float) != 0) - throw std::invalid_argument("native GR RMSNorm requires non-null four-byte aligned pointers"); -} - -} // namespace - -void native_gr_rms_norm_weighted(const float* input, const float* gamma, float* output, - int n_cols, int n_rows, float epsilon, void* stream) { - if (n_cols <= 0 || n_rows <= 0 || !std::isfinite(epsilon) || epsilon < 0.0f) - throw std::invalid_argument("native GR RMSNorm requires positive dimensions and finite nonnegative epsilon"); - check_pointer(input); - check_pointer(gamma); - check_pointer(output); - const auto cuda_stream = static_cast(stream); - if (n_cols < 1024) - weighted_rms_norm<256><<>>(input, gamma, output, n_cols, epsilon); - else - weighted_rms_norm<1024><<>>(input, gamma, output, n_cols, epsilon); - const auto error = cudaGetLastError(); - if (error != cudaSuccess) - throw std::runtime_error(std::string("native GR RMSNorm launch: ") + cudaGetErrorString(error)); -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/native_gr_postops.cu b/src/kernels/cuda/native_gr_postops.cu deleted file mode 100644 index 8616e33..0000000 --- a/src/kernels/cuda/native_gr_postops.cu +++ /dev/null @@ -1,115 +0,0 @@ -// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d: -// ggml/src/ggml-cuda/{dsv4-hc.cu,scale.cu,unary.cu,unary.cuh}. -// -// MIT License -// Copyright (c) 2023-2026 The ggml authors -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -#include "strata/kernels/native_gr_postops.hpp" -#include -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { -constexpr int THREADS = 256; -__device__ __forceinline__ float sigmoid(float x) { return 1.0f / (1.0f + expf(-x)); } -// ggml SCALE uses scale*x+bias, including its +0 bias. Retain this operation -// explicitly so compile-time zero does not change signed-zero behavior. -__device__ __forceinline__ float scale_zero_bias(float x, float scale) { - return __fmaf_rn(scale, x, 0.0f); -} -__global__ void down_silu(float* lo, int count, float scale) { - const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x; - if (i >= std::size_t(count)) return; - const float x = scale_zero_bias(lo[i], scale); - lo[i] = x / (1.0f + expf(-x)); -} -template -__global__ void pre_gated(const float* __restrict__ xn, float* __restrict__ gate, - float* __restrict__ mixed, int n_embd, int hc, float scale) { - const std::size_t d = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x; - if (d >= std::size_t(n_embd)) return; - float sum = 0.0f; - for (int c = 0; c < hc; ++c) { - const std::size_t i = std::size_t(c) * n_embd + d; - const float x = xn[i], w = sigmoid(gate[i]); - const float product = __fmul_rn(x, w); - gate[i] = product; - if constexpr (Fused) sum = __fmaf_rn(x, w, sum); - else sum = c == 0 ? product : __fadd_rn(sum, product); - } - if constexpr (Fused) mixed[d] = scale * sum; - else mixed[d] = scale_zero_bias(sum, scale); -} -__global__ void post(const float* residual, const float* __restrict__ block_out, - const float* __restrict__ inject, float* output, - int n_embd, int hc, float scale) { - const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x; - if (i >= std::size_t(n_embd) * hc) return; - const int c = int(i / n_embd), d = int(i % n_embd); - const float weight = scale_zero_bias(sigmoid(scale_zero_bias(inject[c], scale)), 2.0f); - // Exact residual/output alias is supported; no other thread reads residual[i]. - output[i] = __fmaf_rn(block_out[d], weight, residual[i]); -} -void check_pointer(const void* p) { - if (!p || reinterpret_cast(p) % alignof(float)) - throw std::invalid_argument("native GR postops require non-null four-byte aligned pointers"); -} -void check_shape(int n, int hc) { - if (n <= 0 || hc <= 0 || std::uint64_t(n) * hc > std::uint64_t(std::numeric_limits::max())) - throw std::invalid_argument("native GR postops require positive bounded dimensions"); -} -unsigned blocks(std::size_t n) { return unsigned((n + THREADS - 1) / THREADS); } -void check_launch() { - const auto error = cudaGetLastError(); - if (error != cudaSuccess) - throw std::runtime_error(std::string("native GR postops launch: ") + cudaGetErrorString(error)); -} -} // namespace - -void native_gr_down_silu(float* lo, int hc_lr, int hc, void* stream) { - check_shape(hc_lr, hc); - check_pointer(lo); - down_silu<<(stream)>>>(lo, hc_lr, 1.0f / float(hc)); - check_launch(); -} -void native_gr_pre_gated(const float* xn, float* gate, float* mixed, - int n_embd, int hc, bool fused_layer, void* stream) { - check_shape(n_embd, hc); - check_pointer(xn); check_pointer(gate); check_pointer(mixed); - if (fused_layer) - pre_gated<<(stream)>>>(xn, gate, mixed, n_embd, hc, 1.0f / float(hc)); - else - pre_gated<<(stream)>>>(xn, gate, mixed, n_embd, hc, 1.0f / float(hc)); - check_launch(); -} -void native_gr_post(const float* residual, const float* block_out, const float* inject, - float* output, int n_embd, int hc, void* stream) { - check_shape(n_embd, hc); - check_pointer(residual); check_pointer(block_out); check_pointer(inject); check_pointer(output); - post<<(stream)>>>( - residual, block_out, inject, output, n_embd, hc, 1.0f / float(hc)); - check_launch(); -} -} // namespace strata::kernels diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu deleted file mode 100644 index e0d11bf..0000000 --- a/src/kernels/cuda/native_mmvq.cu +++ /dev/null @@ -1,1619 +0,0 @@ -// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d: -// ggml/src/ggml-cuda/{quantize.cu,vecdotq.cuh,mmvq.cu,common.cuh} -// and ggml/src/ggml-common.h. See docs/native-mmvq.md for exact scope. -// -// MIT License -// Copyright (c) 2023-2026 The ggml authors -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -#include "strata/kernels/native_mmvq.hpp" -#include "strata/kernels/dp4a.hpp" -#include "strata/kernels/q8_1_finite.hpp" -#include "strata/kernels/iq_kernels.hpp" - -#include -#include - -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int QK = 256; -constexpr int Q8K = 32; -constexpr int QI = 32; -constexpr int VDR = 2; -constexpr int WARPS = 4; -constexpr int WARP = 32; -constexpr int QUANT_THREADS = 256; - -struct Q5KBlock { - half2 dm; - uint8_t scales[12]; - uint8_t qh[32]; - uint8_t qs[128]; -}; -struct Q81Block { - half2 ds; - int8_t qs[32]; -}; -struct Q20Block { - half d; - uint8_t qs[16]; -}; -struct Q3KBlock { - uint8_t hmask[32]; - uint8_t qs[64]; - uint8_t scales[12]; - half d; -}; -struct IQ4XSBlock { - half d; - uint16_t scales_h; - uint8_t scales_l[4]; - uint8_t qs[128]; -}; -struct Q4KBlock { - half2 dm; - uint8_t scales[12]; - uint8_t qs[128]; -}; -struct Q6KBlock { - uint8_t ql[128]; - uint8_t qh[64]; - int8_t scales[16]; - half d; -}; -struct Q40Block { - half d; - uint8_t qs[16]; -}; -struct Q50Block { - half d; - uint8_t qh[4]; - uint8_t qs[16]; -}; -struct Q80Block { - half d; - int8_t qs[32]; -}; -struct IQ4NLBlock { - half d; - uint8_t qs[16]; -}; -static_assert(sizeof(Q5KBlock) == 176 && alignof(Q5KBlock) == 4); -static_assert(sizeof(Q81Block) == 36 && alignof(Q81Block) == 4); -static_assert(sizeof(Q20Block) == 18 && alignof(Q20Block) == 2 && offsetof(Q20Block, qs) == 2); -static_assert(sizeof(Q3KBlock) == 110 && alignof(Q3KBlock) == 2 && offsetof(Q3KBlock, qs) == 32 && - offsetof(Q3KBlock, scales) == 96 && offsetof(Q3KBlock, d) == 108); -static_assert(sizeof(IQ4XSBlock) == 136 && alignof(IQ4XSBlock) == 2 && - offsetof(IQ4XSBlock, scales_h) == 2 && offsetof(IQ4XSBlock, scales_l) == 4 && - offsetof(IQ4XSBlock, qs) == 8); -static_assert(offsetof(Q5KBlock, scales) == 4 && offsetof(Q5KBlock, qh) == 16 && - offsetof(Q5KBlock, qs) == 48 && offsetof(Q81Block, qs) == 4); -static_assert(sizeof(Q4KBlock) == 144 && alignof(Q4KBlock) == 4 && - offsetof(Q4KBlock, scales) == 4 && offsetof(Q4KBlock, qs) == 16); -static_assert(sizeof(Q6KBlock) == 210 && alignof(Q6KBlock) == 2 && - offsetof(Q6KBlock, qh) == 128 && offsetof(Q6KBlock, scales) == 192 && - offsetof(Q6KBlock, d) == 208); -static_assert(sizeof(Q40Block) == 18 && alignof(Q40Block) == 2 && offsetof(Q40Block, qs) == 2); -static_assert(sizeof(Q50Block) == 22 && alignof(Q50Block) == 2 && - offsetof(Q50Block, qh) == 2 && offsetof(Q50Block, qs) == 6); -static_assert(sizeof(Q80Block) == 34 && alignof(Q80Block) == 2 && offsetof(Q80Block, qs) == 2); -static_assert(sizeof(IQ4NLBlock) == 18 && alignof(IQ4NLBlock) == 2 && offsetof(IQ4NLBlock, qs) == 2); - -__device__ __forceinline__ float warp_sum(float x) { -#pragma unroll - for (int offset = WARP / 2; offset > 0; offset >>= 1) { - x += __shfl_xor_sync(0xffffffff, x, offset, WARP); - } - return x; -} - -__device__ __forceinline__ float warp_max(float x) { -#pragma unroll - for (int offset = WARP / 2; offset > 0; offset >>= 1) { - x = fmaxf(x, __shfl_xor_sync(0xffffffff, x, offset, WARP)); - } - return x; -} - -__launch_bounds__(QUANT_THREADS, 1) -__global__ void native_quantize_q8_1_kernel(const float* __restrict__ x, - Q81Block* __restrict__ y, int n_in) { - const int i = int(blockIdx.x) * QUANT_THREADS + int(threadIdx.x); - if (i >= n_in) return; // n_in is a multiple of 32: only whole warps return. - const float xi = x[i]; - const float amax = warp_max(fabsf(xi)); - const float sum = warp_sum(xi); - const float d = q8_1_finite(amax / 127.0f); // #606: q8_1_finite.hpp - the same bits for every finite block - const int8_t q = q8_1_quant(xi, d, amax); - y[i / Q8K].qs[i % Q8K] = q; - if (i % Q8K == 0) y[i / Q8K].ds = q8_1_ds(d, sum); -} - -__launch_bounds__(QUANT_THREADS, 1) -__global__ void native_swiglu_quantize_q8_1_kernel(const float* __restrict__ gate, - const float* __restrict__ up, - Q81Block* __restrict__ y, int n_in) { - const int i = int(blockIdx.x) * QUANT_THREADS + int(threadIdx.x); - if (i >= n_in) return; // n_in is a multiple of 32: only whole warps return. - const float gi = gate[i]; - const float xi = __fmul_rn(__fdividef(gi, __fadd_rn(1.0f, __expf(-gi))), up[i]); - const float amax = warp_max(fabsf(xi)); - const float sum = warp_sum(xi); - const float d = amax / 127.0f; - const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); - y[i / Q8K].qs[i % Q8K] = q; - if (i % Q8K == 0) y[i / Q8K].ds = make_half2(d, sum); -} - -// Exact pinned vec_dot_q5_K_q8_1_impl_vmmq expression and integer dot order. -__device__ __forceinline__ float q5_q8_dot_impl( - const int* __restrict__ vl, const int* __restrict__ vh, const int* __restrict__ u, - const uint8_t* __restrict__ sc, const uint8_t* __restrict__ m, const half2& dm5, - const float* __restrict__ d8) { - float sumf_d = 0.0f; - float sumf_m = 0.0f; -#pragma unroll - for (int i = 0; i < 2; ++i) { - const int vl0i = (vl[0] >> (4 * i)) & 0x0f0f0f0f; - const int vl1i = (vl[1] >> (4 * i)) & 0x0f0f0f0f; - const int vh0i = ((vh[0] >> i) << 4) & 0x10101010; - const int vh1i = ((vh[1] >> i) << 4) & 0x10101010; - const int v0i = vl0i | vh0i; - const int v1i = vl1i | vh1i; - const int dot1 = STRATA_DP4A(v0i, u[2 * i], STRATA_DP4A(v1i, u[2 * i + 1], 0)); - const int dot2 = STRATA_DP4A(0x01010101, u[2 * i], STRATA_DP4A(0x01010101, u[2 * i + 1], 0)); - sumf_d += d8[i] * (dot1 * sc[i]); - sumf_m += d8[i] * (dot2 * m[i]); - } - const float2 dm5f = __half22float2(dm5); - return dm5f.x * sumf_d - dm5f.y * sumf_m; -} - -__device__ __forceinline__ float q5_q8_dot(const Q5KBlock* __restrict__ bq5, - const Q81Block* __restrict__ bq8, int iqs) { - int vl[2]; - int vh[2]; - int u[4]; - float d8[2]; - const int bq8_offset = 2 * ((iqs / 2) / 4); - const int* ql = reinterpret_cast(bq5->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4)); - const int* qh = reinterpret_cast(bq5->qh + 4 * ((iqs / 2) % 4)); - vl[0] = ql[0]; - vl[1] = ql[4]; - vh[0] = qh[0] >> bq8_offset; - vh[1] = qh[4] >> bq8_offset; - - const uint16_t* scales = reinterpret_cast(bq5->scales); - const int j = bq8_offset / 2; - const int jm = j & 1; - const uint32_t s0 = scales[jm]; - const uint32_t s2 = scales[jm + 2]; - const uint32_t s4 = scales[jm + 4]; - const uint32_t hi = uint32_t(-int32_t(j >= 2)); - uint16_t aux[2]; - aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) | - ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi)); - aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) | - ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi)); - const uint8_t* sc = reinterpret_cast(aux); - const uint8_t* m = sc + 2; -#pragma unroll - for (int i = 0; i < 2; ++i) { - const Q81Block* bq8i = bq8 + bq8_offset + i; - d8[i] = __low2float(bq8i->ds); - const int* q8 = reinterpret_cast(bq8i->qs) + ((iqs / 2) % 4); - u[2 * i] = q8[0]; - u[2 * i + 1] = q8[4]; - } - return q5_q8_dot_impl(vl, vh, u, sc, m, bq5->dm, d8); -} - -// The generic ncols=1 oracle uses 4 warps and 1 row (or 4 rows for small K), -// eight weight blocks per K iteration, warp-ascending shared sum, then XOR tree. -template -__launch_bounds__(WARPS * WARP, 1) -__global__ void native_q5_k_mmvq_kernel(const Q5KBlock* __restrict__ w, - const Q81Block* __restrict__ x, - float* __restrict__ y, int n_in, int n_out) { - constexpr int ROWS = SmallK ? WARPS : 1; - constexpr int BLOCKS_PER_ITER = VDR * WARPS * WARP / QI; - const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); - const int row0 = ROWS * int(blockIdx.x); - const int blocks_per_row = n_in / QK; - float tmp[ROWS] = {}; - for (int kbx = tid / (QI / VDR); kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) { - const int kby = kbx * (QK / Q8K); - const int kqs = VDR * (tid % (QI / VDR)); -#pragma unroll - for (int i = 0; i < ROWS; ++i) { - // The source assumes allocator padding for partial row groups. This - // guard preserves every valid row's math without an out-of-bounds read. - if (row0 + i < n_out) { - const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx; - tmp[i] += q5_q8_dot(w + block, x + kby, kqs); - } - } - } - __shared__ float partial[WARPS - 1][ROWS][WARP]; - if (threadIdx.y > 0) { -#pragma unroll - for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i]; - } - __syncthreads(); - if (threadIdx.y > 0) return; -#pragma unroll - for (int i = 0; i < ROWS; ++i) { -#pragma unroll - for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x]; - tmp[i] = warp_sum(tmp[i]); - if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i]; - } -} - -// Exact pinned vec_dot_q2_0_q8_1: each thread handles one 32-element chunk. -// The weight block is only 2-byte aligned, so qs is intentionally loaded as -// int16_t, unlike the naturally 4-byte aligned activation codes. -__device__ __forceinline__ float q2_q8_dot(const Q20Block* __restrict__ w, - const Q81Block* __restrict__ x, int iqs) { - const float d2 = w->d; - const int16_t* qs = reinterpret_cast(w->qs) + iqs * 4; - const Q81Block* chunk = x + iqs; - const int* q8 = reinterpret_cast(chunk->qs); - int sumi = 0; -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int q = qs[j]; - const int u = q8[j * 2]; - const int v = q8[j * 2 + 1]; - const int qe = __byte_perm(0x020100ff, 0x020100ff, q >> 0); - const int qo = __byte_perm(0x020100ff, 0x020100ff, q >> 2); - const int qx = __byte_perm(qe, qo, 0x5140); - const int qy = __byte_perm(qe, qo, 0x7362); - sumi = STRATA_DP4A(u, qx, sumi); - sumi = STRATA_DP4A(v, qy, sumi); - } - const float d8 = __low2float(chunk->ds); - return d2 * d8 * sumi; -} - -// Q2_0 generic MMVQ: QK=64, QI=2, VDR=1, 64 blocks per iteration. -// Preserve the same outer accumulation and cross-warp reduction as the oracle. -template -__launch_bounds__(WARPS * WARP, 1) -__global__ void native_q2_0_mmvq_kernel(const Q20Block* __restrict__ w, - const Q81Block* __restrict__ x, - float* __restrict__ y, int n_in, int n_out) { - constexpr int ROWS = SmallK ? WARPS : 1; - constexpr int BLOCKS_PER_ITER = WARPS * WARP / 2; - const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); - const int row0 = ROWS * int(blockIdx.x); - const int blocks_per_row = n_in / 64; - float tmp[ROWS] = {}; - for (int kbx = tid / 2; kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) { - const int kby = kbx * 2; - const int kqs = tid % 2; -#pragma unroll - for (int i = 0; i < ROWS; ++i) { - if (row0 + i < n_out) { - const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx; - tmp[i] += q2_q8_dot(w + block, x + kby, kqs); - } - } - } - __shared__ float partial[WARPS - 1][ROWS][WARP]; - if (threadIdx.y > 0) { -#pragma unroll - for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i]; - } - __syncthreads(); - if (threadIdx.y > 0) return; -#pragma unroll - for (int i = 0; i < ROWS; ++i) { -#pragma unroll - for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x]; - tmp[i] = warp_sum(tmp[i]); - if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i]; - } -} - -// Q3_K's 110-byte stride gives alternate blocks only two-byte alignment. -// Preserve the pinned helper's pair of 16-bit loads and little-endian combine. -__device__ __forceinline__ int load_int_b2(const void* ptr, int i32) { - const auto* x = static_cast(ptr); - int value = x[2 * i32] << 0; - value |= x[2 * i32 + 1] << 16; - return value; -} - -__device__ __forceinline__ float q3_q8_dot_impl(int vl, int vh, const int* __restrict__ u, - const uint8_t* __restrict__ scales, - int scale_offset, float d3, - const float* __restrict__ d8) { - float sumf = 0.0f; -#pragma unroll - for (int i = 0; i < 4; ++i) { - const int isc = scale_offset + 2 * i; - const int isc_low = isc % 8; - const int sc_shift_low = 4 * (isc / 8); - const int sc_low = (scales[isc_low] >> sc_shift_low) & 0xf; - const int isc_high = isc % 4; - const int sc_shift_high = 2 * (isc / 4); - const int sc_high = ((scales[8 + isc_high] >> sc_shift_high) & 3) << 4; - const int sc = (sc_low | sc_high) - 32; - const int vil = (vl >> (2 * i)) & 0x03030303; - const int vih = ((vh >> i) << 2) & 0x04040404; - const int vi = __vsubss4(vil, vih); - sumf += d8[i] * (STRATA_DP4A(vi, u[i], 0) * sc); - } - return d3 * sumf; -} - -__device__ __forceinline__ float q3_q8_dot(const Q3KBlock* __restrict__ w, - const Q81Block* __restrict__ x, int iqs) { - const int bq8_offset = 4 * (iqs / 8); - const int scale_offset = iqs - iqs % 8 + (iqs % 8) / 4; - const float d = w->d; - const int vl = load_int_b2(w->qs, iqs); - const int vh = ~load_int_b2(w->hmask, iqs % 8) >> bq8_offset; - int u[4]; - float d8[4]; -#pragma unroll - for (int i = 0; i < 4; ++i) { - u[i] = reinterpret_cast(x[bq8_offset + i].qs)[iqs % 8]; - d8[i] = __low2float(x[bq8_offset + i].ds); - } - return q3_q8_dot_impl(vl, vh, u, w->scales, scale_offset, d, d8); -} - -// Q3_K generic MMVQ: QK=256, QI=16, VDR=1, eight blocks per iteration. -template -__launch_bounds__(WARPS * WARP, 1) -__global__ void native_q3_k_mmvq_kernel(const Q3KBlock* __restrict__ w, - const Q81Block* __restrict__ x, - float* __restrict__ y, int n_in, int n_out) { - constexpr int ROWS = SmallK ? WARPS : 1; - constexpr int BLOCKS_PER_ITER = WARPS * WARP / 16; - const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); - const int row0 = ROWS * int(blockIdx.x); - const int blocks_per_row = n_in / 256; - float tmp[ROWS] = {}; - for (int kbx = tid / 16; kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) { - const int kby = kbx * 8; - const int kqs = tid % 16; -#pragma unroll - for (int i = 0; i < ROWS; ++i) { - if (row0 + i < n_out) { - const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx; - tmp[i] += q3_q8_dot(w + block, x + kby, kqs); - } - } - } - __shared__ float partial[WARPS - 1][ROWS][WARP]; - if (threadIdx.y > 0) { -#pragma unroll - for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i]; - } - __syncthreads(); - if (threadIdx.y > 0) return; -#pragma unroll - for (int i = 0; i < ROWS; ++i) { -#pragma unroll - for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x]; - tmp[i] = warp_sum(tmp[i]); - if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i]; - } -} - -// The pinned nonlinear IQ4 codebook and its CUDA two-stage byte lookup. The -// explicit alignment satisfies the four 32-bit table loads; values are unchanged. -__device__ __align__(4) int8_t iq4nl_values[16] = { - -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113 -}; - -__device__ __forceinline__ int2 iq4_table_lookup(int q4) { -#if defined(STRATA_HIP_GFX906) - // AMD: llama.cpp's HIP lookup (see iq_kernels.cu get_int_from_table_16): 4 v_perm_b32 per 8 values - const uint32_t* v32 = reinterpret_cast(iq4nl_values); - const uint32_t q_even = (uint32_t) q4, q_odd = (uint32_t) q4 >> 4; - const uint32_t el = __builtin_amdgcn_perm(v32[1], v32[0], q_even & 0x07070707u); - const uint32_t ol = __builtin_amdgcn_perm(v32[1], v32[0], q_odd & 0x07070707u); - const uint32_t eh = __builtin_amdgcn_perm(v32[3], v32[2], q_even & 0x07070707u); - const uint32_t oh = __builtin_amdgcn_perm(v32[3], v32[2], q_odd & 0x07070707u); - return make_int2((int) __builtin_amdgcn_perm(eh, el, 0x03020100u | ((q_even & 0x08080808u) >> 1)), - (int) __builtin_amdgcn_perm(oh, ol, 0x03020100u | ((q_odd & 0x08080808u) >> 1))); -#else - const uint32_t* table32 = reinterpret_cast(iq4nl_values); - uint32_t tmp[2]; - const uint32_t low_high_selection_indices = 0x32103210 | ((q4 & 0x88888888) >> 1); -#pragma unroll - for (uint32_t i = 0; i < 2; ++i) { - const uint32_t shift = 16 * i; - const uint32_t low = __byte_perm(table32[0], table32[1], q4 >> shift); - const uint32_t high = __byte_perm(table32[2], table32[3], q4 >> shift); - tmp[i] = __byte_perm(low, high, low_high_selection_indices >> shift); - } - return make_int2(__byte_perm(tmp[0], tmp[1], 0x6420), __byte_perm(tmp[0], tmp[1], 0x7531)); -#endif -} - -// Exact pinned vec_dot_iq4_xs_q8_1: a lane consumes one 32-element subblock, -// computes integer dot products, applies signed scale in the integer domain, -// then multiplies the two half scales and integer sum in the original order. -__device__ __forceinline__ float iq4_xs_q8_dot(const IQ4XSBlock* __restrict__ w, - const Q81Block* __restrict__ x, int iqs) { - int sumi = 0; -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int aux_q4 = reinterpret_cast(w->qs)[iqs + j]; - const int2 v = iq4_table_lookup(aux_q4); - const int u0 = reinterpret_cast(x[iqs / 4].qs)[j]; - const int u1 = reinterpret_cast(x[iqs / 4].qs)[j + 4]; - sumi = STRATA_DP4A(v.x, u0, sumi); - sumi = STRATA_DP4A(v.y, u1, sumi); - } - const int ls = ((w->scales_l[iqs / 8] >> (iqs & 0x04)) & 0x0f) | - (((w->scales_h >> (iqs / 2)) & 0x03) << 4); - sumi *= ls - 32; - const float d = __half2float(w->d) * __low2float(x[iqs / 4].ds); - return d * sumi; -} - -// IQ4_XS generic MMVQ: QK=256, QI=32, VDR=4,16 blocks per iteration. -template -__launch_bounds__(WARPS * WARP, 1) -__global__ void native_iq4_xs_mmvq_kernel(const IQ4XSBlock* __restrict__ w, - const Q81Block* __restrict__ x, - float* __restrict__ y, int n_in, int n_out) { - constexpr int ROWS = SmallK ? WARPS : 1; - constexpr int BLOCKS_PER_ITER = 4 * WARPS * WARP / 32; - const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); - const int row0 = ROWS * int(blockIdx.x); - const int blocks_per_row = n_in / 256; - float tmp[ROWS] = {}; - for (int kbx = tid / 8; kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) { - const int kby = kbx * 8; - const int kqs = 4 * (tid % 8); -#pragma unroll - for (int i = 0; i < ROWS; ++i) { - if (row0 + i < n_out) { - const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx; - tmp[i] += iq4_xs_q8_dot(w + block, x + kby, kqs); - } - } - } - __shared__ float partial[WARPS - 1][ROWS][WARP]; - if (threadIdx.y > 0) { -#pragma unroll - for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i]; - } - __syncthreads(); - if (threadIdx.y > 0) return; -#pragma unroll - for (int i = 0; i < ROWS; ++i) { -#pragma unroll - for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x]; - tmp[i] = warp_sum(tmp[i]); - if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i]; - } -} - -// Exact pinned vec_dot_q4_K_q8_1_impl_vmmq expression and integer dot order. -__device__ __forceinline__ float q4_q8_dot_impl( - const int* __restrict__ v, const int* __restrict__ u, - const uint8_t* __restrict__ sc, const uint8_t* __restrict__ m, const half2& dm4, - const float* __restrict__ d8) { - float sumf_d = 0.0f; - float sumf_m = 0.0f; -#pragma unroll - for (int i = 0; i < 2; ++i) { - const int v0i = (v[0] >> (4 * i)) & 0x0f0f0f0f; - const int v1i = (v[1] >> (4 * i)) & 0x0f0f0f0f; - const int dot1 = STRATA_DP4A(v1i, u[2 * i + 1], STRATA_DP4A(v0i, u[2 * i], 0)); - const int dot2 = STRATA_DP4A(0x01010101, u[2 * i + 1], STRATA_DP4A(0x01010101, u[2 * i], 0)); - sumf_d += d8[i] * (dot1 * sc[i]); - sumf_m += d8[i] * (dot2 * m[i]); - } - const float2 dm4f = __half22float2(dm4); - return dm4f.x * sumf_d - dm4f.y * sumf_m; -} - -__device__ __forceinline__ float q4_q8_dot(const Q4KBlock* __restrict__ bq4, - const Q81Block* __restrict__ bq8, int iqs) { - int v[2]; - int u[4]; - float d8[2]; - const int bq8_offset = 2 * ((iqs / 2) / 4); - const int* ql = reinterpret_cast(bq4->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4)); - v[0] = ql[0]; - v[1] = ql[4]; - - const uint16_t* scales = reinterpret_cast(bq4->scales); - const int j = bq8_offset / 2; - const int jm = j & 1; - const uint32_t s0 = scales[jm]; - const uint32_t s2 = scales[jm + 2]; - const uint32_t s4 = scales[jm + 4]; - const uint32_t hi = uint32_t(-int32_t(j >= 2)); - uint16_t aux[2]; - aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) | - ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi)); - aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) | - ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi)); - const uint8_t* sc = reinterpret_cast(aux); - const uint8_t* m = sc + 2; -#pragma unroll - for (int i = 0; i < 2; ++i) { - const Q81Block* bq8i = bq8 + bq8_offset + i; - d8[i] = __low2float(bq8i->ds); - const int* q8 = reinterpret_cast(bq8i->qs) + ((iqs / 2) % 4); - u[2 * i] = q8[0]; - u[2 * i + 1] = q8[4]; - } - return q4_q8_dot_impl(v, u, sc, m, bq4->dm, d8); -} - -// The generic ncols=1 oracle uses 4 warps and 1 row (or 4 rows for small K), -// eight weight blocks per K iteration, warp-ascending shared sum, then XOR tree. -template -__launch_bounds__(WARPS * WARP, 1) -__global__ void native_q4_k_mmvq_kernel(const Q4KBlock* __restrict__ w, - const Q81Block* __restrict__ x, - float* __restrict__ y, int n_in, int n_out) { - constexpr int ROWS = SmallK ? WARPS : 1; - constexpr int BLOCKS_PER_ITER = VDR * WARPS * WARP / QI; - const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); - const int row0 = ROWS * int(blockIdx.x); - const int blocks_per_row = n_in / QK; - float tmp[ROWS] = {}; - for (int kbx = tid / (QI / VDR); kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) { - const int kby = kbx * (QK / Q8K); - const int kqs = VDR * (tid % (QI / VDR)); -#pragma unroll - for (int i = 0; i < ROWS; ++i) { - // The source assumes allocator padding for partial row groups. This - // guard preserves every valid row's math without an out-of-bounds read. - if (row0 + i < n_out) { - const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx; - tmp[i] += q4_q8_dot(w + block, x + kby, kqs); - } - } - } - __shared__ float partial[WARPS - 1][ROWS][WARP]; - if (threadIdx.y > 0) { -#pragma unroll - for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i]; - } - __syncthreads(); - if (threadIdx.y > 0) return; -#pragma unroll - for (int i = 0; i < ROWS; ++i) { -#pragma unroll - for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x]; - tmp[i] = warp_sum(tmp[i]); - if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i]; - } -} - -// Exact pinned vec_dot_q6_K_q8_1: keep signed per-16-element scales, -// signed-byte subtraction, DP4A order, and the float accumulation sequence. -__device__ __forceinline__ float q6_q8_dot_impl(int vl, int vh, const int* __restrict__ u, - const int8_t* __restrict__ scales, - float d, const float* __restrict__ d8) { - float sumf = 0.0f; -#pragma unroll - for (int i = 0; i < 2; ++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); - sumf += d8[i] * (STRATA_DP4A(vi, u[i], 0) * sc); - } - return d * sumf; -} - -__device__ __forceinline__ float q6_q8_dot(const Q6KBlock* __restrict__ w, - const Q81Block* __restrict__ x, int iqs) { - const int bq8_offset = 4 * (iqs / 16) + (iqs % 16) / 8; - const int scale_offset = 8 * (iqs / 16) + (iqs % 16) / 4; - const int vh_shift = 2 * ((iqs % 16) / 8); - const int vl = load_int_b2(w->ql, iqs); - const int vh = load_int_b2(w->qh, 8 * (iqs / 16) + iqs % 8) >> vh_shift; - int u[2]; - float d8[2]; -#pragma unroll - for (int i = 0; i < 2; ++i) { - u[i] = reinterpret_cast(x[bq8_offset + 2 * i].qs)[iqs % 8]; - d8[i] = __low2float(x[bq8_offset + 2 * i].ds); - } - return q6_q8_dot_impl(vl, vh, u, w->scales + scale_offset, w->d, d8); -} - -// Q6_K generic MMVQ: QK=256, QI=32, VDR=1, four blocks per iteration. -template -__launch_bounds__(WARPS * WARP, 1) -__global__ void native_q6_k_mmvq_kernel(const Q6KBlock* __restrict__ w, - const Q81Block* __restrict__ x, - float* __restrict__ y, int n_in, int n_out) { - constexpr int ROWS = SmallK ? WARPS : 1; - constexpr int BLOCKS_PER_ITER = WARPS * WARP / 32; - const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); - const int row0 = ROWS * int(blockIdx.x); - const int blocks_per_row = n_in / 256; - float tmp[ROWS] = {}; - for (int kbx = tid / 32; kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) { - const int kby = kbx * 8; - const int kqs = tid % 32; -#pragma unroll - for (int i = 0; i < ROWS; ++i) { - if (row0 + i < n_out) { - const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx; - tmp[i] += q6_q8_dot(w + block, x + kby, kqs); - } - } - } - __shared__ float partial[WARPS - 1][ROWS][WARP]; - if (threadIdx.y > 0) { -#pragma unroll - for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i]; - } - __syncthreads(); - if (threadIdx.y > 0) return; -#pragma unroll - for (int i = 0; i < ROWS; ++i) { -#pragma unroll - for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x]; - tmp[i] = warp_sum(tmp[i]); - if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i]; - } -} - -// The four 32-element formats use native two-byte loads and VDR=2. The affine -// Q4_0/Q5_0 correction consumes the original-input sum stored in Q8_1, exactly -// as the pinned CUDA dot does; a signed-integer code substitution would differ. -__device__ __forceinline__ float small_q8_dot(const Q40Block* __restrict__ w, - const Q81Block* __restrict__ x, int iqs) { - int sumi = 0; -#pragma unroll - for (int i = 0; i < 2; ++i) { - const int v = load_int_b2(w->qs, iqs + i); - const int vi0 = (v >> 0) & 0x0f0f0f0f; - const int vi1 = (v >> 4) & 0x0f0f0f0f; - sumi = STRATA_DP4A(vi0, reinterpret_cast(x->qs)[iqs + i], sumi); - sumi = STRATA_DP4A(vi1, reinterpret_cast(x->qs)[iqs + i + 4], sumi); - } - const float2 ds = __half22float2(x->ds); - const float d = w->d; - return d * (sumi * ds.x - 4 * ds.y); -} - -__device__ __forceinline__ float small_q8_dot(const Q50Block* __restrict__ w, - const Q81Block* __restrict__ x, int iqs) { - int sumi = 0; -#pragma unroll - for (int i = 0; i < 2; ++i) { - const int vl = load_int_b2(w->qs, iqs + i); - const int vh = load_int_b2(w->qh, 0) >> (4 * (iqs + i)); - int vi0 = (vl >> 0) & 0x0f0f0f0f; - vi0 |= (vh << 4) & 0x00000010; - vi0 |= (vh << 11) & 0x00001000; - vi0 |= (vh << 18) & 0x00100000; - vi0 |= (vh << 25) & 0x10000000; - sumi = STRATA_DP4A(vi0, reinterpret_cast(x->qs)[iqs + i], sumi); - int vi1 = (vl >> 4) & 0x0f0f0f0f; - vi1 |= (vh >> 12) & 0x00000010; - vi1 |= (vh >> 5) & 0x00001000; - vi1 |= (vh << 2) & 0x00100000; - vi1 |= (vh << 9) & 0x10000000; - sumi = STRATA_DP4A(vi1, reinterpret_cast(x->qs)[iqs + i + 4], sumi); - } - const float2 ds = __half22float2(x->ds); - const float d = w->d; - return d * (sumi * ds.x - 8 * ds.y); -} - -__device__ __forceinline__ float small_q8_dot(const Q80Block* __restrict__ w, - const Q81Block* __restrict__ x, int iqs) { - int sumi = 0; -#pragma unroll - for (int i = 0; i < 2; ++i) { - const int v = load_int_b2(w->qs, iqs + i); - const int u = reinterpret_cast(x->qs)[iqs + i]; - sumi = STRATA_DP4A(v, u, sumi); - } - const float d0 = w->d; - const float d1 = __low2float(x->ds); - return d0 * d1 * float(sumi); -} - -__device__ __forceinline__ float small_q8_dot(const IQ4NLBlock* __restrict__ w, - const Q81Block* __restrict__ x, int iqs) { - const int* q8 = reinterpret_cast(x->qs) + iqs; - int sumi = 0; -#pragma unroll - for (int i = 0; i < 2; ++i) { - const int2 v = iq4_table_lookup(load_int_b2(w->qs, iqs + i)); - sumi = STRATA_DP4A(v.x, q8[i], sumi); - sumi = STRATA_DP4A(v.y, q8[i + 4], sumi); - } - const float d = __half2float(w->d) * __low2float(x->ds); - return d * sumi; -} - -// QI=4 for Q4_0/Q5_0/IQ4_NL and QI=8 for Q8_0. With VDR=2 this preserves -// the pinned 64/32-block iteration and 2048/1024-element small-K thresholds. -template -__launch_bounds__(WARPS * WARP, 1) -__global__ void native_small_mmvq_kernel(const Weight* __restrict__ w, - const Q81Block* __restrict__ x, - float* __restrict__ y, int n_in, int n_out) { - constexpr int ROWS = SmallK ? WARPS : 1; - constexpr int BLOCKS_PER_ITER = 2 * WARPS * WARP / Qi; - const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); - const int row0 = ROWS * int(blockIdx.x); - const int blocks_per_row = n_in / 32; - float tmp[ROWS] = {}; - for (int kbx = tid / (Qi / 2); kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) { - const int kqs = 2 * (tid % (Qi / 2)); -#pragma unroll - for (int i = 0; i < ROWS; ++i) { - if (row0 + i < n_out) { - const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx; - tmp[i] += small_q8_dot(w + block, x + kbx, kqs); - } - } - } - __shared__ float partial[WARPS - 1][ROWS][WARP]; - if (threadIdx.y > 0) { -#pragma unroll - for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i]; - } - __syncthreads(); - if (threadIdx.y > 0) return; -#pragma unroll - for (int i = 0; i < ROWS; ++i) { -#pragma unroll - for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x]; - tmp[i] = warp_sum(tmp[i]); - if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i]; - } -} - -// ============================ plan v0.3 P3: ncols = 2..8 (speculative verify, small batches) ============================ -// -// One generic kernel for every format, parameterized by the format's iteration traits below, which are -// transcribed from the ncols = 1 kernels above (same thread-to-block mapping, same blocks per iteration, same -// small-K rule). Column j reads activation blocks x + j * (n_in / 32) and writes y + j * n_out. Each (column, -// row) value is accumulated over kbx in the same order, summed across warps in the same order and reduced with -// the same warp tree as the ncols = 1 kernel, so every column is BITWISE equal to a single-column call on that -// column (checked by bench/micro/native_mmvq_multi.cpp). The ncols = 1 kernels are untouched. -constexpr int MAX_NCOLS = 8; - -// Each format splits its dot product into `load` (everything that depends only on the weight block: codes, -// unpacked scales, block scale) and `apply` (the activation loads and the original *_impl expression). `load` runs -// once per (row, block) and `apply` once per column, so adding columns adds only activation work. `apply` calls -// the same impl functions, in the same order, with the same values as the ncols = 1 dot, which is what keeps -// every column bitwise equal to it. -struct Q5KTraits { - using Block = Q5KBlock; - static constexpr int DIV = QK, T = QI / VDR, KBY = QK / Q8K, BPI = VDR * WARPS * WARP / QI; - __device__ static int kqs(int tid) { return VDR * (tid % (QI / VDR)); } - struct W { int vl[2], vh[2]; uint16_t aux[2]; half2 dm; int bq8_offset; }; - __device__ static W load(const Block* __restrict__ bq5, int iqs) { - W r; - r.bq8_offset = 2 * ((iqs / 2) / 4); - const int* ql = reinterpret_cast(bq5->qs + 16 * r.bq8_offset + 4 * ((iqs / 2) % 4)); - const int* qh = reinterpret_cast(bq5->qh + 4 * ((iqs / 2) % 4)); - r.vl[0] = ql[0]; - r.vl[1] = ql[4]; - r.vh[0] = qh[0] >> r.bq8_offset; - r.vh[1] = qh[4] >> r.bq8_offset; - const uint16_t* scales = reinterpret_cast(bq5->scales); - const int j = r.bq8_offset / 2; - const int jm = j & 1; - const uint32_t s0 = scales[jm]; - const uint32_t s2 = scales[jm + 2]; - const uint32_t s4 = scales[jm + 4]; - const uint32_t hi = uint32_t(-int32_t(j >= 2)); - r.aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) | ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi)); - r.aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) | ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi)); - r.dm = bq5->dm; - return r; - } - __device__ static float apply(const W& r, const Q81Block* __restrict__ bq8, int iqs) { - int u[4]; - float d8[2]; -#pragma unroll - for (int i = 0; i < 2; ++i) { - const Q81Block* bq8i = bq8 + r.bq8_offset + i; - d8[i] = __low2float(bq8i->ds); - const int* q8 = reinterpret_cast(bq8i->qs) + ((iqs / 2) % 4); - u[2 * i] = q8[0]; - u[2 * i + 1] = q8[4]; - } - const uint8_t* sc = reinterpret_cast(r.aux); - return q5_q8_dot_impl(r.vl, r.vh, u, sc, sc + 2, r.dm, d8); - } -}; -struct Q4KTraits { - using Block = Q4KBlock; - static constexpr int DIV = QK, T = QI / VDR, KBY = QK / Q8K, BPI = VDR * WARPS * WARP / QI; - __device__ static int kqs(int tid) { return VDR * (tid % (QI / VDR)); } - struct W { int v[2]; uint16_t aux[2]; half2 dm; int bq8_offset; }; - __device__ static W load(const Block* __restrict__ bq4, int iqs) { - W r; - r.bq8_offset = 2 * ((iqs / 2) / 4); - const int* ql = reinterpret_cast(bq4->qs + 16 * r.bq8_offset + 4 * ((iqs / 2) % 4)); - r.v[0] = ql[0]; - r.v[1] = ql[4]; - const uint16_t* scales = reinterpret_cast(bq4->scales); - const int j = r.bq8_offset / 2; - const int jm = j & 1; - const uint32_t s0 = scales[jm]; - const uint32_t s2 = scales[jm + 2]; - const uint32_t s4 = scales[jm + 4]; - const uint32_t hi = uint32_t(-int32_t(j >= 2)); - r.aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) | ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi)); - r.aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) | ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi)); - r.dm = bq4->dm; - return r; - } - __device__ static float apply(const W& r, const Q81Block* __restrict__ bq8, int iqs) { - int u[4]; - float d8[2]; -#pragma unroll - for (int i = 0; i < 2; ++i) { - const Q81Block* bq8i = bq8 + r.bq8_offset + i; - d8[i] = __low2float(bq8i->ds); - const int* q8 = reinterpret_cast(bq8i->qs) + ((iqs / 2) % 4); - u[2 * i] = q8[0]; - u[2 * i + 1] = q8[4]; - } - const uint8_t* sc = reinterpret_cast(r.aux); - return q4_q8_dot_impl(r.v, u, sc, sc + 2, r.dm, d8); - } -}; -struct Q20Traits { - using Block = Q20Block; - static constexpr int DIV = 64, T = 2, KBY = 2, BPI = WARPS * WARP / 2; - __device__ static int kqs(int tid) { return tid % 2; } - struct W { int qx[4], qy[4]; float d2; }; - __device__ static W load(const Block* __restrict__ w, int iqs) { - W r; - r.d2 = w->d; - const int16_t* qs = reinterpret_cast(w->qs) + iqs * 4; -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int q = qs[j]; - const int qe = __byte_perm(0x020100ff, 0x020100ff, q >> 0); - const int qo = __byte_perm(0x020100ff, 0x020100ff, q >> 2); - r.qx[j] = __byte_perm(qe, qo, 0x5140); - r.qy[j] = __byte_perm(qe, qo, 0x7362); - } - return r; - } - __device__ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) { - const Q81Block* chunk = x + iqs; - const int* q8 = reinterpret_cast(chunk->qs); - int sumi = 0; -#pragma unroll - for (int j = 0; j < 4; ++j) { - sumi = STRATA_DP4A(q8[j * 2], r.qx[j], sumi); - sumi = STRATA_DP4A(q8[j * 2 + 1], r.qy[j], sumi); - } - const float d8 = __low2float(chunk->ds); - return r.d2 * d8 * sumi; - } -}; -struct Q3KTraits { - using Block = Q3KBlock; - static constexpr int DIV = 256, T = 16, KBY = 8, BPI = WARPS * WARP / 16; - __device__ static int kqs(int tid) { return tid % 16; } - struct W { int vl, vh; float d; const uint8_t* scales; int scale_offset, bq8_offset; }; - __device__ static W load(const Block* __restrict__ w, int iqs) { - W r; - r.bq8_offset = 4 * (iqs / 8); - r.scale_offset = iqs - iqs % 8 + (iqs % 8) / 4; - r.d = w->d; - r.vl = load_int_b2(w->qs, iqs); - r.vh = ~load_int_b2(w->hmask, iqs % 8) >> r.bq8_offset; - r.scales = w->scales; - return r; - } - __device__ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) { - int u[4]; - float d8[4]; -#pragma unroll - for (int i = 0; i < 4; ++i) { - u[i] = reinterpret_cast(x[r.bq8_offset + i].qs)[iqs % 8]; - d8[i] = __low2float(x[r.bq8_offset + i].ds); - } - return q3_q8_dot_impl(r.vl, r.vh, u, r.scales, r.scale_offset, r.d, d8); - } -}; -struct Q6KTraits { - using Block = Q6KBlock; - static constexpr int DIV = 256, T = 32, KBY = 8, BPI = WARPS * WARP / 32; - __device__ static int kqs(int tid) { return tid % 32; } - struct W { int vl, vh; float d; const int8_t* scales; int bq8_offset; }; - __device__ static W load(const Block* __restrict__ w, int iqs) { - W r; - r.bq8_offset = 4 * (iqs / 16) + (iqs % 16) / 8; - const int scale_offset = 8 * (iqs / 16) + (iqs % 16) / 4; - const int vh_shift = 2 * ((iqs % 16) / 8); - r.vl = load_int_b2(w->ql, iqs); - r.vh = load_int_b2(w->qh, 8 * (iqs / 16) + iqs % 8) >> vh_shift; - r.scales = w->scales + scale_offset; - r.d = w->d; - return r; - } - __device__ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) { - int u[2]; - float d8[2]; -#pragma unroll - for (int i = 0; i < 2; ++i) { - u[i] = reinterpret_cast(x[r.bq8_offset + 2 * i].qs)[iqs % 8]; - d8[i] = __low2float(x[r.bq8_offset + 2 * i].ds); - } - return q6_q8_dot_impl(r.vl, r.vh, u, r.scales, r.d, d8); - } -}; -struct IQ4XSTraits { - using Block = IQ4XSBlock; - static constexpr int DIV = 256, T = 8, KBY = 8, BPI = 4 * WARPS * WARP / 32; - __device__ static int kqs(int tid) { return 4 * (tid % 8); } - struct W { int2 v[4]; int ls; float dw; }; - __device__ static W load(const Block* __restrict__ w, int iqs) { - W r; -#pragma unroll - for (int j = 0; j < 4; ++j) r.v[j] = iq4_table_lookup(reinterpret_cast(w->qs)[iqs + j]); - r.ls = ((w->scales_l[iqs / 8] >> (iqs & 0x04)) & 0x0f) | (((w->scales_h >> (iqs / 2)) & 0x03) << 4); - r.dw = __half2float(w->d); - return r; - } - __device__ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) { - int sumi = 0; -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int u0 = reinterpret_cast(x[iqs / 4].qs)[j]; - const int u1 = reinterpret_cast(x[iqs / 4].qs)[j + 4]; - sumi = STRATA_DP4A(r.v[j].x, u0, sumi); - sumi = STRATA_DP4A(r.v[j].y, u1, sumi); - } - sumi *= r.ls - 32; - const float d = r.dw * __low2float(x[iqs / 4].ds); - return d * sumi; - } -}; -// The four 32-element formats: `load` keeps the block pointer (their decode is a few integer ops) and `apply` is -// the unchanged small_q8_dot. Their per-column cost is small; the win above is for the K and IQ formats. -template -struct SmallTraits { - using Block = Weight; - static constexpr int DIV = 32, T = Qi / 2, KBY = 1, BPI = 2 * WARPS * WARP / Qi; - __device__ static int kqs(int tid) { return 2 * (tid % (Qi / 2)); } - struct W { const Weight* w; }; - __device__ static W load(const Block* __restrict__ w, int) { return W{w}; } - __device__ static float apply(const W& r, const Q81Block* __restrict__ x, int k) { return small_q8_dot(r.w, x, k); } -}; - -// NW warps per block and ROWS rows per block. The EXACT layout (NW = 4, ROWS = 1, or 4 for small K) is the -// ncols = 1 layout and keeps every column bitwise equal to a single-column call. The UPSTREAM layout is -// llama.cpp's generic multi-column table (ncols 2-4: 4 warps; 5-8: 2 warps; always 2 rows per block): faster, -// equal to ncols = 1 only to float rounding (the cross-warp reduction groups partial sums differently). -bool g_multi_exact = true; // until the upstream layout is timed on an idle GPU (plan rule: default only what is measured) - -template -__launch_bounds__(NW * WARP, (ROWS <= 2 ? 4 : 1)) -__global__ void native_mmvq_multi_kernel(const typename F::Block* __restrict__ w, - const Q81Block* __restrict__ x, - float* __restrict__ y, int n_in, int n_out) { - constexpr int BPI = F::BPI * NW / WARPS; // blocks per iteration scale with the warp count - const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); - const int row0 = ROWS * int(blockIdx.x); - const int blocks_per_row = n_in / F::DIV; - const int x_stride = n_in / Q8K; // Q8_1 blocks per activation column - float tmp[NCOLS][ROWS] = {}; - for (int kbx = tid / F::T; kbx < blocks_per_row; kbx += BPI) { - const int kby = kbx * F::KBY; - const int kqs = F::kqs(tid); -#pragma unroll - for (int i = 0; i < ROWS; ++i) { - if (row0 + i < n_out) { - const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx; - const typename F::W wv = F::load(w + block, kqs); // once per (row, block) -#pragma unroll - for (int j = 0; j < NCOLS; ++j) // then per column - tmp[j][i] += F::apply(wv, x + std::size_t(j) * x_stride + kby, kqs); - } - } - } - __shared__ float partial[NW - 1 > 0 ? NW - 1 : 1][NCOLS][ROWS][WARP]; - if (threadIdx.y > 0) { -#pragma unroll - for (int j = 0; j < NCOLS; ++j) -#pragma unroll - for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][j][i][threadIdx.x] = tmp[j][i]; - } - __syncthreads(); - if (threadIdx.y > 0) return; -#pragma unroll - for (int j = 0; j < NCOLS; ++j) { -#pragma unroll - for (int i = 0; i < ROWS; ++i) { -#pragma unroll - for (int l = 0; l < NW - 1; ++l) tmp[j][i] += partial[l][j][i][threadIdx.x]; - tmp[j][i] = warp_sum(tmp[j][i]); - if (threadIdx.x == i && row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = tmp[j][i]; - } - } -} - -template -void launch_multi_n(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, cudaStream_t s) { - const auto* w = static_cast(weights); - const auto* x = static_cast(x_q8_1); - if (!g_multi_exact) { - constexpr int NW = NCOLS <= 4 ? 4 : 2; - const unsigned blocks = unsigned((std::size_t(n_out) + 1) / 2); - native_mmvq_multi_kernel<<>>(w, x, y, n_in, n_out); - return; - } - const dim3 threads(WARP, WARPS); - if (n_in / F::DIV < F::BPI) { - constexpr int ROWS = 2; - const unsigned blocks = unsigned((std::size_t(n_out) + ROWS - 1) / ROWS); - native_mmvq_multi_kernel<<>>(w, x, y, n_in, n_out); - } else { - native_mmvq_multi_kernel<<>>(w, x, y, n_in, n_out); - } -} - -template -void launch_multi(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, - void* stream) { - const auto s = static_cast(stream); - switch (ncols) { - case 2: launch_multi_n(weights, x_q8_1, y, n_in, n_out, s); break; - case 3: launch_multi_n(weights, x_q8_1, y, n_in, n_out, s); break; - case 4: launch_multi_n(weights, x_q8_1, y, n_in, n_out, s); break; - case 5: launch_multi_n(weights, x_q8_1, y, n_in, n_out, s); break; - case 6: launch_multi_n(weights, x_q8_1, y, n_in, n_out, s); break; - case 7: launch_multi_n(weights, x_q8_1, y, n_in, n_out, s); break; - case 8: launch_multi_n(weights, x_q8_1, y, n_in, n_out, s); break; - default: throw std::invalid_argument("native MMVQ multi-column launch requires 2 <= ncols <= 8"); - } -} - -void validate_shape(int n_in, int ncols, int block_elems = Q8K) { - if (n_in <= 0 || n_in % block_elems != 0) { - throw std::invalid_argument("native MMVQ requires n_in > 0 and divisible by its block element count"); - } - if (ncols < 1 || ncols > MAX_NCOLS) throw std::invalid_argument("native MMVQ requires 1 <= ncols <= 8"); -} -void validate_pointer(const void* p) { - if (!p || reinterpret_cast(p) % 4 != 0) { - throw std::invalid_argument("native MMVQ requires non-null 4-byte aligned device pointers"); - } -} -void validate_stream(void* stream) { - if (!stream) throw std::invalid_argument("native MMVQ requires an explicit non-null CUDA stream"); -} -void launch_check() { - const auto error = cudaGetLastError(); - if (error != cudaSuccess) { - throw std::runtime_error(std::string("native MMVQ launch: ") + cudaGetErrorString(error)); - } -} - - -#if defined(STRATA_HIP_GFX906) -// ---- AMD (wave64) layout: one wavefront per R rows, four wavefronts per block, the row's blocks strided over the -// 64 lanes exactly as the CUDA kernels stride them over a block (kbx = lane / T, stride 64 / T), and a 64-lane -// butterfly instead of the LDS partials and __syncthreads of the one-block-per-row layout: on gfx906 a block per -// 2 KB row spent most of its time being launched and joined. The SAME kernel serves every column count 1..8, so a -// column's sums do not depend on how many columns (verify tokens) ride along. STRATA_MMVQ_WAVE=0: the CUDA layout. -bool g_wave_off = std::getenv("STRATA_MMVQ_WAVE") && std::string(std::getenv("STRATA_MMVQ_WAVE")) == "0"; -template -__launch_bounds__(256) -__global__ void native_mmvq_wave_kernel(const typename F::Block* __restrict__ w, const Q81Block* __restrict__ x, - float* __restrict__ y, int n_in, int n_out) { - constexpr int BPIW = 64 / F::T; - static_assert(64 % F::T == 0, "a block's threads must tile the wavefront"); - const int lane = int(threadIdx.x) & 63; - const int row0 = (int(blockIdx.x) * 4 + (int(threadIdx.x) >> 6)) * R; - if (row0 >= n_out) return; - const int blocks_per_row = n_in / F::DIV; - const int x_stride = n_in / Q8K; - const int kqs = F::kqs(lane); - float tmp[NCOLS][R] = {}; - for (int kbx = lane / F::T; kbx < blocks_per_row; kbx += BPIW) { - const int kby = kbx * F::KBY; -#pragma unroll - for (int i = 0; i < R; ++i) { - if (row0 + i < n_out) { - const typename F::W wv = F::load(w + std::size_t(row0 + i) * blocks_per_row + kbx, kqs); -#pragma unroll - for (int j = 0; j < NCOLS; ++j) tmp[j][i] += F::apply(wv, x + std::size_t(j) * x_stride + kby, kqs); - } - } - } -#pragma unroll - for (int j = 0; j < NCOLS; ++j) -#pragma unroll - for (int i = 0; i < R; ++i) { - float v = tmp[j][i]; -#pragma unroll - for (int off = 32; off > 0; off >>= 1) v += __shfl_xor(v, off, 64); - if (lane == 0 && row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = v; - } -} -template -void wave_launch_n(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, cudaStream_t s) { - const auto* w = static_cast(weights); - const auto* x = static_cast(x_q8_1); - constexpr int R = 1; - const unsigned blocks = unsigned((std::size_t(n_out) + 4 * R - 1) / (4 * R)); - native_mmvq_wave_kernel<<>>(w, x, y, n_in, n_out); -} -template -void wave_launch(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) { - const auto s = static_cast(stream); - switch (ncols) { - case 1: wave_launch_n(weights, x_q8_1, y, n_in, n_out, s); break; - case 2: wave_launch_n(weights, x_q8_1, y, n_in, n_out, s); break; - case 3: wave_launch_n(weights, x_q8_1, y, n_in, n_out, s); break; - case 4: wave_launch_n(weights, x_q8_1, y, n_in, n_out, s); break; - case 5: wave_launch_n(weights, x_q8_1, y, n_in, n_out, s); break; - case 6: wave_launch_n(weights, x_q8_1, y, n_in, n_out, s); break; - case 7: wave_launch_n(weights, x_q8_1, y, n_in, n_out, s); break; - case 8: wave_launch_n(weights, x_q8_1, y, n_in, n_out, s); break; - default: throw std::invalid_argument("native MMVQ (wave) requires 1 <= ncols <= 8"); - } -} -#define STRATA_WAVE_MMVQ(...) \ - if (!g_wave_off) { wave_launch<__VA_ARGS__>(weights, x_q8_1, y, n_in, n_out, ncols, stream); launch_check(); return; } -#else -#define STRATA_WAVE_MMVQ(...) -#endif - -template -void small_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream) { - validate_shape(n_in, ncols, 32); - if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); - validate_pointer(weights); - validate_pointer(x_q8_1); - validate_pointer(y); - validate_stream(stream); - STRATA_WAVE_MMVQ(SmallTraits) - if (ncols > 1) { - launch_multi>(weights, x_q8_1, y, n_in, n_out, ncols, stream); - launch_check(); - return; - } - const auto* w = static_cast(weights); - const auto* x = static_cast(x_q8_1); - const auto s = static_cast(stream); - const dim3 threads(WARP, WARPS); - if (n_in / 32 < 2 * WARPS * WARP / Qi) { - const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS); - native_small_mmvq_kernel<<>>(w, x, y, n_in, n_out); - } else { - native_small_mmvq_kernel<<>>(w, x, y, n_in, n_out); - } - launch_check(); -} - -template -void small_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream) { - validate_shape(n_in, ncols, 32); - if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); - validate_pointer(weights); - validate_pointer(x); - validate_pointer(scratch_q8_1); - validate_pointer(y); - validate_stream(stream); - native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream); - small_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream); -} - -} // namespace - -void native_mmvq_set_multi_exact(bool exact) { g_multi_exact = exact; } -bool native_mmvq_multi_exact() { return g_multi_exact; } - -std::size_t native_q8_1_bytes(int n_in, int ncols) { - validate_shape(n_in, ncols); - return std::size_t(ncols) * std::size_t(n_in / Q8K) * sizeof(Q81Block); -} - -void native_quantize_q8_1(const float* x, void* x_q8_1, int n_in, int ncols, void* stream) { - validate_shape(n_in, ncols); - validate_pointer(x); - validate_pointer(x_q8_1); - validate_stream(stream); - // Columns are contiguous and n_in is a multiple of 32, so ncols columns quantize as one vector of - // ncols * n_in elements: every 32-element block stays inside one column. - const int n_total = n_in * ncols; - const unsigned blocks = unsigned((std::size_t(n_total) + QUANT_THREADS - 1) / QUANT_THREADS); - native_quantize_q8_1_kernel<<(stream)>>>(x, static_cast(x_q8_1), n_total); - launch_check(); -} - -void native_swiglu_quantize_q8_1(const float* gate, const float* up, void* x_q8_1, - int n_in, int ncols, void* stream) { - validate_shape(n_in, ncols); - validate_pointer(gate); - validate_pointer(up); - validate_pointer(x_q8_1); - validate_stream(stream); - const int n_total = n_in * ncols; - const unsigned blocks = unsigned((std::size_t(n_total) + QUANT_THREADS - 1) / QUANT_THREADS); - native_swiglu_quantize_q8_1_kernel<<(stream)>>>( - gate, up, static_cast(x_q8_1), n_total); - launch_check(); -} - -void native_q5_k_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream) { - validate_shape(n_in, ncols, QK); - if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); - validate_pointer(weights); - validate_pointer(x_q8_1); - validate_pointer(y); - validate_stream(stream); - STRATA_WAVE_MMVQ(Q5KTraits) - if (ncols > 1) { - launch_multi(weights, x_q8_1, y, n_in, n_out, ncols, stream); - launch_check(); - return; - } - const auto* w = static_cast(weights); - const auto* x = static_cast(x_q8_1); - const auto s = static_cast(stream); - const dim3 threads(WARP, WARPS); - if (n_in / QK < VDR * WARPS * WARP / QI) { - const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS); - native_q5_k_mmvq_kernel<<>>(w, x, y, n_in, n_out); - } else { - native_q5_k_mmvq_kernel<<>>(w, x, y, n_in, n_out); - } - launch_check(); -} - -void native_q5_k_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream) { - // Validate all outputs before enqueueing the first operation. - validate_shape(n_in, ncols, QK); - if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); - validate_pointer(weights); - validate_pointer(x); - validate_pointer(scratch_q8_1); - validate_pointer(y); - validate_stream(stream); - native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream); - native_q5_k_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream); -} - -void native_q2_0_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream) { - validate_shape(n_in, ncols, 64); - if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); - validate_pointer(weights); - validate_pointer(x_q8_1); - validate_pointer(y); - validate_stream(stream); - STRATA_WAVE_MMVQ(Q20Traits) - if (ncols > 1) { - launch_multi(weights, x_q8_1, y, n_in, n_out, ncols, stream); - launch_check(); - return; - } - const auto* w = static_cast(weights); - const auto* x = static_cast(x_q8_1); - const auto s = static_cast(stream); - const dim3 threads(WARP, WARPS); - if (n_in / 64 < WARPS * WARP / 2) { - const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS); - native_q2_0_mmvq_kernel<<>>(w, x, y, n_in, n_out); - } else { - native_q2_0_mmvq_kernel<<>>(w, x, y, n_in, n_out); - } - launch_check(); -} - -void native_q2_0_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream) { - validate_shape(n_in, ncols, 64); - if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); - validate_pointer(weights); - validate_pointer(x); - validate_pointer(scratch_q8_1); - validate_pointer(y); - validate_stream(stream); - native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream); - native_q2_0_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream); -} - -void native_q3_k_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream) { - validate_shape(n_in, ncols, 256); - if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); - validate_pointer(weights); - validate_pointer(x_q8_1); - validate_pointer(y); - validate_stream(stream); - STRATA_WAVE_MMVQ(Q3KTraits) - if (ncols > 1) { - launch_multi(weights, x_q8_1, y, n_in, n_out, ncols, stream); - launch_check(); - return; - } - const auto* w = static_cast(weights); - const auto* x = static_cast(x_q8_1); - const auto s = static_cast(stream); - const dim3 threads(WARP, WARPS); - if (n_in / 256 < WARPS * WARP / 16) { - const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS); - native_q3_k_mmvq_kernel<<>>(w, x, y, n_in, n_out); - } else { - native_q3_k_mmvq_kernel<<>>(w, x, y, n_in, n_out); - } - launch_check(); -} - -void native_q3_k_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream) { - validate_shape(n_in, ncols, 256); - if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); - validate_pointer(weights); - validate_pointer(x); - validate_pointer(scratch_q8_1); - validate_pointer(y); - validate_stream(stream); - native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream); - native_q3_k_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream); -} - -void native_iq4_xs_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream) { - validate_shape(n_in, ncols, 256); - if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); - validate_pointer(weights); - validate_pointer(x_q8_1); - validate_pointer(y); - validate_stream(stream); - STRATA_WAVE_MMVQ(IQ4XSTraits) - if (ncols > 1) { - launch_multi(weights, x_q8_1, y, n_in, n_out, ncols, stream); - launch_check(); - return; - } - const auto* w = static_cast(weights); - const auto* x = static_cast(x_q8_1); - const auto s = static_cast(stream); - const dim3 threads(WARP, WARPS); - if (n_in / 256 < 4 * WARPS * WARP / 32) { - const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS); - native_iq4_xs_mmvq_kernel<<>>(w, x, y, n_in, n_out); - } else { - native_iq4_xs_mmvq_kernel<<>>(w, x, y, n_in, n_out); - } - launch_check(); -} - -void native_iq4_xs_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream) { - validate_shape(n_in, ncols, 256); - if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); - validate_pointer(weights); - validate_pointer(x); - validate_pointer(scratch_q8_1); - validate_pointer(y); - validate_stream(stream); - native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream); - native_iq4_xs_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream); -} - -void native_q4_k_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream) { - validate_shape(n_in, ncols, 256); - if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); - validate_pointer(weights); - validate_pointer(x_q8_1); - validate_pointer(y); - validate_stream(stream); - STRATA_WAVE_MMVQ(Q4KTraits) - if (ncols > 1) { - launch_multi(weights, x_q8_1, y, n_in, n_out, ncols, stream); - launch_check(); - return; - } - const auto* w = static_cast(weights); - const auto* x = static_cast(x_q8_1); - const auto s = static_cast(stream); - const dim3 threads(WARP, WARPS); - if (n_in / 256 < WARPS * WARP / 16) { - const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS); - native_q4_k_mmvq_kernel<<>>(w, x, y, n_in, n_out); - } else { - native_q4_k_mmvq_kernel<<>>(w, x, y, n_in, n_out); - } - launch_check(); -} - -void native_q4_k_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream) { - validate_shape(n_in, ncols, 256); - if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); - validate_pointer(weights); - validate_pointer(x); - validate_pointer(scratch_q8_1); - validate_pointer(y); - validate_stream(stream); - native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream); - native_q4_k_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream); -} - -void native_q6_k_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream) { - validate_shape(n_in, ncols, 256); - if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); - validate_pointer(weights); - validate_pointer(x_q8_1); - validate_pointer(y); - validate_stream(stream); - STRATA_WAVE_MMVQ(Q6KTraits) - if (ncols > 1) { - launch_multi(weights, x_q8_1, y, n_in, n_out, ncols, stream); - launch_check(); - return; - } - const auto* w = static_cast(weights); - const auto* x = static_cast(x_q8_1); - const auto s = static_cast(stream); - const dim3 threads(WARP, WARPS); - if (n_in / 256 < WARPS * WARP / 32) { - const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS); - native_q6_k_mmvq_kernel<<>>(w, x, y, n_in, n_out); - } else { - native_q6_k_mmvq_kernel<<>>(w, x, y, n_in, n_out); - } - launch_check(); -} - -void native_q6_k_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream) { - validate_shape(n_in, ncols, 256); - if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); - validate_pointer(weights); - validate_pointer(x); - validate_pointer(scratch_q8_1); - validate_pointer(y); - validate_stream(stream); - native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream); - native_q6_k_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream); -} - -void native_q4_0_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream) { - small_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); -} - -void native_q4_0_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream) { - small_f32(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream); -} - -void native_q5_0_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream) { - small_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); -} - -void native_q5_0_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream) { - small_f32(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream); -} - -void native_q8_0_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream) { - small_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); -} - -void native_q8_0_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream) { - small_f32(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream); -} - -void native_iq4_nl_mmvq(const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream) { - small_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); -} - -void native_iq4_nl_f32(const void* weights, const float* x, void* scratch_q8_1, - float* y, int n_in, int n_out, int ncols, void* stream) { - small_f32(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream); -} - -bool native_mmvq_supported(int ggml_type) noexcept { - return ggml_type == 2 || ggml_type == 6 || ggml_type == 7 || ggml_type == 8 || ggml_type == 11 || - ggml_type == 12 || ggml_type == 13 || ggml_type == 14 || ggml_type == 20 || - ggml_type == 23 || ggml_type == 42 || ggml_type == 16 || ggml_type == 17 || ggml_type == 18 || - ggml_type == 21 || ggml_type == 22 || ggml_type == 29; -} - -std::size_t native_mmvq_weight_bytes(int ggml_type, int n_in, int n_out) { - int block_elems, block_bytes; - switch (ggml_type) { - case 2: block_elems = 32; block_bytes = 18; break; - case 6: block_elems = 32; block_bytes = 22; break; - case 7: block_elems = 32; block_bytes = 24; break; - case 8: block_elems = 32; block_bytes = 34; break; - case 20: block_elems = 32; block_bytes = 18; break; - case 11: block_elems = 256; block_bytes = 110; break; - case 12: block_elems = 256; block_bytes = 144; break; - case 13: block_elems = 256; block_bytes = 176; break; - case 14: block_elems = 256; block_bytes = 210; break; - case 23: block_elems = 256; block_bytes = 136; break; - case 42: block_elems = 64; block_bytes = 18; break; - case 16: case 17: case 18: case 21: case 22: case 29: - block_elems = 256; block_bytes = (int) iq_row_bytes(ggml_type, 256); break; - default: throw std::invalid_argument("unsupported native MMVQ GGML type"); - } - validate_shape(n_in, 1, block_elems); - if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); - const std::size_t row_bytes = std::size_t(n_in / block_elems) * block_bytes; - if (row_bytes > std::numeric_limits::max() / std::size_t(n_out)) { - throw std::length_error("native MMVQ weight byte count overflows size_t"); - } - return row_bytes * std::size_t(n_out); -} - -void native_mmvq(int ggml_type, const void* weights, const void* x_q8_1, float* y, - int n_in, int n_out, int ncols, void* stream) { - switch (ggml_type) { - case 2: native_q4_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; - case 6: native_q5_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; - case 7: iq_mmvq(ggml_type, weights, x_q8_1, y, n_in, n_out, ncols, stream); break; - case 8: native_q8_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; - case 20: native_iq4_nl_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; - case 11: native_q3_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; - case 12: native_q4_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; - case 13: native_q5_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; - case 14: native_q6_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; - case 23: native_iq4_xs_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; - case 42: native_q2_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; - case 16: case 17: case 18: case 21: case 22: case 29: - iq_mmvq(ggml_type, weights, x_q8_1, y, n_in, n_out, ncols, stream); break; - default: throw std::invalid_argument("unsupported native MMVQ GGML type"); - } -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/native_moe.cu b/src/kernels/cuda/native_moe.cu deleted file mode 100644 index 7f1f91c..0000000 --- a/src/kernels/cuda/native_moe.cu +++ /dev/null @@ -1,86 +0,0 @@ -// Arithmetic adapted from the MIT-licensed pinned ggml CUDA -// moe-weighted-reduction.cu at 3cf03257f219afbe7334045ff7c6a06ac68c627d. -// MIT License -// Copyright (c) 2023-2026 The ggml authors -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -#include "strata/kernels/native_moe.hpp" -#include -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { -std::atomic enabled{false}; -__global__ void combine(const float* __restrict__ parts, const float* __restrict__ weights, - const float* __restrict__ shared, float* __restrict__ output, - int64_t n_embd, int k) { - // blockIdx.y = the token of a multi-token launch (0 for the single one) - const int64_t tk = blockIdx.y; - parts += tk * k * n_embd; weights += tk * k; if (shared) shared += tk * n_embd; output += tk * n_embd; - const int64_t col = int64_t(blockIdx.x) * blockDim.x + threadIdx.x; - if (col >= n_embd) return; - float sum = parts[col] * weights[0]; - for (int expert = 1; expert < k; ++expert) { - sum += parts[int64_t(expert) * n_embd + col] * weights[expert]; - } - if (shared) sum += shared[col]; - output[col] = sum; -} -bool valid_span(const void* p, size_t bytes) { - const auto address = reinterpret_cast(p); - return p && address % alignof(float) == 0 && bytes <= UINTPTR_MAX - address; -} -bool overlap(const void* a, size_t an, const void* b, size_t bn) { - const auto ap = reinterpret_cast(a), bp = reinterpret_cast(b); - return ap < bp + bn && bp < ap + an; -} -} -void native_moe_combine_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); } -bool native_moe_combine_enabled() { return enabled.load(std::memory_order_relaxed); } -void native_moe_combine(const float* parts, const float* weights, const float* shared, - float* output, int64_t n_embd, int64_t k, void* stream) { - if (!stream || n_embd <= 0 || n_embd > std::numeric_limits::max() || k < 1 || k > 15) - throw std::invalid_argument("native MoE combine requires a stream, positive width and 1..15 experts"); - const size_t row_bytes = size_t(n_embd) * sizeof(float); - const size_t part_bytes = row_bytes * size_t(k), weight_bytes = size_t(k) * sizeof(float); - if (!valid_span(parts, part_bytes) || !valid_span(weights, weight_bytes) || !valid_span(output, row_bytes) - || (shared && !valid_span(shared, row_bytes)) - || overlap(output, row_bytes, parts, part_bytes) - || overlap(output, row_bytes, weights, weight_bytes) - || (shared && overlap(output, row_bytes, shared, row_bytes))) - throw std::invalid_argument("native MoE combine requires aligned spans and disjoint output"); - combine<<(stream)>>>( - parts, weights, shared, output, n_embd, int(k)); - const auto error = cudaGetLastError(); - if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); -} -void native_moe_combine_multi(const float* parts, const float* weights, const float* shared, float* output, - int64_t n_embd, int64_t k, int n_tok, void* stream) { - if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1) - throw std::invalid_argument("native MoE combine (multi) requires a stream, width, 1..15 experts, tokens"); - combine<<(stream)>>>( - parts, weights, shared, output, n_embd, int(k)); - const auto error = cudaGetLastError(); - if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); -} -} diff --git a/src/kernels/cuda/native_ple_postops.cu b/src/kernels/cuda/native_ple_postops.cu deleted file mode 100644 index 922ae0a..0000000 --- a/src/kernels/cuda/native_ple_postops.cu +++ /dev/null @@ -1,221 +0,0 @@ -// Arithmetic adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d: -// src/models/qwen4exp.cpp and ggml-cuda/{reduce_rows.cuh,sumrows.cu,unary.cu}. -// MIT License -// Copyright (c) 2023-2026 The ggml authors -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -#include "strata/kernels/native_ple_postops.hpp" -#include "strata/kernels/native_gr_norm.hpp" -#include "strata/kernels/ngram.hpp" -#include -#include -#include -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { -constexpr int N = 2560, H = 4, D = N * H, HISTORY = 9; -__device__ float warp_sum(float x) { - for (int offset = 16; offset; offset >>= 1) x += __shfl_xor_sync(0xffffffffu, x, offset); - return x; -} -__global__ void gate_kernel(const float* key, const float* query, float* gate, float scale) { - // SUM_ROWS selects 512 threads for four rows on the target GPU. Preserve - // its eight partial lanes and materialized MUL rounding (never a dot FMA). - float sums[8] = {}; -#pragma unroll - for (int j = 0; j < 8; ++j) { - const int d = threadIdx.x + j * 512; - const float p = d < N ? __fmul_rn(key[blockIdx.x * N + d], query[blockIdx.x * N + d]) : 0.0f; - sums[j] += p; - } - float sum = 0; -#pragma unroll - for (int j = 0; j < 8; ++j) sum += sums[j]; - __shared__ float partials[32]; - sum = warp_sum(sum); - const int lane = threadIdx.x % 32; - if (!lane) partials[threadIdx.x / 32] = sum; - __syncthreads(); - sum = lane < 16 ? partials[lane] : 0.0f; - sum = warp_sum(sum); - if (threadIdx.x == 0) { - const float s = __fmaf_rn(scale, sum, 0.0f); // ggml SCALE's zero bias - const float mag = sqrtf(fmaxf(fabsf(s), 1e-6f)); - const float sign = float((s > 0.0f) - (s < 0.0f)); - gate[blockIdx.x] = 1.0f / (1.0f + expf(-__fmul_rn(sign, mag))); - } -} -__global__ void broadcast_kernel(const float* value, const float* gate, float* gated) { - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i < D) gated[i] = __fmul_rn(value[i % N], gate[i / N]); -} -__global__ void conv_residual_kernel(const float* history, const float* normalized, - const uint16_t* weights, const float* hidden, - const float* gated, float* conv, float* result) { - const int c = blockIdx.x * blockDim.x + threadIdx.x; - if (c >= D) return; - float sum = 0; -#pragma unroll - for (int k = 0; k < 4; ++k) { - const float x = k == 3 ? normalized[c] : history[c * HISTORY + 3 * k]; - const float w = __half2float(__ushort_as_half(weights[c * 4 + k])); - const float term = __fmul_rn(x, w); - sum = k == 0 ? term : __fadd_rn(sum, term); - } - const float activation = sum / (1.0f + expf(-sum)); - conv[c] = activation; - // Exact hidden/result alias is safe: each thread owns one element. - result[c] = __fadd_rn(hidden[c], __fadd_rn(gated[c], activation)); -} -// ---- the batch: T tokens, the same arithmetic per element as the kernels above -// weighted_rms_norm (native_gr_norm.cu) with the gamma row repeating every H rows (one token's H groups) -__device__ float norm_warp_sum(float value) { -#pragma unroll - for (int offset = 16; offset > 0; offset >>= 1) value += __shfl_xor_sync(0xffffffffu, value, offset, 32); - return value; -} -__global__ void rms_rep_kernel(const float* __restrict__ input, const float* __restrict__ gamma, - float* __restrict__ output) { - constexpr int BlockSize = 1024; // native_gr_rms_norm_weighted's choice for 2560 columns - const int tid = threadIdx.x; - const size_t row_offset = size_t(blockIdx.x) * N; - input += row_offset; - output += row_offset; - gamma += size_t(blockIdx.x % H) * N; - float partial = 0.0f; - for (int col = tid; col < N; col += BlockSize) { - const float value = input[col]; - partial += value * value; - } - __shared__ float sums[32]; - partial = norm_warp_sum(partial); - const int lane = tid % 32; - if (lane == 0) sums[tid / 32] = partial; - __syncthreads(); - partial = 0.0f; - if (lane < BlockSize / 32) partial = sums[lane]; - partial = norm_warp_sum(partial); - const float mean = partial / N; - const float scale = rsqrtf(mean + NG_RMS_EPS); - for (int col = tid; col < N; col += BlockSize) output[col] = scale * input[col] * gamma[col]; -} -__global__ void broadcast_batch_kernel(const float* value, const float* gate, float* gated, int T) { - const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; - if (i >= size_t(T) * D) return; - const size_t t = i / D, d = i % D; - gated[i] = __fmul_rn(value[t * N + d % N], gate[t * H + d / N]); -} -// the dilated conv (taps 9, 6, 3 tokens back and this one) and the residual; a tap before the chunk reads the history -__global__ void conv_residual_batch_kernel(const float* history, const float* normalized, const uint16_t* weights, - float* hidden, const float* gated, int T) { - const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; - if (i >= size_t(T) * D) return; - const int t = int(i / D), c = int(i % D); - float sum = 0; -#pragma unroll - for (int k = 0; k < 4; ++k) { - const int p = t - 9 + 3 * k; // the token this tap reads (k == 3: this one) - const float x = p >= 0 ? normalized[size_t(p) * D + c] : history[size_t(c) * HISTORY + (9 + p)]; - const float wk = __half2float(__ushort_as_half(weights[c * 4 + k])); - const float term = __fmul_rn(x, wk); - sum = k == 0 ? term : __fadd_rn(sum, term); - } - const float activation = sum / (1.0f + expf(-sum)); - hidden[i] = __fadd_rn(hidden[i], __fadd_rn(gated[i], activation)); -} -// the history after the chunk: the last nine normalized rows (older ones from the history when T < 9) -__global__ void history_batch_kernel(float* history, const float* normalized, int T) { - const int c = blockIdx.x * blockDim.x + threadIdx.x; - if (c >= D) return; - float h[HISTORY]; -#pragma unroll - for (int r = 0; r < HISTORY; ++r) { - const int p = T - HISTORY + r; - h[r] = p >= 0 ? normalized[size_t(p) * D + c] : history[size_t(c) * HISTORY + (T + r)]; - } -#pragma unroll - for (int r = 0; r < HISTORY; ++r) history[size_t(c) * HISTORY + r] = h[r]; -} - -struct Span { const void* p; size_t bytes; size_t alignment; }; -bool overlaps(Span a, Span b) { - const auto x = reinterpret_cast(a.p), y = reinterpret_cast(b.p); - return x < y + b.bytes && y < x + a.bytes; -} -void validate(Span span) { - const auto p = reinterpret_cast(span.p); - if (!p || p % span.alignment || p > std::numeric_limits::max() - span.bytes) - throw std::invalid_argument("native PLE postops require nonnull aligned bounded spans"); -} -void launch_check() { - const auto error = cudaGetLastError(); - if (error != cudaSuccess) throw std::runtime_error(std::string("native PLE postops launch: ") + cudaGetErrorString(error)); -} -} // namespace - -void native_ple_postops(const float* projected_key, const float* hidden, - const float* value, const float* history, - const PleWeights& w, const NativePlePostopsBuffers& b, void* stream) { - if (!stream) throw std::invalid_argument("native PLE postops require an explicit stream"); - const Span inputs[] = {{projected_key,D*4,4}, {hidden,D*4,4}, {value,N*4,4}, - {history,HISTORY*D*4,4}, {w.norm_key,D*4,4}, {w.norm_query,D*4,4}, - {w.norm_conv,D*4,4}, {w.conv1d_f16,4*D*2,2}}; - const Span outputs[] = {{b.key,D*4,4}, {b.query,D*4,4}, {b.gate,H*4,4}, - {b.gated,D*4,4}, {b.normalized,D*4,4}, {b.conv,D*4,4}, {b.result,D*4,4}}; - for (const auto& span : inputs) validate(span); - for (const auto& span : outputs) validate(span); - for (size_t i = 0; i < 7; ++i) { - for (size_t j = 0; j < 8; ++j) - if (!(i == 6 && j == 1 && b.result == hidden) && overlaps(outputs[i], inputs[j])) - throw std::invalid_argument("native PLE postops output overlaps an input or weight"); - for (size_t j = i + 1; j < 7; ++j) - if (!(i == 1 && j == 4 && b.query == b.normalized) && overlaps(outputs[i], outputs[j])) - throw std::invalid_argument("native PLE postops writable spans overlap"); - } - native_gr_rms_norm_weighted(projected_key,w.norm_key,b.key,N,H,NG_RMS_EPS,stream); - native_gr_rms_norm_weighted(hidden,w.norm_query,b.query,N,H,NG_RMS_EPS,stream); - auto st = static_cast(stream); - gate_kernel<<>>(b.key,b.query,b.gate,1.0f / std::sqrt(float(N))); - broadcast_kernel<<>>(value,b.gate,b.gated); - launch_check(); - native_gr_rms_norm_weighted(b.gated,w.norm_conv,b.normalized,N,H,NG_RMS_EPS,stream); - conv_residual_kernel<<>>(history,b.normalized,w.conv1d_f16,hidden,b.gated,b.conv,b.result); - launch_check(); -} - -void native_ple_postops_batch(float* key, float* hidden, const float* value, float* history, const PleWeights& w, - float* query_norm, float* gated, float* gate, int T, void* stream) { - if (!stream || T <= 0 || !key || !hidden || !value || !history || !query_norm || !gated || !gate) - throw std::invalid_argument("native PLE postops batch: null input or empty batch"); - auto st = static_cast(stream); - const unsigned rows = unsigned(T) * H; - const unsigned blocks = unsigned((size_t(T) * D + 255) / 256); - rms_rep_kernel<<>>(key, w.norm_key, key); - rms_rep_kernel<<>>(hidden, w.norm_query, query_norm); - gate_kernel<<>>(key, query_norm, gate, 1.0f / std::sqrt(float(N))); - broadcast_batch_kernel<<>>(value, gate, gated, T); - rms_rep_kernel<<>>(gated, w.norm_conv, query_norm); - conv_residual_batch_kernel<<>>(history, query_norm, w.conv1d_f16, hidden, gated, T); - history_batch_kernel<<>>(history, query_norm, T); - launch_check(); -} -} // namespace strata::kernels diff --git a/src/kernels/cuda/native_qsa.cu b/src/kernels/cuda/native_qsa.cu deleted file mode 100644 index 32e2511..0000000 --- a/src/kernels/cuda/native_qsa.cu +++ /dev/null @@ -1,127 +0,0 @@ -// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d: -// ggml/src/ggml-cuda/{norm.cu,common.cuh,unary.cu}. -// -// MIT License -// Copyright (c) 2023-2026 The ggml authors -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -#include "strata/kernels/native_qsa.hpp" -#include -#include -#include -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { -std::atomic enabled{false}; -__device__ __forceinline__ float warp_sum(float value) { -#pragma unroll - for (int offset = 16; offset; offset >>= 1) - value += __shfl_xor_sync(0xffffffffu, value, offset, 32); - return value; -} -template -__global__ void norm(const float* input, const float* __restrict__ gamma, float* output, - int n_cols, float epsilon) { - const int tid = threadIdx.x; - const std::size_t row_offset = std::size_t(blockIdx.x) * n_cols; - input += row_offset; output += row_offset; - float partial = 0.0f; - for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) { - const float x = input[col]; - partial += x * x; - } - __shared__ float sums[32]; - partial = warp_sum(partial); - const int lane = tid % 32; - if (lane == 0) sums[tid / 32] = partial; - // All reads of input for the reduction precede this barrier. Afterwards, - // each thread reads/writes only its own elements, allowing exact in-place use. - __syncthreads(); - partial = lane < BlockSize / 32 ? sums[lane] : 0.0f; - partial = warp_sum(partial); - const float mean = partial / n_cols; - const float scale = rsqrtf(mean + epsilon); - for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) - output[col] = scale * input[col] * gamma[col]; -} -__global__ void gate(const float* attn, const float* __restrict__ q_full, float* output, - int n_head, int head_dim) { - const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x; - if (i >= std::size_t(n_head) * head_dim) return; - const std::size_t head = i / head_dim, channel = i % head_dim; - const float raw = q_full[head * 2 * head_dim + head_dim + channel]; - const float sigmoid = 1.0f / (1.0f + expf(-raw)); - output[i] = attn[i] * sigmoid; -} -std::size_t elements(int cols, int rows) { - if (cols <= 0 || rows <= 0 || std::uint64_t(cols) * rows > std::uint64_t(std::numeric_limits::max())) - throw std::invalid_argument("native QSA requires positive bounded dimensions"); - return std::size_t(cols) * rows; -} -bool valid(const void* ptr, std::size_t bytes) { - const auto address = reinterpret_cast(ptr); - return ptr && address % 4 == 0 && bytes <= UINTPTR_MAX - address; -} -bool overlap(const void* a, std::size_t an, const void* b, std::size_t bn) { - const auto ap = reinterpret_cast(a), bp = reinterpret_cast(b); - return ap < bp + bn && bp < ap + an; -} -void buffers(const float* input, std::size_t in_bytes, const float* weight, std::size_t weight_bytes, - float* output, void* stream) { - if (!stream || !valid(input, in_bytes) || !valid(weight, weight_bytes) || !valid(output, in_bytes) || - overlap(input, in_bytes, weight, weight_bytes) || overlap(output, in_bytes, weight, weight_bytes) || - (input != output && overlap(input, in_bytes, output, in_bytes))) - throw std::invalid_argument("native QSA requires a stream, aligned spans, and disjoint buffers or exact input/output alias"); -} -void check_launch() { - const auto result = cudaGetLastError(); - if (result != cudaSuccess) - throw std::runtime_error(std::string("native QSA launch: ") + cudaGetErrorString(result)); -} -} // namespace - -void native_qsa_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); } -bool native_qsa_enabled() { return enabled.load(std::memory_order_relaxed); } - -void native_qsa_rms_norm_weighted(const float* input, const float* gamma, float* output, - int n_cols, int n_rows, float epsilon, void* stream) { - const auto count = elements(n_cols, n_rows); - if (!std::isfinite(epsilon) || epsilon < 0.0f) - throw std::invalid_argument("native QSA requires finite nonnegative epsilon"); - buffers(input, count * 4, gamma, std::size_t(n_cols) * 4, output, stream); - if (n_cols < 1024) - norm<256><<(stream)>>>(input, gamma, output, n_cols, epsilon); - else - norm<1024><<(stream)>>>(input, gamma, output, n_cols, epsilon); - check_launch(); -} -void native_qsa_gate_apply(const float* attn, const float* q_full, float* output, - int n_head, int head_dim, void* stream) { - const auto count = elements(head_dim, n_head); - buffers(attn, count * 4, q_full, count * 8, output, stream); - gate<<(stream)>>>(attn, q_full, output, n_head, head_dim); - check_launch(); -} -} // namespace strata::kernels diff --git a/src/kernels/cuda/native_qsa_indexer.cu b/src/kernels/cuda/native_qsa_indexer.cu deleted file mode 100644 index 8147c70..0000000 --- a/src/kernels/cuda/native_qsa_indexer.cu +++ /dev/null @@ -1,290 +0,0 @@ -// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d: -// src/models/qwen4exp.cpp; ggml/src/ggml-cuda/{set-rows.cu,norm.cu,rope.cu}. -// MIT License -// Copyright (c) 2023-2026 The ggml authors -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -#include "strata/kernels/native_qsa_indexer.hpp" -#include "strata/kernels/mrope.hpp" -#include -#include -#include -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { -std::atomic enabled{false}; -constexpr int D = 128, R = 4, ROT = 64, THREADS = 256; -__device__ float warp_sum(float x) { -#pragma unroll - for (int offset = 16; offset; offset >>= 1) - x += __shfl_xor_sync(0xffffffffu, x, offset); - return x; -} -// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table. The host launches whenever -// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it; -// with it merely skipped at run time, the compiled default path changed its results). -template -__global__ void append(const float* __restrict__ raw, const int32_t* __restrict__ pos_dev, - int pos_base, const float* __restrict__ gamma, float epsilon, - float* __restrict__ tail, float* __restrict__ dead, - float* __restrict__ pooled, int32_t* __restrict__ block_pos, - int max_cells, float theta_scale, float freq_scale, float corr_low, - float corr_high, float ext_factor, float mscale, - const int32_t* __restrict__ mtab, RopeTab rt) { - const int pos = *pos_dev, d = threadIdx.x; - if (pos < 0 || pos >= max_cells) return; - const int slot = pos % R; - float incoming = 0.0f; - if (d < D) { - // SET_ROWS stores F16; GET_ROWS expands those exact values to F32. - incoming = __half2float(__float2half_rn(raw[d])); - if (slot < R - 1) tail[slot * D + d] = incoming; - } - if (pos != 0 && slot != R - 1) return; - __shared__ float values[D]; - __shared__ float partials[32]; - float mean = 0.0f; - if (d < D) { - // The spare's four gather indices all name cell zero. Completed blocks - // use chronological slices; each graph ADD materializes an F32 sum. - float sum = pos == 0 ? incoming : tail[d]; -#pragma unroll - for (int j = 1; j < R; ++j) - sum = __fadd_rn(sum, pos == 0 || j == R - 1 ? incoming : tail[j * D + d]); - mean = __fmaf_rn(0.25f, sum, 0.0f); // SCALE includes a zero bias. - } - float square_sum = 0.0f; - if (d < D) square_sum += mean * mean; - square_sum = warp_sum(square_sum); - const int lane = d % 32; - if (lane == 0) partials[d / 32] = square_sum; - __syncthreads(); - square_sum = lane < THREADS / 32 ? partials[lane] : 0.0f; - square_sum = warp_sum(square_sum); - const float scale = rsqrtf(square_sum / D + epsilon); - if (d < D) values[d] = scale * mean * gamma[d]; - __syncthreads(); - if (d >= D) return; - const int b = pos / R; - const int rope_pos = pos == 0 ? 0 : pos_base + R * b; - float y = values[d]; - if (d < ROT) { - const int pair = d % (ROT / 2); - // The spare (pos == 0) keeps its zero angle; under YaRN the mscale magnitude still rides in - // through cos(0) - which is exactly what the queries are scaled by, so the top-k is unmoved. - float c, s; - if (!(TAB && rope_tab_cs(rt, pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s))) { - const float theta_extrap = (pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); - rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); - } - const float a = values[pair], z = values[pair + ROT / 2]; - y = d < ROT / 2 ? a * c - z * s : a * s + z * c; - } - pooled[std::size_t(b) * D + d] = y; - if (pos == 0) dead[d] = y; - else pooled[std::size_t(b + 1) * D + d] = dead[d]; - if (d == 0 && pos != 0) *block_pos = rope_pos; -} -// ---- C-2: the batched append. The pooled key of a completed block b (its last cell pos = 4b+3), computed with -// the single append's arithmetic: keys rounded through F16, summed tail[0]+tail[1]+tail[2]+incoming in that order, -// the RMS norm, gamma, the rotation at pos_base + 4b. `k(j)` is the key of the block's cell j: a row of this batch -// (cell >= p0) or the tail the previous batch left (cell < p0). Only the batch's last completed block writes the -// spare after it (every earlier one's is overwritten by the next block in order). -template -__device__ __forceinline__ float pooled_value(const float* values, int d, int rope_pos, float theta_scale, - float freq_scale, float corr_low, float corr_high, - float ext_factor, float mscale, const int32_t* mtab, bool zero_pos, - const RopeTab& rt) { - float y = values[d]; - if (d < ROT) { - const int pair = d % (ROT / 2); - // The same rotation the single append applies, rope_scaling.hpp's helper shared: under none this is - // today's cosf/sinf; under linear/YaRN the pooled keys move with the cache's K, and the spare's zero - // angle carries the mscale magnitude through cos(0) exactly as the single append's does. - float c, s; - if (!(TAB && rope_tab_cs(rt, zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s))) { - const float theta_extrap = (zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); - rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); - } - const float a = values[pair], z = values[pair + ROT / 2]; - y = d < ROT / 2 ? a * c - z * s : a * s + z * c; - } - return y; -} -__device__ __forceinline__ float norm_scale(float mean, float* partials, int d) { - float square_sum = d < D ? mean * mean : 0.0f; - square_sum = warp_sum(square_sum); - const int lane = d % 32; - if (lane == 0) partials[d / 32] = square_sum; - __syncthreads(); - square_sum = lane < THREADS / 32 ? partials[lane] : 0.0f; - square_sum = warp_sum(square_sum); - return square_sum; -} -// cell 0 of a sequence: the spare (every gather index names cell 0), written to pooled[0] and dead -template -__global__ void append_first(const float* __restrict__ raw, const float* __restrict__ gamma, float epsilon, - float* __restrict__ dead, float* __restrict__ pooled, float theta_scale, - float freq_scale, float corr_low, float corr_high, float ext_factor, float mscale, - const int32_t* __restrict__ mtab, RopeTab rt) { - const int d = threadIdx.x; - __shared__ float values[D]; - __shared__ float partials[32]; - float mean = 0.0f; - if (d < D) { - const float incoming = __half2float(__float2half_rn(raw[d])); - float sum = incoming; -#pragma unroll - for (int j = 1; j < R; ++j) sum = __fadd_rn(sum, incoming); - mean = __fmaf_rn(0.25f, sum, 0.0f); - } - const float square_sum = norm_scale(mean, partials, d); - const float scale = rsqrtf(square_sum / D + epsilon); - if (d < D) values[d] = scale * mean * gamma[d]; - __syncthreads(); - if (d >= D) return; - const float y = pooled_value(values, d, 0, theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale, - mtab, true, rt); - pooled[d] = y; - dead[d] = y; -} -template -__global__ void append_blocks(const float* __restrict__ raw, int64_t n, int64_t p0, int pos_base, - const float* __restrict__ gamma, float epsilon, const float* __restrict__ tail, - const float* __restrict__ dead, float* __restrict__ pooled, int32_t* __restrict__ block_pos, - int64_t first_block, int64_t last_block, float theta_scale, float freq_scale, - float corr_low, float corr_high, float ext_factor, float mscale, - const int32_t* __restrict__ mtab, RopeTab rt) { - const int64_t b = first_block + blockIdx.x; - const int d = threadIdx.x; - __shared__ float values[D]; - __shared__ float partials[32]; - float mean = 0.0f; - if (d < D) { - auto key = [&](int j) -> float { - const int64_t cell = b * R + j; - return cell >= p0 ? __half2float(__float2half_rn(raw[(cell - p0) * D + d])) : tail[j * D + d]; - }; - float sum = key(0); -#pragma unroll - for (int j = 1; j < R; ++j) sum = __fadd_rn(sum, key(j)); - mean = __fmaf_rn(0.25f, sum, 0.0f); - } - const float square_sum = norm_scale(mean, partials, d); - const float scale = rsqrtf(square_sum / D + epsilon); - if (d < D) values[d] = scale * mean * gamma[d]; - __syncthreads(); - if (d >= D) return; - const int rope_pos = pos_base + R * (int) b; - pooled[std::size_t(b) * D + d] = pooled_value(values, d, rope_pos, theta_scale, freq_scale, corr_low, corr_high, - ext_factor, mscale, mtab, false, rt); - if (b == last_block) { - pooled[std::size_t(b + 1) * D + d] = dead[d]; - if (d == 0) *block_pos = rope_pos; - } -} -// the tail after the batch: slot s holds the key of the batch's last cell with cell % 4 == s (s < 3), if any -__global__ void append_tail(const float* __restrict__ raw, int64_t n, int64_t p0, float* __restrict__ tail) { - const int s = blockIdx.x, d = threadIdx.x; - if (d >= D) return; - const int64_t last = p0 + n - 1; - int64_t cell = last - ((last % R) - s + R) % R; // the last cell <= last with cell % 4 == s - if (cell < p0) return; - tail[s * D + d] = __half2float(__float2half_rn(raw[(cell - p0) * D + d])); -} -struct Span { const void* p; std::size_t n; }; -void validate(Span s) { - const auto p = reinterpret_cast(s.p); - if (!p || p % 4 || s.n > UINTPTR_MAX - p) - throw std::invalid_argument("native QSA indexer requires aligned bounded spans"); -} -bool overlaps(Span a, Span b) { - const auto x = reinterpret_cast(a.p), y = reinterpret_cast(b.p); - return x < y + b.n && y < x + a.n; -} -} // namespace - -void native_qsa_indexer_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); } -bool native_qsa_indexer_enabled() { return enabled.load(std::memory_order_relaxed); } -void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_device, int32_t pos_base, - const float* gamma, float epsilon, const QsaIndexerBuffers& b, - const QsaShapes& s, int64_t max_cells, const RopeScaling& scaling, void* stream) { - if (!stream || s.idx_dim != D || s.idx_block != R || s.n_rot != ROT || - max_cells < 1 || max_cells > INT32_MAX || pos_base < 0 || pos_base % R || - int64_t(pos_base) + max_cells > INT32_MAX || !std::isfinite(epsilon) || epsilon <= 0.0f || - rope_scaling_invalid(scaling) != nullptr) - throw std::invalid_argument("native QSA indexer requires fixed geometry, aligned position base, positive capacity/epsilon, valid frequency/scaling and explicit stream"); - const Span spans[] = {{raw,D*4},{relative_pos_device,4},{gamma,D*4},{b.tail,(R-1)*D*4}, - {b.dead,D*4},{b.pooled,std::size_t(max_cells/R+1)*D*4},{b.block_pos,4}}; - for (const auto& span : spans) validate(span); - for (int i = 0; i < 7; ++i) for (int j = i + 1; j < 7; ++j) - if (overlaps(spans[i], spans[j])) throw std::invalid_argument("native QSA indexer buffers overlap"); - const float theta_scale = powf((float) scaling.freq_base, -2.0f / ROT); - const RopeKernelArgs k = scaling.kernel_args(ROT); // none: the identity constants - const RopeTab rt = rope_table_for(scaling); - if (rt.cos != nullptr) - append<<<1,THREADS,0,static_cast(stream)>>>(raw,relative_pos_device,pos_base,gamma,epsilon, - b.tail,b.dead,b.pooled,b.block_pos,int(max_cells),theta_scale,k.freq_scale, - k.corr_low,k.corr_high,k.ext_factor,k.attn_factor,mrope_table(),rt); - else - append<<<1,THREADS,0,static_cast(stream)>>>(raw,relative_pos_device,pos_base,gamma,epsilon, - b.tail,b.dead,b.pooled,b.block_pos,int(max_cells),theta_scale,k.freq_scale, - k.corr_low,k.corr_high,k.ext_factor,k.attn_factor,mrope_table(),rt); - const auto error = cudaGetLastError(); - if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); -} -void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, int32_t pos_base, const float* gamma, - float epsilon, const QsaIndexerBuffers& b, const QsaShapes& s, int64_t max_cells, - const RopeScaling& scaling, void* stream) { - if (n <= 0) return; - if (!stream || s.idx_dim != D || s.idx_block != R || s.n_rot != ROT || p0 < 0 || p0 + n > max_cells || - max_cells > INT32_MAX || pos_base < 0 || pos_base % R || int64_t(pos_base) + max_cells > INT32_MAX || - !std::isfinite(epsilon) || epsilon <= 0.0f || rope_scaling_invalid(scaling) != nullptr) - throw std::invalid_argument("native QSA indexer (batch): bad geometry, positions, parameters or scaling"); - const float theta_scale = powf((float) scaling.freq_base, -2.0f / ROT); - const RopeKernelArgs k = scaling.kernel_args(ROT); // none: the identity constants - const float fsf = k.freq_scale, cl = k.corr_low, ch = k.corr_high, ef = k.ext_factor, ms = k.attn_factor; - const cudaStream_t st = static_cast(stream); - const int32_t* mtab = mrope_table(); - const RopeTab rt = rope_table_for(scaling); - if (p0 == 0) { - if (rt.cos != nullptr) - append_first<<<1, THREADS, 0, st>>>(raw, gamma, epsilon, b.dead, b.pooled, theta_scale, - fsf, cl, ch, ef, ms, mtab, rt); - else - append_first<<<1, THREADS, 0, st>>>(raw, gamma, epsilon, b.dead, b.pooled, theta_scale, - fsf, cl, ch, ef, ms, mtab, rt); - } - // completed blocks: those whose last cell (4b+3) lies in [p0, p0 + n) - const int64_t first = p0 <= R - 1 ? 0 : (p0 - (R - 1) + R - 1) / R; // the smallest b with 4b+3 >= p0 - const int64_t hi = p0 + n - 1 >= R - 1 ? (p0 + n - 1 - (R - 1)) / R : -1; // the largest b with 4b+3 <= p0+n-1 - if (hi >= first && rt.cos != nullptr) - append_blocks<<<(unsigned) (hi - first + 1), THREADS, 0, st>>>(raw, n, p0, pos_base, gamma, epsilon, - b.tail, b.dead, b.pooled, b.block_pos, first, hi, theta_scale, fsf, cl, ch, ef, ms, mtab, rt); - else if (hi >= first) - append_blocks<<<(unsigned) (hi - first + 1), THREADS, 0, st>>>(raw, n, p0, pos_base, gamma, epsilon, - b.tail, b.dead, b.pooled, b.block_pos, first, hi, theta_scale, fsf, cl, ch, ef, ms, mtab, rt); - append_tail<<>>(raw, n, p0, b.tail); - const auto error = cudaGetLastError(); - if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); -} -} // namespace strata::kernels diff --git a/src/kernels/cuda/native_qsa_score.cu b/src/kernels/cuda/native_qsa_score.cu deleted file mode 100644 index cdcfead..0000000 --- a/src/kernels/cuda/native_qsa_score.cu +++ /dev/null @@ -1,213 +0,0 @@ -// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d: -// ggml/src/ggml-cuda/{mmf.cuh,mma.cuh,unary.cu,binbcast.cu}. -// MIT License -// Copyright (c) 2023-2026 The ggml authors -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -#include "strata/kernels/native_qsa_score.hpp" -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { -std::atomic enabled{false}; -constexpr int D=128, HEADS=4, R=4, ROWS=32, WARPS=2, STRIDE=36, COMBINE=68; -struct TileA { uint32_t x[4]; }; -struct TileB { uint32_t x[2]; }; -struct TileC { float x[4]={0.0f,0.0f,0.0f,0.0f}; }; -#if !defined(__HIPCC__) -#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 -__device__ __forceinline__ void load_a(TileA& a,const float* p) { - const float* src=p+(threadIdx.x%16)*STRIDE+(threadIdx.x/16)*4; - asm volatile("ldmatrix.sync.aligned.m8n8.x4.b16 {%0,%1,%2,%3}, [%4];" - : "=r"(a.x[0]),"=r"(a.x[1]),"=r"(a.x[2]),"=r"(a.x[3]):"l"(src)); -} -__device__ __forceinline__ void load_b(TileB& b,const float* p) { - const float* src=p+(threadIdx.x%8)*STRIDE+((threadIdx.x/8)*4)%8; - asm volatile("ldmatrix.sync.aligned.m8n8.x2.b16 {%0,%1}, [%2];" - : "=r"(b.x[0]),"=r"(b.x[1]):"l"(src)); -} -__device__ __forceinline__ void mma(TileC& c,const TileA& a,const TileB& b) { - // Deliberately no cvt.rn.tf32: pinned mma.cuh passes raw F32 bits directly. - asm("mma.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};" - : "+f"(c.x[0]),"+f"(c.x[1]),"+f"(c.x[2]),"+f"(c.x[3]) - : "r"(a.x[0]),"r"(a.x[1]),"r"(a.x[2]),"r"(a.x[3]),"r"(b.x[0]),"r"(b.x[1])); -} -#endif -__global__ __launch_bounds__(64,1) void score_kernel( - const float* __restrict__ pooled,const float* __restrict__ query, - const float* __restrict__ bias,const int32_t* __restrict__ step, - int max_cells,float* __restrict__ cells) { - const int n=step[kStepNKv],full=step[kStepNBid]; - if(n<1||n>max_cells||step[kStepPos]!=n-1||full!=n/R|| - step[kStepWidth]!=(n<2051?n:2051))return; - const int row0=blockIdx.x*ROWS; - if(row0>full)return; - const int lane=threadIdx.x,warp=threadIdx.y; -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800 - // Turing (STRATA_EXPERIMENTAL_SM75, a layer-split stage): no tf32 mma. The same scores with FP32 FMAs, one row - // per thread of the first warp - rounded differently from the tensor-core path (FP32 instead of TF32 inputs). - if(warp!=0)return; - const int row=row0+lane; - if(row>full)return; - float h[HEADS]; - for(int j=0;jfull)return; - float h[HEADS]; -#pragma unroll - for(int j=0;jmax_cells||step[kStepPos]!=n-1||full!=n/R|| - step[kStepWidth]!=(n<2051?n:2051))return; - const int row=blockIdx.x; - if(row>full)return; - __shared__ float head_score[HEADS]; - const int head=threadIdx.x; - if(head0.0f?dot:0.0f; - } - __syncthreads(); - if(head==0){ - float sum=__fadd_rn(0.0f,head_score[0]); - sum=__fadd_rn(sum,head_score[1]); - sum=__fadd_rn(sum,head_score[2]); - sum=__fadd_rn(sum,head_score[3]); - if(bias)sum=__fadd_rn(sum,bias[row]); - sum=__fadd_rn(sum,row==full&&n%R?1e9f:0.0f); - sum=__fadd_rn(sum,0.0f); - for(int i=row*R;i(s.p); - if(!p||p%4||s.n>UINTPTR_MAX-p)throw std::invalid_argument("native QSA score requires aligned bounded spans"); -} -bool overlaps(Span a,Span b){ - const auto x=reinterpret_cast(a.p),y=reinterpret_cast(b.p); - return xINT32_MAX-3||max_blocks!=max_cells/R+1) - throw std::invalid_argument("native QSA score requires128dim/4heads/4cells/2048budget, exact capacities and explicit stream"); - const Span spans[]={{pooled,size_t(max_blocks)*D*4},{query,HEADS*D*4}, - {step,kStepCount*4},{cells,size_t(max_cells)*4},{bias,bias?size_t(max_blocks)*4:0}}; - const int count=bias?5:4; - for(int i=0;i(stream)>>>( - pooled,query,bias,step,int(max_cells),cells); -#else - score_kernel<<(stream)>>>( - pooled,query,bias,step,int(max_cells),cells); -#endif - const auto error=cudaGetLastError(); - if(error!=cudaSuccess)throw std::runtime_error(cudaGetErrorString(error)); -} -} // namespace strata::kernels diff --git a/src/kernels/cuda/native_rope.cu b/src/kernels/cuda/native_rope.cu deleted file mode 100644 index 57cbe79..0000000 --- a/src/kernels/cuda/native_rope.cu +++ /dev/null @@ -1,147 +0,0 @@ -// Numerical contract: pinned ggml/src/ggml-cuda/rope.cu, rope_multi/rope_yarn. -// Text positions are equal across the four IMRoPE sections, so section routing -// reduces to the one position associated with each contiguous row. -// MIT License -// -// Copyright (c) 2023-2026 The ggml authors -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -#include "strata/kernels/native_rope.hpp" -#include "strata/kernels/mrope.hpp" -#include -#include -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { -std::atomic enabled{false}; -bool overlaps(const void* a, size_t an, const void* b, size_t bn) { - auto x = reinterpret_cast(a), y = reinterpret_cast(b); - return x <= y ? y - x < an : x - y < bn; -} -// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table. The host launches whenever -// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it; -// with it merely skipped at run time, the compiled default path changed its results). -template -__global__ void apply(const float* x, float* out, int rows, int width, - int n_rot, float theta_scale, float freq_scale, float corr_low, float corr_high, - float ext_factor, float mscale, const int* positions, const int32_t* mtab, RopeTab rt) { - const int row = blockIdx.y; - const int pair = blockIdx.x * blockDim.x + threadIdx.x; - if (row >= rows || pair >= width / 2) return; - const size_t start = size_t(row) * width; - if (pair >= n_rot / 2) { - if (x != out) { - out[start + 2 * pair] = x[start + 2 * pair]; - out[start + 2 * pair + 1] = x[start + 2 * pair + 1]; - } - return; - } - float c, s; - if (!(TAB && rope_tab_cs(rt, mrope_pos(mtab, positions[row], pair), pair, c, s))) { - const float theta_extrap = mrope_pos(mtab, positions[row], pair) * powf(theta_scale, float(pair)); - rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); - } - const float a = x[start + pair], b = x[start + pair + n_rot / 2]; - out[start + pair] = a * c - b * s; - out[start + pair + n_rot / 2] = a * s + b * c; -} -} -// one table per device (a layer split runs the rope kernels on several): set and read for the current device -namespace { -constexpr int kMropeDevices = 64; -std::atomic mrope_tab[kMropeDevices] = {}; -int mrope_dev() { - int d = 0; - if (cudaGetDevice(&d) != cudaSuccess || d < 0 || d >= kMropeDevices) d = 0; - return d; -} -} // namespace -void mrope_table_set(const int32_t* device_table) { mrope_tab[mrope_dev()].store(device_table, std::memory_order_relaxed); } -const int32_t* mrope_table() { return mrope_tab[mrope_dev()].load(std::memory_order_relaxed); } -namespace { -// #280: the float64 angle table of each device, set at session init (before any graph is captured) -struct RopeReg { - RopeTab tab; - RopeScaling scaling; -}; -RopeReg rope_tab[kMropeDevices] = {}; -bool same_scaling(const RopeScaling& a, const RopeScaling& b) { - return a.type == b.type && a.freq_base == b.freq_base && a.factor == b.factor && a.freq_scale_in == b.freq_scale_in && - a.orig_ctx == b.orig_ctx && a.ext_factor == b.ext_factor && a.attn_factor == b.attn_factor && - a.beta_fast == b.beta_fast && a.beta_slow == b.beta_slow; -} -// opt-in: STRATA_ROPE_TABLE=1 (the table's angles differ from the fast-math ones in the last bits, so outputs move) -bool rope_table_enabled() { - static const bool on = [] { - const char* e = std::getenv("STRATA_ROPE_TABLE"); - return e != nullptr && e[0] == '1'; - }(); - return on; -} -} // namespace -void rope_table_set(const float* cos_tab, const float* sin_tab, int max_pos, const RopeScaling& scaling) { - rope_tab[mrope_dev()] = RopeReg{RopeTab{cos_tab, sin_tab, max_pos}, scaling}; -} -void rope_table_release(const float* cos_tab) { - // every device's entry that points at it (the caller may free it from another current device) - for (RopeReg& r : rope_tab) - if (cos_tab != nullptr && r.tab.cos == cos_tab) r = RopeReg{}; -} -RopeTab rope_table_for(const RopeScaling& scaling) { - if (!rope_table_enabled()) return {}; - const RopeReg& r = rope_tab[mrope_dev()]; - return r.tab.cos != nullptr && same_scaling(r.scaling, scaling) ? r.tab : RopeTab{}; -} -void native_rope_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); } -bool native_rope_enabled() { return enabled.load(std::memory_order_relaxed); } -void native_rope_apply(const float* x, float* out, int rows, int head_dim, - int n_rot, const RopeScaling& scaling, const int* positions, void* stream) { - if (!x || !out || !positions || !stream || rows < 1 || rows > 65535 || - (head_dim != 128 && head_dim != 256) || n_rot != 64 || - rope_scaling_invalid(scaling) != nullptr || - reinterpret_cast(x) % 4 || reinterpret_cast(out) % 4 || - reinterpret_cast(positions) % 4) { - throw std::invalid_argument("native RoPE requires aligned F32 rows, width 128/256, rotation 64, valid base/scaling and explicit stream"); - } - const size_t bytes = size_t(rows) * head_dim * sizeof(float); - if ((x != out && overlaps(x, bytes, out, bytes)) || - overlaps(positions, size_t(rows) * sizeof(int), out, bytes) || - overlaps(positions, size_t(rows) * sizeof(int), x, bytes)) { - throw std::invalid_argument("native RoPE buffers partially overlap"); - } - // Match pinned host-side float powf before device fast powf/trigonometry. - const float theta_scale = powf((float) scaling.freq_base, -2.0f / n_rot); - const RopeKernelArgs k = scaling.kernel_args(n_rot); // none: the identity constants - const RopeTab rt = rope_table_for(scaling); - const dim3 grid((head_dim / 2 + 127) / 128, rows); - if (rt.cos != nullptr) - apply<<(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale, - k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, positions, mrope_table(), rt); - else - apply<<(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale, - k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, positions, mrope_table(), rt); - const auto error = cudaGetLastError(); - if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); -} -} diff --git a/src/kernels/cuda/native_router.cu b/src/kernels/cuda/native_router.cu deleted file mode 100644 index 3f8b69c..0000000 --- a/src/kernels/cuda/native_router.cu +++ /dev/null @@ -1,127 +0,0 @@ -// Adapted from topk-moe.cu/common.cuh in llama.cpp -// 3cf03257f219afbe7334045ff7c6a06ac68c627d; finite F32, 512-expert/10-output path. -// MIT License -// Copyright (c) 2023-2026 The ggml authors -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -#include "strata/kernels/native_router.hpp" -#include -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { -std::atomic enabled{false}; -__device__ __forceinline__ float warp_sum(float value) { -#pragma unroll - for (int mask = 16; mask; mask >>= 1) value += __shfl_xor_sync(0xffffffffu, value, mask, 32); - return value; -} -__device__ __forceinline__ float warp_max(float value) { -#pragma unroll - for (int mask = 16; mask; mask >>= 1) value = fmaxf(value, __shfl_xor_sync(0xffffffffu, value, mask, 32)); - return value; -} -__launch_bounds__(256, 1) -__global__ void route(const float* __restrict__ logits, int32_t* __restrict__ ids, - float* __restrict__ weights) { - // Preserve the pinned 32x8 block geometry; only row zero is active here. - // blockIdx.x = the token (a multi-token launch; 0 for the single one) - logits += (size_t) blockIdx.x * 512; ids += (size_t) blockIdx.x * 10; weights += (size_t) blockIdx.x * 10; - if (threadIdx.y != 0) return; - const int lane = threadIdx.x; - float values[16]; -#pragma unroll - for (int i = 0; i < 16; ++i) values[i] = logits[lane + i * 32]; - __syncthreads(); - float maximum = -INFINITY; -#pragma unroll - for (int i = 0; i < 16; ++i) maximum = max(maximum, values[i]); - maximum = warp_max(maximum); - float sum = 0.0f; -#pragma unroll - for (int i = 0; i < 16; ++i) { - values[i] = expf(values[i] - maximum); - sum += values[i]; - } - const float reciprocal = 1.0f / warp_sum(sum); -#pragma unroll - for (int i = 0; i < 16; ++i) { - values[i] *= reciprocal; - if (__isnanf(values[i])) values[i] = -FLT_MAX; - } - float selected = 0.0f, selected_sum = 0.0f; - for (int rank = 0; rank < 10; ++rank) { - float best = values[0]; - int expert = lane; -#pragma unroll - for (int i = 1; i < 16; ++i) { - if (values[i] > best) { best = values[i]; expert = lane + i * 32; } - } -#pragma unroll - for (int mask = 16; mask; mask >>= 1) { - const float other = __shfl_xor_sync(0xffffffffu, best, mask, 32); - const int other_id = __shfl_xor_sync(0xffffffffu, expert, mask, 32); - if (other > best || (other == best && other_id < expert)) { best = other; expert = other_id; } - } - if ((expert & 31) == lane) { - values[expert / 32] = -INFINITY; - ids[rank] = expert; - // Deliberately accumulate by WINNING EXPERT lane, not output rank. - // Multiple selected experts in one lane add in selection order. - selected_sum += best; - } - if (rank == lane) selected = best; - } - selected_sum = max(warp_sum(selected_sum), 6.103515625e-5f); - const float inverse_selected_sum = 1.0f / selected_sum; - if (lane < 10) weights[lane] = selected * inverse_selected_sum; -} -bool valid(const void* p, size_t bytes) { - const auto address = reinterpret_cast(p); - return p && address % 4 == 0 && bytes <= UINTPTR_MAX - address; -} -bool overlap(const void* a, size_t an, const void* b, size_t bn) { - const auto ap = reinterpret_cast(a), bp = reinterpret_cast(b); - return ap < bp + bn && bp < ap + an; -} -} -void native_router_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); } -bool native_router_enabled() { return enabled.load(std::memory_order_relaxed); } -void native_router_top10(const float* logits, int32_t* ids, float* weights, void* stream) { - if (!stream || !valid(logits, 512 * 4) || !valid(ids, 10 * 4) || !valid(weights, 10 * 4) - || overlap(logits, 512 * 4, ids, 10 * 4) || overlap(logits, 512 * 4, weights, 10 * 4) - || overlap(ids, 10 * 4, weights, 10 * 4)) - throw std::invalid_argument("native router requires a stream, aligned spans, and disjoint outputs"); - route<<<1, dim3(32, 8), 0, static_cast(stream)>>>(logits, ids, weights); - const auto error = cudaGetLastError(); - if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); -} -void native_router_top10_multi(const float* logits, int32_t* ids, float* weights, int n_tok, void* stream) { - if (!stream || n_tok < 1 || !valid(logits, (size_t) n_tok * 512 * 4) || !valid(ids, (size_t) n_tok * 10 * 4) || - !valid(weights, (size_t) n_tok * 10 * 4)) - throw std::invalid_argument("native router (multi) requires a stream and aligned [n,512]/[n,10] buffers"); - route<<<(unsigned) n_tok, dim3(32, 8), 0, static_cast(stream)>>>(logits, ids, weights); - const auto error = cudaGetLastError(); - if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); -} -} diff --git a/src/kernels/cuda/ple.cu b/src/kernels/cuda/ple.cu deleted file mode 100644 index 984512b..0000000 --- a/src/kernels/cuda/ple.cu +++ /dev/null @@ -1,386 +0,0 @@ -// src/kernels/cuda/ple.cu - P2.S4: the PLE block's GPU half. -// -// See include/strata/kernels/ple.hpp for the structure and for the `normalized`-is-the-conv-input finding. -// -// The legacy arithmetic below follows the captured CPU ggml graph -// (`bench/micro/ple_in.bin` / `ple_out.bin`, produced by `ple_layer_xcheck.cpp`): -// -// * `rms_norm` accumulates `(double)(x*x)` with the PRODUCT rounded in f32 first - that is literally what -// `ggml_compute_forward_rms_norm_f32` does (`sum += (ggml_float)(x[i00]*x[i00])` with `ggml_float` = -// double), and it is not the same as accumulating in f32 or as widening before the multiply. -// * `silu` is `x / (1 + expf(-x))` in f32, which is `ggml_silu_f32`. -// * the gate's `sqrt` and `sigmoid` are f32. -// -// The opt-in native BF16 path replaces only ple_value with the pinned CUDA single-token BF16/F32 MMVF. -// A separate opt-in native postops path follows the pinned CUDA arithmetic after both projections. -#include "strata/kernels/ple.hpp" -#include "strata/kernels/bf16_gemv.hpp" -#include "strata/kernels/f16_bits.hpp" -#include "strata/kernels/ngram.hpp" -#include "strata/kernels/quantize_act.hpp" -#include "strata/kernels/s2_gemv_q8.hpp" -#include "strata/kernels/native_mmvq.hpp" -#include "strata/kernels/native_ple_postops.hpp" - -#include - -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int THREADS = 256; -bool native_bf16 = false; -bool native_postops = false; - -bool overlap(const void* a, size_t a_bytes, const void* b, size_t b_bytes) { - if (a == nullptr || b == nullptr || a_bytes == 0 || b_bytes == 0) return false; - const uintptr_t aa = reinterpret_cast(a), bb = reinterpret_cast(b); - return aa < bb ? bb - aa < a_bytes : aa - bb < b_bytes; -} - -__global__ void history_advance_kernel(float* __restrict__ history, const float* __restrict__ normalized) { - const int channel = blockIdx.x * blockDim.x + threadIdx.x; - if (channel >= NG_HC_DIM) return; - float* column = history + (size_t) channel * NG_HIST; - for (int row = 0; row + 1 < NG_HIST; ++row) column[row] = column[row + 1]; - column[NG_HIST - 1] = normalized[channel]; -} - -__device__ __forceinline__ uint16_t bf16_bits(float f) { - uint32_t i; - memcpy(&i, &f, 4); - i = (i + ((i >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u; - return (uint16_t) (i >> 16); -} - -__device__ __forceinline__ float bf16_float(uint16_t h) { - const uint32_t i = (uint32_t) h << 16; - float f; - memcpy(&f, &i, 4); - return f; -} - -__device__ __forceinline__ float silu_f(float x) { return x / (1.0f + expf(-x)); } - -/// Block-wide sum in double, broadcast to all threads. The leading `__syncthreads` matters: the result is -/// read out of `scratch[0]` and a later call reuses the array, so without a barrier a fast thread can -/// overwrite it before a slow one has read it - invisible in most runs and a slightly different norm when it -/// fires. -__device__ double block_sum(double v, double* scratch) { - __syncthreads(); - const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; - for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off); - if (lane == 0) scratch[warp] = v; - __syncthreads(); - const int nw = ((int) blockDim.x + 31) >> 5; - v = (threadIdx.x < nw) ? scratch[threadIdx.x] : 0.0; - if (warp == 0) - for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off); - if (threadIdx.x == 0) scratch[0] = v; - __syncthreads(); - return scratch[0]; -} - -/// `grouped_norm`, ONE BLOCK PER STREAM. The ggml form is `reshape_3d(x, n_embd, hc, T)` then -/// `rms_norm(..., eps) * w`, so ne0 = n_embd is the reduction axis and each hc stream is normalised on its -/// own. In the flat ggml layout (ne0 fastest) stream c occupies [c*n_embd, (c+1)*n_embd). -__global__ void gnorm_kernel(const float* __restrict__ x, const float* __restrict__ w, - float* __restrict__ y, int n_embd, float eps) { - __shared__ double scratch[8]; - const int c = blockIdx.x; - const float* xc = x + (size_t) c * n_embd; - const float* wc = w + (size_t) c * n_embd; - float* yc = y + (size_t) c * n_embd; - - double acc = 0.0; - for (int d = threadIdx.x; d < n_embd; d += blockDim.x) { - // The PRODUCT is rounded in f32 before it is widened - `(ggml_float)(x[i00]*x[i00])`. - const float sq = xc[d] * xc[d]; - acc += (double) sq; - } - const float mean = (float) (block_sum(acc, scratch) / (double) n_embd); - const float scale = 1.0f / sqrtf(mean + eps); - for (int d = threadIdx.x; d < n_embd; d += blockDim.x) yc[d] = xc[d] * scale * wc[d]; -} - -/// `s[c] = sum_d key[c][d]*query[c][d] / sqrt(n_embd)`, then the signed square root and the sigmoid. -/// -/// `mag = sqrt(clamp(|s|, 1e-6, inf))` and `gate = sigmoid(sgn(s) * mag)`. The clamp is a floor on |s|, so -/// it only bites near zero; the SIGN is carried separately, which is what keeps the gate symmetric about 0.5. -__global__ void gate_kernel(const float* __restrict__ key, const float* __restrict__ query, - float* __restrict__ gate, int n_embd, float inv_sqrt_n) { - __shared__ double scratch[8]; - const int c = blockIdx.x; - const float* kc = key + (size_t) c * n_embd; - const float* qc = query + (size_t) c * n_embd; - double acc = 0.0; - for (int d = threadIdx.x; d < n_embd; d += blockDim.x) acc += (double) (kc[d] * qc[d]); - const float s = (float) (block_sum(acc, scratch) / (double) 1.0) * inv_sqrt_n; - const float mag = sqrtf(fmaxf(fabsf(s), 1e-6f)); - const float sgn = (s > 0.0f) ? 1.0f : ((s < 0.0f) ? -1.0f : 0.0f); - if (threadIdx.x == 0) gate[c] = 1.0f / (1.0f + expf(-(sgn * mag))); -} - -/// `gated[c][d] = value[d] * gate[c]` - the value broadcast across the hc streams. -__global__ void bcast_kernel(const float* __restrict__ value, const float* __restrict__ gate, - float* __restrict__ gated, int n_embd, int hc) { - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n_embd * hc) return; - gated[i] = value[i % n_embd] * gate[i / n_embd]; -} - -/// The depthwise causal dilated conv, then SiLU. One thread per channel. -/// -/// `out[c] = sum_k kW[k][c] * terms[t - (kern-1-k)*dil][c]` with `t = hist` (the first new position), so tap k -/// reads row `hist - (kern-1-k)*dil` of `[history | new]`. For the real geometry (kern 4, dil 3, hist 9) the -/// four taps read rows 0, 3, 6 and 9 - and row 9 is the NEW row, which is the only one beyond the history. -/// That is why no `terms` buffer is built: three taps come from the caller's history and one from `norm`. -/// -/// `kW` IS GGML-NATIVE: `kW[k + kern*c]`. The manifest's shape is [4, 10240] with ne0 = 4 fast, and -/// `ref/ngram.py`'s (4, 10240) numpy `kernel[k][c]` is the TRANSPOSE of that. The source's own view -/// (`ggml_view_2d(model.layers[il].ple_conv1d, 1, hc_dim, nb[1], k*nb[0])`) settles which one is meant. -__global__ void conv_kernel(const float* __restrict__ hist, const float* __restrict__ norm, - const uint16_t* __restrict__ kW, float* __restrict__ out, int hc_dim, int kern, - int dil, int nhist) { - const int c = blockIdx.x * blockDim.x + threadIdx.x; - if (c >= hc_dim) return; - float acc = 0.0f; - for (int k = 0; k < kern; ++k) { - const int row = nhist - (kern - 1 - k) * dil; // tap 0 reads the FURTHEST back - // ROW-FASTEST: `hist[row + nhist*c]`. The conv state is `ggml_reshape_3d(state, d_conv-1, - // conv_channels, n_seqs)`, so ne0 = hist varies fastest and the flat index is row + hist*channel. - // Channel-slowest (`row*hc_dim + c`) is the natural thing to write and would read a transposed state - - // `ple_layer_xcheck.cpp` L79-83 records getting this wrong once already. - const float v = (row == nhist) ? norm[c] : hist[(size_t) row + (size_t) nhist * c]; - acc += f32_from_f16(kW[k + kern * c]) * v; - } - out[c] = silu_f(acc); -} - -/// `result = hidden + gated + conv`, elementwise over hc_dim. -__global__ void add3_kernel(const float* __restrict__ hidden, const float* __restrict__ gated, - const float* __restrict__ conv, float* __restrict__ result, int n) { - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) result[i] = hidden[i] + gated[i] + conv[i]; -} - -/// `y[o] = sum_i bf16(x[i]) * bf16(w[o*n_in + i])`. The weight is BF16 and so is the ACTIVATION, which is -/// the contract for a BF16 tensor (`docs/activation-contract.md`); with both sides bf16 the products are -/// exact in f32 and only the summation order differs from ggml's. -__global__ void bf16_gemv_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, - float* __restrict__ y, int n_in, int n_out) { - const int o = blockIdx.x * blockDim.x + threadIdx.x; - if (o >= n_out) return; - const uint16_t* row = w + (size_t) o * n_in; - double acc = 0.0; - for (int i = 0; i < n_in; ++i) acc += (double) bf16_float(x[i]) * (double) bf16_float(row[i]); - y[o] = (float) acc; -} - -__global__ void to_bf16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, int n) { - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) y[i] = bf16_bits(x[i]); -} - -void ck(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "ple_block: %s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -} // namespace - -void ple_set_native_bf16(bool enabled) { native_bf16 = enabled; } -bool ple_native_bf16_enabled() { return native_bf16; } -void ple_set_native_postops(bool enabled) { native_postops = enabled; } -bool ple_native_postops_enabled() { return native_postops; } - -void ple_history_advance(float* hist, const float* normalized, void* stream) { - if (hist == nullptr || normalized == nullptr) - throw std::invalid_argument("ple_history_advance: null history or normalized input"); - if (overlap(hist, (size_t) NG_HIST * NG_HC_DIM * sizeof(float), - normalized, (size_t) NG_HC_DIM * sizeof(float))) - throw std::invalid_argument("ple_history_advance: history and normalized input overlap"); - history_advance_kernel<<<(NG_HC_DIM + THREADS - 1) / THREADS, THREADS, 0, (cudaStream_t) stream>>>(hist, normalized); - ck(cudaGetLastError(), "history advance launch"); -} - -bool ple_block_available() { - int n = 0; - return cudaGetDeviceCount(&n) == cudaSuccess && n > 0; -} - -uint64_t ple_block_scratch_bytes() { - // five hc_dim floats + n_embd + hc, then the Q8 activation image, then the BF16 embedding copy, each - // 16-byte aligned because `d_scratch` is cast to `float*` and `d_act` to `uint8_t*` at those offsets. - const size_t f = (size_t) (5 * NG_HC_DIM + NG_N_EMBD + NG_HC) * sizeof(float); - const size_t q = (size_t) (NG_N_EMBD / 32) * 34; - const size_t e = (size_t) NG_N_EMBD * sizeof(uint16_t); - return ((f + 15) & ~(size_t) 15) + ((q + 15) & ~(size_t) 15) + e + 256; -} - -void ple_block(const float* emb, const float* hidden, const float* hist_rows, const PleWeights& w, - PleOut& out, void* scratch, void* stream) { - const bool native_key = w.key_native_data != nullptr && w.key_bf16 == nullptr; - if (native_key && (!emb || !hidden || !hist_rows || !out.result || !scratch || !stream || - !w.key_native_q8_1 || - (w.key_native_type != 42 && w.key_native_type != 18 && w.key_native_type != 23 && - w.key_native_type != 8))) - throw std::invalid_argument("ple_block: native key requires Q2_0, IQ3_XXS, IQ4_XS or Q8_0 weights, input/output, private scratch and explicit stream"); - if (emb == nullptr || hidden == nullptr || hist_rows == nullptr || out.result == nullptr) return; - const int n_embd = NG_N_EMBD, hc = NG_HC, hc_dim = NG_HC_DIM; - static_assert(NG_N_EMBD == 2560 && NG_HC_DIM == 10240, "native PLE key geometry changed"); - const size_t float_bytes = (size_t) (5 * hc_dim + n_embd + hc) * sizeof(float); - cudaStream_t st = (cudaStream_t) stream; - - // One allocation for every intermediate. - // - // THE ENGINE WILL NOT DO THIS. P2.T10 requires zero token-path allocations, and the fix is the same one - // `gr_read` already uses: a caller-owned workspace carved once at startup. It is done this way here - // because this function's job in P2.S4 is to be CORRECT and comparable against the oracle, and matching - // `shared_expert.cu`'s existing shape keeps the diff small. Recorded rather than hidden. - // - // FIVE SEPARATE hc_dim BUFFERS, deliberately. `key` and `normalized` are both needed at the end for the - // oracle comparison, so aliasing one onto the other - which the first version did - silently returns the - // WRONG `key`. Two buffers of the same size look like an obvious saving and the only thing it saves is - // 40 KB. - // **THE WORKSPACE IS CARVED FROM THE CALLER'S, NOT ALLOCATED.** Three `cudaMalloc`s and a - // `cudaStreamSynchronize` used to live here, and inside a stream capture both are errors: the engine - // reported `ple_block: scratch: operation not permitted when stream is capturing`, and a token-path - // allocation is a P2.T10 violation besides. The comment this replaces already said the right shape was - // "a caller-owned workspace carved once at startup"; this is that. - const size_t q8_bytes = (size_t) (n_embd / 32) * 34; - if (scratch == nullptr) { - std::fprintf(stderr, "ple_block: scratch is null; the caller owns it (see ple_block_scratch_bytes)\n"); - std::exit(1); - } - const struct Export { const float* pointer; size_t count; const char* name; } exports[] = { - {out.key, (size_t) hc_dim, "key"}, {out.value, (size_t) n_embd, "value"}, - {out.gate, (size_t) hc, "gate"}, {out.gated, (size_t) hc_dim, "gated"}, - {out.normalized, (size_t) hc_dim, "normalized"}, {out.conv, (size_t) hc_dim, "conv"}, - {out.result, (size_t) hc_dim, "result"} - }; - for (const auto& item : exports) { - if (overlap(item.pointer, item.count * sizeof(float), scratch, (size_t) ple_block_scratch_bytes())) - throw std::invalid_argument(std::string("ple_block: output ") + item.name + " overlaps scratch"); - } - if (native_key) { - const size_t native_bytes = native_q8_1_bytes(n_embd); - const size_t weight_bytes = native_mmvq_weight_bytes(w.key_native_type, n_embd, hc_dim); - if ((reinterpret_cast(w.key_native_data) & 3u) || - (reinterpret_cast(w.key_native_q8_1) & 3u)) - throw std::invalid_argument("ple_block: native key buffers require four-byte alignment"); - const struct Region { const void* pointer; size_t bytes; } regions[] = { - {scratch, (size_t) ple_block_scratch_bytes()}, {emb, (size_t) n_embd * 4}, - {hidden, (size_t) hc_dim * 4}, {hist_rows, (size_t) NG_HIST * hc_dim * 4}, - {w.key_native_data, weight_bytes}, {w.value_bf16, (size_t) n_embd * n_embd * 2}, - {w.norm_key, (size_t) hc_dim * 4}, {w.norm_query, (size_t) hc_dim * 4}, - {w.norm_conv, (size_t) hc_dim * 4}, {w.conv1d_f16, (size_t) PLE_CONV_KERNEL * hc_dim * 2} - }; - for (const auto& region : regions) - if (overlap(w.key_native_q8_1, native_bytes, region.pointer, region.bytes)) - throw std::invalid_argument("ple_block: native key scratch overlaps workspace, input or weight"); - for (const auto& item : exports) - if (overlap(w.key_native_q8_1, native_bytes, item.pointer, item.count * sizeof(float))) - throw std::invalid_argument(std::string("ple_block: native key scratch overlaps output ") + item.name); - } - uint8_t* base = (uint8_t*) scratch; - float* d_scratch = (float*) base; - uint8_t* d_act = base + ((float_bytes + 15) & ~(size_t) 15); - uint16_t* d_emb16 = (uint16_t*) (d_act + ((q8_bytes + 15) & ~(size_t) 15)); - float* d_key = d_scratch; - float* d_query = d_key + hc_dim; - float* d_norm = d_query + hc_dim; - float* d_gated = d_norm + hc_dim; - float* d_conv = d_gated + hc_dim; - float* d_value = d_conv + hc_dim; - float* d_gate = d_value + n_embd; - - // ---- key = grouped_norm(ple_key @ emb). The optional native projection - // follows pinned CUDA Q8_1 MMVQ; the default retains its canonical Q8_0 path. - if (w.key_bf16 != nullptr) { - bf16_gemv_fp32_mmvf(emb, w.key_bf16, d_key, n_embd, hc_dim, stream); - } else if (native_key) { - native_quantize_q8_1(emb, w.key_native_q8_1, n_embd, 1, stream); - native_mmvq(w.key_native_type, w.key_native_data, w.key_native_q8_1, - d_key, n_embd, hc_dim, 1, stream); - } else { - quantize_q8_0(emb, d_act, n_embd, st); - s2_gemv_q8(d_act, w.key_codes, w.key_scales, d_key, n_embd, hc_dim, 8, st); - } - if (!native_postops) { - gnorm_kernel<<>>(d_key, w.norm_key, d_key, n_embd, NG_RMS_EPS); - gnorm_kernel<<>>(hidden, w.norm_query, d_query, n_embd, NG_RMS_EPS); - } - - // The value projection's independent option leaves the nonlinear PLE operations unchanged. - if (native_bf16) { - bf16_gemv_fp32_mmvf(emb, w.value_bf16, d_value, n_embd, n_embd, stream); - } else { - to_bf16_kernel<<<(n_embd + THREADS - 1) / THREADS, THREADS, 0, st>>>(emb, d_emb16, n_embd); - bf16_gemv_kernel<<<(n_embd + THREADS - 1) / THREADS, THREADS, 0, st>>>(d_emb16, w.value_bf16, d_value, - n_embd, n_embd); - } - - const float* normalized_key = d_key; - if (native_postops) { - // The key norm has a distinct destination; temporary query storage can - // be reused for normalized gated values after the gate consumes it. - NativePlePostopsBuffers buffers{d_query,d_norm,d_gate,d_gated,d_norm,d_conv,out.result}; - native_ple_postops(d_key,hidden,d_value,hist_rows,w,buffers,stream); - normalized_key = d_query; - } else { - gate_kernel<<>>(d_key, d_query, d_gate, n_embd, 1.0f / sqrtf((float) n_embd)); - bcast_kernel<<<(hc_dim + THREADS - 1) / THREADS, THREADS, 0, st>>>(d_value, d_gate, d_gated, n_embd, hc); - gnorm_kernel<<>>(d_gated, w.norm_conv, d_norm, n_embd, NG_RMS_EPS); - conv_kernel<<<(hc_dim + THREADS - 1) / THREADS, THREADS, 0, st>>>(hist_rows, d_norm, w.conv1d_f16, d_conv, - hc_dim, PLE_CONV_KERNEL, NGRAM_SIZE, - NG_HIST); - add3_kernel<<<(hc_dim + THREADS - 1) / THREADS, THREADS, 0, st>>>(hidden, d_gated, d_conv, out.result, - hc_dim); - } - - // ---- the intermediates the oracle comparison needs. `key` is the NORMALISED key, because the source's - // `cb(key, ...)` capture is after `gnorm`; `value` is the projection before the gate. Each stage the - // oracle records is reproduced here so a mismatch can be attributed instead of guessed at. - if (out.key) ck(cudaMemcpyAsync(out.key, normalized_key, hc_dim * sizeof(float), cudaMemcpyDeviceToDevice, st), "key"); - if (out.value) - ck(cudaMemcpyAsync(out.value, d_value, n_embd * sizeof(float), cudaMemcpyDeviceToDevice, st), "value"); - if (out.gate) ck(cudaMemcpyAsync(out.gate, d_gate, hc * sizeof(float), cudaMemcpyDeviceToDevice, st), "gate"); - if (out.gated) - ck(cudaMemcpyAsync(out.gated, d_gated, hc_dim * sizeof(float), cudaMemcpyDeviceToDevice, st), "gated"); - if (out.normalized) - ck(cudaMemcpyAsync(out.normalized, d_norm, hc_dim * sizeof(float), cudaMemcpyDeviceToDevice, st), "norm"); - if (out.conv) - ck(cudaMemcpyAsync(out.conv, d_conv, hc_dim * sizeof(float), cudaMemcpyDeviceToDevice, st), "conv"); - - ck(cudaGetLastError(), "launch"); - // **NO `cudaStreamSynchronize` HERE.** It was there to make the function self-contained for the parity - // test, and inside a capture it is an error - a caller that wants the result immediately synchronises - // itself, and the engine's caller does not want that at all. -} - -void ple_block_projected(const float* projected_key, const float* projected_value, const float* hidden, - const float* hist_rows, const PleWeights& w, PleOut& out, void* scratch, void* stream) { - if (!projected_key || !projected_value || !hidden || !hist_rows || !out.result || !scratch) return; - const int n_embd = NG_N_EMBD, hc = NG_HC, hc_dim = NG_HC_DIM; - float* d_scratch = (float*) scratch; - float* d_key = d_scratch; - float* d_query = d_key + hc_dim; - float* d_norm = d_query + hc_dim; - float* d_gated = d_norm + hc_dim; - float* d_conv = d_gated + hc_dim; - float* d_value = d_conv + hc_dim; - float* d_gate = d_value + n_embd; - float* norm_dst = out.normalized ? out.normalized : d_norm; - NativePlePostopsBuffers buffers{d_query, norm_dst, d_gate, d_gated, norm_dst, d_conv, out.result}; - native_ple_postops(projected_key, hidden, projected_value, hist_rows, w, buffers, stream); -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/qsa.cu b/src/kernels/cuda/qsa.cu deleted file mode 100644 index acdd085..0000000 --- a/src/kernels/cuda/qsa.cu +++ /dev/null @@ -1,841 +0,0 @@ -// src/kernels/cuda/qsa.cu - P2.S2: the QSA cache, indexer and attention (see include/strata/kernels/qsa.hpp). -// -// The header documents the layouts and the scope; this file documents the four decisions that are about the -// KERNEL rather than about the interface. -// -// 1. THE THRESHOLD SEARCH IN `topk_512` RATHER THAN A SORT. The selection has to reproduce `ggml_top_k` on the -// masked per-cell scores with the reference's tie rule (ascending index), and it has to be EXACT: a -// different selected set is a different attention input, and `docs/capture-format.md` L127 gives -// `indexer_ids` no tolerance. The kernel therefore computes the width-th largest score as a 32-bit -// "order key" by binary lifting (32 monotone passes with `count(key >= cand) >= width`), and then emits - -// in ONE ascending walk - every cell strictly above it and the first `width - c_gt` cells equal to it. That -// is provably the same set as sorting by (score desc, index asc) and taking the first width, it needs no -// scratch and no sort, it is deterministic, and it is the reason `kTopkMaxCells` exists: the whole selection -// runs in ONE block so the ascending walk is a chunked scan rather than a second global pass. Phase 3 -// replaces it with a radix select; this one is the thing that radix select has to agree with. -// -// 2. ONE BLOCK PER HEAD IN `qsa_attend`, SCORES IN SHARED MEMORY. n_ids reaches 2051, so a per-head score -// vector is 8 KB and 24 heads are 24 blocks: the whole attention is 24 blocks x 256 threads, which is a -// small grid, but it is also exactly the shape the source uses (one flash tile per query head) and it keeps -// the softmax's three passes over the scores in shared memory instead of in global. The score loop has one -// thread per CELL walking the 256 dims sequentially, which reads 16-byte-vectorisable half2 runs; the value -// loop has one thread per DIM walking the cells, whose warp-wide reads are contiguous within a cell. Both -// are coalesced for the layout the gather produces. -// -// 3. NO `__float2half`. `f16_from_f32` from f16_bits.hpp, for the reason round 193 recorded: `__float2half` -// produced 0x2600 for 0x26DB and 0x3C01 for exactly 1.0. The parity test checks that converter against -// vectors generated by numpy's float16, which is an oracle sharing no code with it. -// -// 4. THE POOLING ARITHMETIC IS IN DOUBLE AND ORDER-FIXED. `pooled` and the spare key are compared BIT-EXACT -// against the reference (the spare key's rotation is at position 0, where the f32 rope kernel is an exact -// identity, so the comparison is not weakened by the rope). That needs the same summation order on both -// sides: the `r` raw keys are added in CELL order, the sum of squares runs d = 0..idx_dim-1 sequentially, -// and `__dadd_rn`/`__dmul_rn` block FMA contraction, which would otherwise fuse `ss + m*m` into one -// operation with no intermediate rounding and land one ulp away from the host. -// -// THE `d` IN THOSE NAMES IS NOT COSMETIC. The first version wrote `__fadd_rn`/`__fmul_rn`, which are -// the SINGLE-precision intrinsics: the compiler converted each double operand to float, operated -// there, and converted back, so the whole pooling arithmetic ran in single precision - `ss` held only -// float precision (121.82236480712891 on the device against 121.82236342931094 in the reference). -// Every comparison still passed at any sane tolerance, the spare key landing 0.4 f32 ulp away; only a -// BIT-EXACT assertion plus a full-precision probe of the intermediate found it. That is the strongest -// argument in this file for keeping both. -#include "strata/core/emulate.hpp" -#include "strata/kernels/qsa.hpp" - -#include "strata/kernels/f16_bits.hpp" -#include "strata/kernels/kv_stream.hpp" -#include "strata/kernels/rope.hpp" -#include "strata/kernels/mrope.hpp" - -#include - -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int THREADS = 128; - -void fail(const char* what) { - std::fprintf(stderr, "qsa: %s\n", what); - std::exit(1); -} - -void check_launch(const char* what) { - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "qsa: %s launch: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -/// The SYNCHRONOUS entry points must check their own wait. Without this the sticky error from a kernel that -/// faulted becomes visible only at the NEXT call's `cudaGetLastError()`, which then names the wrong kernel - -/// exactly the mis-attribution that made round 198's first `kv_append` failure look like a later one. -void check_sync(const char* what) { - const cudaError_t e = cudaDeviceSynchronize(); - if (e != cudaSuccess) { - std::fprintf(stderr, "qsa: %s (synchronise): %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -/// Geometry validation. A silently wrong `head_dim % 4` would corrupt the gather's uint2 copy and a silently -/// wrong `n_head % n_head_kv` would produce a plausible attention with the wrong key, so both are refused. -void validate(const QsaShapes& s, const char* who) { - char why[256]; - if (!qsa_shapes_valid(s, why, sizeof why)) { - std::fprintf(stderr, "qsa: %s: %s\n", who, why); - std::exit(1); - } -} -/// The indexer's own entry points: a dense shape (no indexer) has nothing for them to read. -void validate_indexer(const QsaShapes& s, const char* who) { - validate(s, who); - if (qsa_dense(s)) { - std::fprintf(stderr, "qsa: %s: the geometry has no indexer (dense attention); nothing to score or select\n", who); - std::exit(1); - } -} - -__device__ __forceinline__ float h2f(uint16_t bits) { return f32_from_f16(bits); } - -// ================= 1. kv_append ================= - -__global__ void kv_append_kernel(uint16_t* __restrict__ k_pool, uint16_t* __restrict__ v_pool, - const int32_t* __restrict__ table, const int32_t* __restrict__ step, - const float* __restrict__ kcur, const float* __restrict__ vcur, int kv_heads, - int head_dim, int page_size, KvHostPools host) { - const long long pos = (long long) __ldg(step + kStepPos); - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i >= kv_heads * head_dim) return; - const int h = i / head_dim, d = i - h * head_dim; - // `[page][kv_head][page_size][head_dim]`: one head's consecutive cells are contiguous inside a page. - // KV streaming: the host copy (identity layout) always, the VRAM page only if the block is resident. - const long long page = (long long) table[pos / page_size]; - if (page >= 0) { - const long long row = (page * kv_heads + h) * page_size + (pos % page_size); - k_pool[row * head_dim + d] = f16_from_f32(kcur[i]); - v_pool[row * head_dim + d] = f16_from_f32(vcur[i]); - } - if (host.k_pool != nullptr) { - const long long row = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size); - host.k_pool[row * head_dim + d] = f16_from_f32(kcur[i]); - host.v_pool[row * head_dim + d] = f16_from_f32(vcur[i]); - } -} - -// ================= 2. indexer_key_append ================= - -/// Appends the raw key, and on a block completion pools AND ROTATES the pooled row. One thread per indexer -/// dim, shared `mean` in double. -/// -/// **THE ROTATION IS INSIDE THIS KERNEL, AND THAT IS WHAT MAKES THE WHOLE FUNCTION CAPTURABLE.** It used to be -/// a second launch from the host wrapper, guarded by `if (pos % idx_block == idx_block - 1)` - a HOST branch on -/// `pos`, which forced `pos` to be a host scalar, which meant a captured graph would replay the first token's -/// position forever. Doing it here reads the position from `pos_dev` like every other kernel, so the grid and -/// the arguments are the same for every token and the graph replays correctly. -__global__ void indexer_key_append_kernel(const float* __restrict__ raw, const int32_t* __restrict__ pos_dev, - int pos_base, const float* __restrict__ w_k_norm, float eps, - float* __restrict__ tail, float* __restrict__ dead, - float* __restrict__ pooled, int32_t* __restrict__ block_pos, - int idx_dim, int r, int n_rot, const float* __restrict__ cos_tab, - const float* __restrict__ sin_tab, const int32_t* __restrict__ mtab) { - extern __shared__ double s_mean[]; // idx_dim doubles - const int d = threadIdx.x; - const int pos = (int) __ldg(pos_dev); - const int slot = pos % r; - - // The RAW tail: a cell that COMPLETES a block is not stored, because the pool below consumes it directly. - // That is what makes `idx_block - 1` rows enough. - if (slot < r - 1) tail[(size_t) slot * idx_dim + d] = raw[d]; - - // The spare slot's key is `rms_norm(raw[0])`, which is CONSTANT for the sequence and is the only reason - // cell 0's raw key has to be kept: the three-row tail no longer holds it after the first block. - if (pos == 0) { - double p = (double) raw[d]; - double ss = 0.0; - // Same order as the pooled path, so the two are comparable: sum of squares over the dims, sequential. - // Every thread computes the same `ss` and uses only its own output element. - // - // `__dadd_rn`/`__dmul_rn`, NOT `__fadd_rn`/`__fmul_rn`: the `f` names are the SINGLE-precision - // intrinsics, and using them on doubles silently rounds every operation to float. `ss` then carries - // only float precision (121.82236480712891 against the reference's 121.82236342931094) and the spare - // key comes out 0.4 f32 ulp away - close enough that only a BIT-EXACT assertion notices. `__ddiv_rn` - // and `__dsqrt_rn` pin the reciprocal square root for the same reason. - for (int i = 0; i < idx_dim; ++i) { - const double v = (double) raw[i]; - ss = __dadd_rn(ss, __dmul_rn(v, v)); - } - const double inv = __ddiv_rn(1.0, __dsqrt_rn(ss / (double) idx_dim + (double) eps)); - float y = (float) (p * inv * (double) w_k_norm[d]); - // The spare rotates at position 0 - ALWAYS row 0 of the table, whatever `pos_base` is, as the native - // indexer's spare does. At angle 0 the sine is exactly 0 in every scaling (sin(0) * mscale), so the - // pair rotation reduces to `v * cos_tab[pair]` with no partner element to read (and no barrier). - // Unscaled, row 0 is exactly (1, 0) and `v * 1.0f` is `v` bit for bit - today's value, which the - // parity test holds bit-exact. Under YaRN row 0 is (mscale, 0): the rotated dims carry the magnitude - // correction exactly like every other pooled row and like the native kernel's spare (the unrotated - // dims pass through, as in the rotation of the completed blocks below). Skipping the rotation here, - // as this kernel once did, left `dead` and `pooled[0]` the only unscaled keys of a scaled cache. - if (d < n_rot) y *= cos_tab[d % (n_rot / 2)]; - dead[d] = y; - pooled[d] = y; - } - - if (slot != r - 1) return; - __syncthreads(); // the tail rows this thread is about to read are written above - - // The mean of this block's r raw keys, in CELL order: the r-1 tail rows (slots 0..r-2) then the incoming - // cell (slot r-1). The sum of r f32 values is exact in double, so the mean's order cannot matter here - - // but the order of the SUM OF SQUARES below can, and it is fixed to d ascending on both sides. - double m = 0.0; - for (int j = 0; j < r - 1; ++j) m = __dadd_rn(m, (double) tail[(size_t) j * idx_dim + d]); - m = __dadd_rn(m, (double) raw[d]); - m = m / (double) r; - s_mean[d] = m; - __syncthreads(); - - double ss = 0.0; - for (int i = 0; i < idx_dim; ++i) ss = __dadd_rn(ss, __dmul_rn(s_mean[i], s_mean[i])); - const double inv = __ddiv_rn(1.0, __dsqrt_rn(ss / (double) idx_dim + (double) eps)); - - const int b = pos / r; - pooled[(size_t) b * idx_dim + d] = (float) (m * inv * (double) w_k_norm[d]); - // The spare slot MOVES to b+1 and is rewritten with the same constant value. - pooled[(size_t) (b + 1) * idx_dim + d] = dead[d]; - // The rotation position for this row, kept because a capture reader and the debug dumps want it. It is the - // block's first cell's POSITION, `pos_base + b*r`, and NOT the cell index `b*r`. - if (d == 0) *block_pos = (int32_t) (pos_base + b * r); - __syncthreads(); // the row is complete only now; the rotation below reads TWO elements of it - - // ---- the rotation of the row that just completed, IN PLACE. - // - // `i` pairs with `i + half`, so only the first `half` threads do any work - but EVERY thread must reach the - // barrier above, which is why the guard is here and not around the whole block's tail. - // - // The position is the BLOCK'S FIRST cell (`ref/qsa.py` PROPERTY 4: rotating at the block's last cell keeps - // every shape and every magnitude), and it comes from `pos_base`, which is constant for a sequence. - const int half = n_rot / 2; - if (d < half) { - float* row = pooled + (size_t) b * idx_dim; - const size_t toff = (size_t) mrope_pos(mtab, pos_base + b * r, d) * half; - // THE SAME `rope_neox_pair` THE STANDALONE ROPE KERNEL USES. A second transcription of the pairing is - // what this project keeps finding written down wrong. - rope_neox_pair(row[d], row[half + d], cos_tab[toff + d], sin_tab[toff + d], row[d], row[half + d]); - } -} - -// ================= 3. qsa_index ================= - -/// One warp per indexer head, one block per pooled row; thread 0 sums the relu'd dots IN HEAD ORDER and maps -/// the row's score onto its cells. The reference's Relu is PER HEAD, so the dots cannot be summed first. -__global__ void qsa_index_kernel(const float* __restrict__ pooled, - const float* __restrict__ q_idx, const float* __restrict__ bias, - int idx_n_head, int idx_dim, long long r, - const int32_t* __restrict__ step, float* __restrict__ cell_scores) { - const long long n_bid = (long long) __ldg(step + kStepNBid); - const long long n_kv = (long long) __ldg(step + kStepNKv); - __shared__ double s_dot[32]; - const long long b = blockIdx.x; - // A BLOCK PAST THE COMPLETED-BLOCK COUNT MUST DO NOTHING. This is what lets the LAYER launch a CONSTANT - // grid of the maximum block count instead of this token's `n_bid + 1`: a grid sized from a per-token value - // is a per-token LAUNCH CONFIGURATION, and a CUDA graph bakes those in exactly as it bakes in an argument. - // Without this guard, a capacity-sized grid would score pooled rows that have not been written yet - - // reading zeros and producing a plausible score for a block that does not exist. - if (b > n_bid) return; - const int wid = threadIdx.x >> 5, lane = threadIdx.x & 31; - if (wid == 0) s_dot[lane] = 0.0; // thread 0 reads all idx_n_head entries; zero the unused ones - __syncthreads(); - - double acc = 0.0; - for (int d = lane; d < idx_dim; d += 32) - acc = __dadd_rn(acc, __dmul_rn((double) pooled[(size_t) b * idx_dim + d], - (double) q_idx[(size_t) wid * idx_dim + d])); - for (int o = 16; o > 0; o >>= 1) acc = __dadd_rn(acc, __shfl_xor_sync(0xffffffffu, acc, o)); - if (lane == 0) s_dot[wid] = acc; - __syncthreads(); - - if (threadIdx.x != 0) return; - double score = 0.0; - for (int h = 0; h < idx_n_head; ++h) score += (s_dot[h] > 0.0) ? s_dot[h] : 0.0; - if (bias != nullptr) score += (double) bias[b]; - // cell_block: cells of block b for b < n_bid, and the WHOLE incomplete tail for b == n_bid - long long lo = b * r, hi = lo + r; - if (b == n_bid) hi = n_kv; - if (hi > n_kv) hi = n_kv; - // llama-memory-hybrid-idx.cpp::set_input_qsa gives incomplete-tail cells - // a finite +1e9 bias before top-k. Read the current step on every replay: - // the spare row becomes an ordinary block as soon as its fourth cell arrives. - float sc = (float) score; - if (b == n_bid && n_kv % r != 0) sc += 1e9f; - for (long long j = lo; j < hi; ++j) cell_scores[j] = sc; -} - -// ================= 4. topk_512 ================= - -/// Total order over f32 as an unsigned key, so one integer comparison orders scores with numpy's float -/// semantics. `+ 0.0f` maps -0.0 to +0.0 because numpy treats them as EQUAL (and would break the tie by -/// index), while the raw bit pattern orders them. A NaN is mapped to 0, below every real key, i.e. never -/// selected - numpy sorts NaN LAST, and silently selecting one would be worse than the disagreement. -__device__ __forceinline__ uint32_t order_key(float s) { - const float v = s + 0.0f; - if (!(v == v)) return 0u; - uint32_t b; - memcpy(&b, &v, 4); - return (b & 0x80000000u) ? ~b : (b | 0x80000000u); -} - -constexpr int TOPK_THREADS = 256; - -__global__ void topk_kernel(const float* __restrict__ scores, const int32_t* __restrict__ step, - int* __restrict__ out_ids) { - const long long n_kv = (long long) __ldg(step + kStepNKv); - const long long width = (long long) __ldg(step + kStepWidth); - __shared__ int s_a[TOPK_THREADS]; - __shared__ int s_b[TOPK_THREADS]; - __shared__ long long s_cgt; - const int t = threadIdx.x; - const long long chunk = (n_kv + TOPK_THREADS - 1) / TOPK_THREADS; - const long long lo = (long long) t * chunk; - long long hi = lo + chunk; - if (hi > n_kv) hi = n_kv; - - // ---- binary lifting: the largest key v with count(key >= v) >= width. Monotone in v, so setting the - // bits from the top down lands on exactly that value, and count(>= v) >= width > count(>= v+1). - uint32_t v = 0u; - for (int bit = 31; bit >= 0; --bit) { - const uint32_t cand = v | (1u << bit); - int c = 0; - for (long long j = lo; j < hi; ++j) if (order_key(scores[j]) >= cand) ++c; - s_a[t] = c; - __syncthreads(); - for (int s = TOPK_THREADS / 2; s > 0; s >>= 1) { - if (t < s) s_a[t] += s_a[t + s]; - __syncthreads(); - } - const int tot = s_a[0]; - __syncthreads(); // before the next round overwrites s_a - if (tot >= (int) width) v = cand; - } - const uint32_t thr = v; - - // ---- counts and their exclusive prefixes. The prefixes are computed by thread 0 in one walk, which is - // 256 iterations ONCE per kernel and removes 2 log-steps of scan machinery from a path that is already - // 32 passes deep. - int gt = 0, eq = 0; - for (long long j = lo; j < hi; ++j) { - const uint32_t k = order_key(scores[j]); - if (k > thr) ++gt; - else if (k == thr) ++eq; - } - s_a[t] = gt; - s_b[t] = eq; - __syncthreads(); - if (t == 0) { - long long ag = 0, ae = 0; - for (int i = 0; i < TOPK_THREADS; ++i) { - const int g = s_a[i], e = s_b[i]; - s_a[i] = (int) ag; - s_b[i] = (int) ae; - ag += g; - ae += e; - } - s_cgt = ag; // how many are strictly above the threshold, i.e. where the equals start - } - __syncthreads(); - // THE RANK VS THE COUNT. `off_eq` is how many equal-to-threshold cells come BEFORE this chunk, and it is - // compared against `eq_budget`, the number of them the selection has room for. The first version wrote - // `c_gt + prefix_eq` - where an equal cell would land in a "greater-than first, then equal" LAYOUT - and - // compared THAT against the budget. With distinct scores `c_gt == width` and `eq_budget == 0`, so nothing - // was ever selected at the threshold and the kernel emitted `width` ids with one missing and one stale. - // Every all-equal fixture passed, because there `c_gt == 0` and the two readings coincide. - const long long off_eq = s_b[t]; - const long long eq_budget = width - s_cgt; - - // ---- how many this chunk selects, so the ascending walk can be scattered into place - int sel = 0; - { - long long e = off_eq; - for (long long j = lo; j < hi; ++j) { - const uint32_t k = order_key(scores[j]); - if (k > thr) ++sel; - else if (k == thr && e < eq_budget) { ++sel; ++e; } - } - } - s_a[t] = sel; - __syncthreads(); - if (t == 0) { - long long a = 0; - for (int i = 0; i < TOPK_THREADS; ++i) { - const int c = s_a[i]; - s_a[i] = (int) a; - a += c; - } - } - __syncthreads(); - - // ---- emit, walking the cells ASCENDING so the tie rule's "first by index" is the walk order itself - long long w = s_a[t]; - long long e = off_eq; - for (long long j = lo; j < hi; ++j) { - const uint32_t k = order_key(scores[j]); - if (k > thr) out_ids[w++] = (int) j; - else if (k == thr && e < eq_budget) { ++e; out_ids[w++] = (int) j; } - } -} - -// ================= 5. kv_gather ================= - -__global__ void kv_gather_kernel(const uint16_t* __restrict__ k_pool, const uint16_t* __restrict__ v_pool, - const int32_t* __restrict__ table, const int32_t* __restrict__ ids, - const int32_t* __restrict__ step, int kv_heads, int head_dim, int page_size, - uint16_t* __restrict__ k_scratch, uint16_t* __restrict__ v_scratch) { - const long long n_ids = (long long) __ldg(step + kStepWidth); - const int per = head_dim / 4; // 4 halfs per uint2 - const long long total = n_ids * kv_heads * per; - const long long i = blockIdx.x * (long long) blockDim.x + threadIdx.x; - if (i >= total) return; - const long long id = i / (kv_heads * (long long) per); - const int rem = (int) (i % (kv_heads * (long long) per)); - const int h = rem / per, q = rem - h * per; - const int cell = ids[id]; - const long long page = (long long) table[cell / page_size]; - const long long src = ((page * kv_heads + h) * page_size + (cell % page_size)) * (long long) per + q; - const long long dst = (id * kv_heads + h) * (long long) per + q; - reinterpret_cast(k_scratch)[dst] = reinterpret_cast(k_pool)[src]; - reinterpret_cast(v_scratch)[dst] = reinterpret_cast(v_pool)[src]; -} - -// ================= 6. qsa_attend ================= - -__device__ __forceinline__ float warp_max(float v) { - for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o)); - return v; -} - -__device__ __forceinline__ float warp_sum(float v) { - for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); - return v; -} - -/// One block per query head. `s` holds the scores, which are then overwritten with the softmax weights. -__global__ void qsa_attend_kernel(const float* __restrict__ q, const uint16_t* __restrict__ k_scratch, - const uint16_t* __restrict__ v_scratch, const int32_t* __restrict__ step, - int n_head, int n_head_kv, int head_dim, - float* __restrict__ attn, float* __restrict__ weights) { - const long long n_ids = (long long) __ldg(step + kStepWidth); - extern __shared__ float s_w[]; // CAPACITY floats (scores, then weights) + 32 for the reductions - float* red = s_w; // red[0..31] live past the scores/weights: see the launch - float* w = s_w + 32; - const int h = blockIdx.x; - const int d = threadIdx.x; - // AN EMPTY SELECTION IS HANDLED HERE, not by a host early return. The wrapper used to check `n_ids == 0` - // and `cudaMemsetAsync` the output, but `n_ids` is a device value now - so the branch has to be on the - // device, and this is also the only form a graph can replay: the launch is unconditional and the kernel - // decides. Below the selection bound the selection is the IDENTITY, so `n_ids` is never 0 there; it is - // reachable only for a genuinely empty cache, and the reference returns zeros for that. - if (n_ids == 0) { - for (int i = d; i < head_dim; i += blockDim.x) attn[(size_t) h * head_dim + i] = 0.0f; - return; - } - const int kv = h / (n_head / n_head_kv); // ops.cpp L8729: iv2 = iq2 / rv2, NOT h % n_head_kv - const float scale = 1.0f / sqrtf((float) head_dim); - const int lane = d & 31, wid = d >> 5, nwarp = (int) ((blockDim.x + 31) >> 5); - - for (long long j = d; j < n_ids; j += blockDim.x) { - const uint16_t* krow = k_scratch + (j * n_head_kv + kv) * head_dim; - float acc = 0.0f; - for (int i = 0; i < head_dim; ++i) acc += h2f(krow[i]) * q[(size_t) h * head_dim + i]; - w[j] = acc * scale; - } - __syncthreads(); - - float mx = -FLT_MAX; // not -inf, whose double -> float conversion nvcc warns about - for (long long j = d; j < n_ids; j += blockDim.x) mx = fmaxf(mx, w[j]); - mx = warp_max(mx); - if (lane == 0) red[wid] = mx; - __syncthreads(); - if (wid == 0) { - mx = (lane < nwarp) ? red[lane] : -FLT_MAX; - mx = warp_max(mx); - if (lane == 0) red[0] = mx; - } - __syncthreads(); - mx = red[0]; - __syncthreads(); - - float sum = 0.0f; - for (long long j = d; j < n_ids; j += blockDim.x) { - const float e = expf(w[j] - mx); - w[j] = e; - sum += e; - } - sum = warp_sum(sum); - if (lane == 0) red[wid] = sum; - __syncthreads(); - if (wid == 0) { - sum = (lane < nwarp) ? red[lane] : 0.0f; - sum = warp_sum(sum); - if (lane == 0) red[0] = 1.0f / sum; - } - __syncthreads(); - const float inv = red[0]; - __syncthreads(); - - float acc = 0.0f; - for (long long j = 0; j < n_ids; ++j) - acc += (w[j] * inv) * h2f(v_scratch[(j * n_head_kv + kv) * head_dim + d]); - attn[(size_t) h * head_dim + d] = acc; - if (weights != nullptr) { - for (long long j = d; j < n_ids; j += blockDim.x) weights[(size_t) h * n_ids + j] = w[j] * inv; - } -} - -// ================= 7. qsa_gate_apply ================= - -__global__ void qsa_gate_apply_kernel(const float* __restrict__ attn, const float* __restrict__ q_full, - int n_head, int head_dim, uint16_t* __restrict__ out) { - const long long i = blockIdx.x * (long long) blockDim.x + threadIdx.x; - if (i >= (long long) n_head * head_dim) return; - const int h = (int) (i / head_dim), d = (int) (i % head_dim); - const double g = (double) q_full[((size_t) h * 2 * head_dim) + head_dim + d]; // the SECOND half - const double sig = 1.0 / (1.0 + exp(-g)); - out[i] = f16_from_f32((float) ((double) attn[i] * sig)); -} - -inline unsigned grid_for(long long n, int threads) { - return (unsigned) ((n + threads - 1) / threads); -} - -} // namespace - -/// THE STEP STATE, UPLOADED. Every kernel below reads its per-token counts from here rather than from a kernel -/// argument, because a CUDA graph bakes arguments in at capture time - see the long note in `qsa.hpp`. This -/// module-level buffer is what lets the OLD host-scalar signatures keep working unchanged while the kernels -/// already read the device values; the layer will pass its own buffer once it captures. -/// -/// It is per-PROCESS and reused, which is safe because the upload and the kernel that reads it are on the same -/// stream and the host is the only writer. `cudaMemcpyAsync` on the null stream is ordered against the null -/// stream's kernels, which is what every direct-launch caller here uses. -namespace { - -int32_t* step_scratch() { - static int32_t* d_step = nullptr; - if (d_step == nullptr) { - if (cudaMalloc(&d_step, qsa_step_bytes()) != cudaSuccess) { - std::fprintf(stderr, "qsa: step upload: cudaMalloc failed\n"); - std::exit(1); - } - } - return d_step; -} - -void step_upload_raw(const int32_t* h_step) { - int32_t* d = step_scratch(); - if (cudaMemcpy(d, h_step, qsa_step_bytes(), cudaMemcpyHostToDevice) != cudaSuccess) { - std::fprintf(stderr, "qsa: step upload: cudaMemcpy failed\n"); - std::exit(1); - } -} - -/// From a POSITION: fills all four entries. This is the form the layer will use, and the only form that cannot -/// produce an inconsistent `n_kv`/`n_bid`/`width`. -const int32_t* step_upload(int64_t pos, int64_t n_kv_hint, const QsaShapes& s) { - int32_t h[kStepCount]; - qsa_step_fill(h, pos, s); - // A caller that also knows `n_kv` is CHECKED against it rather than believed: a disagreement is exactly the - // inconsistency `qsa_step_fill` exists to make impossible, so it is worth an exit rather than a silent - // preference for one of the two. - if (n_kv_hint >= 0 && n_kv_hint != (int64_t) h[kStepNKv]) { - std::fprintf(stderr, "qsa: step upload: n_kv %lld disagrees with pos+1 = %d\n", (long long) n_kv_hint, - h[kStepNKv]); - std::exit(1); - } - step_upload_raw(h); - return step_scratch(); -} - -/// From a WIDTH. `kv_gather` and `qsa_attend` are handed the selection width directly and never see `pos`, so -/// only that entry is meaningful for them; the others are set consistently anyway rather than left stale, -/// because a stale entry is a value the NEXT kernel might read. -const int32_t* step_upload_width(int64_t width, const QsaShapes& s) { - int32_t h[kStepCount]; - for (int i = 0; i < kStepCount; ++i) h[i] = 0; - h[kStepWidth] = (int32_t) width; - (void) s; - step_upload_raw(h); - return step_scratch(); -} - -} // namespace - -// ================= THE CAPTURABLE ENTRY POINTS ================= -// -// These are the REAL implementations: every launch below is sized from a constant capacity and every per-token -// count comes from `step`. The host-scalar entry points further down are wrappers that fill a module-level step -// buffer and forward this token's counts as the capacities. - -void kv_append_step(uint16_t* k_pool, uint16_t* v_pool, const int32_t* page_table, const int32_t* step, - const float* kcur, const float* vcur, const QsaShapes& s, void* stream, const KvHostPools* host) { - validate(s, "kv_append"); - if (step == nullptr) fail("kv_append: step is null"); - // The grid is the head x dim count, which is a CONSTANT - `kv_append` writes one cell. - const long long n = s.n_head_kv * s.head_dim; - kv_append_kernel<<>>( - k_pool, v_pool, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size, - host ? *host : KvHostPools{}); - check_launch("kv_append"); - if (stream == nullptr) check_sync("kv_append"); -} - -void qsa_index_step(const float* pooled, const float* q_idx, const float* bias, const QsaShapes& s, - const int32_t* step, int64_t max_blocks, float* cell_scores, void* stream) { - validate_indexer(s, "qsa_index"); - 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 - // `b > n_bid`, so the surplus blocks cost a launch and nothing else. - const int threads = 32 * (int) s.idx_n_head; - qsa_index_kernel<<<(unsigned) max_blocks, threads, 0, (cudaStream_t) stream>>>( - pooled, q_idx, bias, (int) s.idx_n_head, (int) s.idx_dim, s.idx_block, step, cell_scores); - check_launch("qsa_index"); - if (stream == nullptr) check_sync("qsa_index"); -} - -void topk_512_step(const float* cell_scores, const QsaShapes& s, int64_t cap, const int32_t* step, - int32_t* ids, void* stream) { - validate_indexer(s, "topk_512"); - 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 - // `n_kv <= kTopkMaxCells`, so this is the most the kernel can ever write. - const int64_t width_max = qsa_selection_width(kTopkMaxCells, s); - if (cap < width_max) { - std::fprintf(stderr, "qsa: topk_512: cap %lld < the largest possible selection width %lld\n", - (long long) cap, (long long) width_max); - std::exit(1); - } - // One block, so the launch is already constant; the kernel reads `n_kv` and `width` from `step`. - topk_kernel<<<1, TOPK_THREADS, 0, (cudaStream_t) stream>>>(cell_scores, step, ids); - check_launch("topk_512"); - if (stream == nullptr) check_sync("topk_512"); -} - -void kv_gather_step(const uint16_t* k_pool, const uint16_t* v_pool, const int32_t* page_table, - const int32_t* ids, const int32_t* step, int64_t max_ids, const QsaShapes& s, - uint16_t* k_scratch, uint16_t* v_scratch, void* stream) { - validate(s, "kv_gather"); - if (step == nullptr) fail("kv_gather: step is null"); - if (max_ids <= 0) return; - // THE GRID IS THE CAPACITY. The kernel reads the real `n_ids` from `step` and its `if (i >= total) return;` - // guard leaves the surplus threads idle. - const long long total = max_ids * s.n_head_kv * (s.head_dim / 4); - kv_gather_kernel<<>>( - k_pool, v_pool, page_table, ids, step, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size, - k_scratch, v_scratch); - check_launch("kv_gather"); - if (stream == nullptr) check_sync("kv_gather"); -} - -void qsa_attend_step(const float* q, const uint16_t* k_scratch, const uint16_t* v_scratch, - const int32_t* step, int64_t max_ids, const QsaShapes& s, float* attn, float* weights, - void* stream) { - validate(s, "qsa_attend"); - if (step == nullptr) fail("qsa_attend: step is null"); - if (max_ids <= 0) fail("qsa_attend: max_ids must be positive"); - // THE SHARED SIZE IS THE CAPACITY. Shared memory is part of the LAUNCH CONFIGURATION, so sizing it from - // this token's `n_ids` bakes the sequence length in: a captured layer would allocate room for token 1 and - // then index past it at token 500. The kernel reads the real count from `step`, so a larger allocation is - // exactly what it wants. The opt-in therefore happens once, for the capacity. - const size_t smem = (size_t) (max_ids + 32) * sizeof(float); - // per DEVICE: the opt-in is a device setting (a layer split runs this on two cards) - static size_t s_configured_dev[64] = {}; - int cur_dev = 0; - cudaGetDevice(&cur_dev); - size_t& s_configured = s_configured_dev[(cur_dev >= 0 && cur_dev < 64) ? cur_dev : 0]; - if (smem > s_configured) { - int dev = 0, max_shared = 0; - cudaGetDevice(&dev); - cudaDeviceGetAttribute(&max_shared, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev); - max_shared = strata::smem_optin_of(max_shared); - if ((int) smem > max_shared) { - std::fprintf(stderr, "qsa: qsa_attend: max_ids %lld needs %zu B of shared, over the %d B limit\n", - (long long) max_ids, smem, max_shared); - std::exit(1); - } - const cudaError_t e = - cudaFuncSetAttribute(qsa_attend_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem); - if (e != cudaSuccess) { - std::fprintf(stderr, "qsa: qsa_attend: shared opt-in: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - s_configured = smem; - } - qsa_attend_kernel<<<(unsigned) s.n_head, (unsigned) s.head_dim, smem, (cudaStream_t) stream>>>( - q, k_scratch, v_scratch, step, (int) s.n_head, (int) s.n_head_kv, (int) s.head_dim, attn, weights); - check_launch("qsa_attend"); - if (stream == nullptr) check_sync("qsa_attend"); -} - -// ================= 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"); - // ONE PLACE COMPUTES ALL FOUR, which is the whole reason the step state is a BUFFER rather than four - // separate parameters. `n_kv`, `n_bid` and `width` are DERIVED from `pos`, so a caller filling them in - // itself could fill them inconsistently - and `qsa_index`'s host guard against exactly that inconsistency - // now has a single writer to check against instead of two independent arguments. - // - // This is the form the LAYER will use: every value a QSA kernel needs derives from one position, so one - // H2D per token updates all of them and no entry point takes a per-token scalar. - const int64_t n_kv = pos + 1; - host_step[kStepPos] = (int32_t) pos; - host_step[kStepNKv] = (int32_t) n_kv; - host_step[kStepNBid] = (int32_t) (n_kv / s.idx_block); - host_step[kStepWidth] = (int32_t) qsa_selection_width(n_kv, s); -} - -void kv_append(uint16_t* k_pool, uint16_t* v_pool, const int32_t* page_table, int64_t pos, - const float* kcur, const float* vcur, const QsaShapes& s, void* stream) { - if (pos < 0) { validate(s, "kv_append"); fail("kv_append: pos < 0"); } - kv_append_step(k_pool, v_pool, page_table, step_upload(pos, -1, s), kcur, vcur, s, stream); -} - -void indexer_key_append(const float* raw, const int32_t* pos_dev, int32_t pos_base, const float* w_k_norm, - float eps, const QsaIndexerBuffers& b, const QsaShapes& s, const float* cos_tab, - const float* sin_tab, void* stream) { - validate_indexer(s, "indexer_key_append"); - 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)"); - const int threads = (int) s.idx_dim; - const size_t smem = (size_t) s.idx_dim * sizeof(double); - // **ONE LAUNCH, NO HOST BRANCH ON THE POSITION.** The completion rotation is inside the kernel now. The - // arguments here are identical for every token, which is the property a CUDA graph needs: this function can - // be captured and replayed, and the position arrives through `pos_dev` like every other kernel's data. - indexer_key_append_kernel<<<1, threads, smem, (cudaStream_t) stream>>>( - raw, pos_dev, (int) pos_base, w_k_norm, eps, b.tail, b.dead, b.pooled, b.block_pos, (int) s.idx_dim, - (int) s.idx_block, (int) s.n_rot, cos_tab, sin_tab, mrope_table()); - check_launch("indexer_key_append"); - if (stream == nullptr) check_sync("indexer_key_append"); -} - -void qsa_index(const float* pooled, int64_t n_bid, const float* q_idx, const float* bias, const QsaShapes& s, - int64_t n_kv, float* cell_scores, void* stream) { - validate_indexer(s, "qsa_index"); - 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. - if ((n_kv / s.idx_block) != n_bid) { - std::fprintf(stderr, "qsa: qsa_index: n_bid %lld is not n_kv %lld / r %lld\n", (long long) n_bid, - (long long) n_kv, (long long) s.idx_block); - std::exit(1); - } - // THIS TOKEN'S counts as the CAPACITIES: correct for a direct launch, WRONG in a graph. The layer passes a - // constant `max_blocks` from its state instead - see the note in `qsa.hpp`. - qsa_index_step(pooled, q_idx, bias, s, step_upload(n_kv - 1, n_kv, s), n_bid + 1, cell_scores, stream); -} - -void topk_512(const float* cell_scores, int64_t n_kv, const QsaShapes& s, int64_t cap, int32_t* ids, - void* stream) { - validate_indexer(s, "topk_512"); - 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", - (long long) n_kv, (long long) kTopkMaxCells); - std::exit(1); - } - topk_512_step(cell_scores, s, cap, step_upload(n_kv - 1, n_kv, s), ids, stream); -} - -void kv_gather(const uint16_t* k_pool, const uint16_t* v_pool, const int32_t* page_table, const int32_t* ids, - int64_t n_ids, const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream) { - validate(s, "kv_gather"); - if (n_ids <= 0) return; - kv_gather_step(k_pool, v_pool, page_table, ids, step_upload_width(n_ids, s), n_ids, s, k_scratch, - v_scratch, stream); -} - -void qsa_attend(const float* q, const uint16_t* k_scratch, const uint16_t* v_scratch, int64_t n_ids, - const QsaShapes& s, float* attn, float* weights, void* stream) { - validate(s, "qsa_attend"); - if (n_ids < 0) fail("qsa_attend: n_ids < 0"); - if (n_ids == 0) { - // The empty selection goes through the kernel's own zero path; `max_ids` must still be positive, so the - // wrapper gives it the geometry's capacity rather than 0. - qsa_attend_step(q, k_scratch, v_scratch, step_upload_width(0, s), - qsa_selection_width(kTopkMaxCells, s), s, attn, weights, stream); - return; - } - qsa_attend_step(q, k_scratch, v_scratch, step_upload_width(n_ids, s), n_ids, s, attn, weights, stream); -} - -/// The same multiply as `qsa_gate_apply_kernel` WITHOUT the fp16 round - see the header for why the caller -/// whose weight is a K-quant needs the f32 form. Identical arithmetic up to the last step. -__global__ void qsa_gate_apply_f32_kernel(const float* __restrict__ attn, const float* __restrict__ q_full, - int n_head, int head_dim, float* __restrict__ out) { - const long long i = blockIdx.x * (long long) blockDim.x + threadIdx.x; - if (i >= (long long) n_head * head_dim) return; - const int h = (int) (i / head_dim), d = (int) (i % head_dim); - const double g = (double) q_full[((size_t) h * 2 * head_dim) + head_dim + d]; // the SECOND half - const double sig = 1.0 / (1.0 + exp(-g)); - out[i] = (float) ((double) attn[i] * sig); -} - -void qsa_gate_apply_f32(const float* attn, const float* q_full, const QsaShapes& s, float* out, void* stream) { - validate(s, "qsa_gate_apply_f32"); - const long long n = s.n_head * s.head_dim; - qsa_gate_apply_f32_kernel<<>>(attn, q_full, (int) s.n_head, - (int) s.head_dim, out); - check_launch("qsa_gate_apply_f32"); - if (stream == nullptr) check_sync("qsa_gate_apply_f32"); -} - -void qsa_gate_apply(const float* attn, const float* q_full, const QsaShapes& s, uint16_t* out, void* stream) { - validate(s, "qsa_gate_apply"); - const long long n = s.n_head * s.head_dim; - qsa_gate_apply_kernel<<>>(attn, q_full, (int) s.n_head, - (int) s.head_dim, out); - check_launch("qsa_gate_apply"); - if (stream == nullptr) check_sync("qsa_gate_apply"); -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu deleted file mode 100644 index 9a31cab..0000000 --- a/src/kernels/cuda/qsa_decode_attn.cu +++ /dev/null @@ -1,793 +0,0 @@ -// src/kernels/cuda/qsa_decode_attn.cu - see include/strata/kernels/qsa_decode_attn.hpp. -#include "strata/kernels/qsa_decode_attn.hpp" -#include "strata/kernels/kv_q8.hpp" -#include "strata/kernels/kv_q4.hpp" - -#include -#include - -#include -#include -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int HD = 256; // head_dim -constexpr int CHUNK = 64; // cells per SUB-CHUNK: the unit of the score / softmax / value phases below -constexpr int 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 - for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); - return v; -} -__device__ __forceinline__ float warp_max(float v) { -#pragma unroll - for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o)); - return v; -} - -// 8 consecutive values of one cell's key or value row for KV head `kvh`, dimensions [d0, d0+8). -// Per-format bodies; `load8` below is the KV_MODE dispatcher. value=false is the K side, true the V side. -__device__ __forceinline__ void load8_f16(const QsaAttnPools& p, bool value, long long row, int d0, float* out) { - const uint16_t* base = (value ? p.v_pool : p.k_pool) + row * HD + d0; - const uint4 raw = *reinterpret_cast(base); - const __half2* h2 = reinterpret_cast(&raw); -#pragma unroll - for (int j = 0; j < 4; ++j) { - const float2 f = __half22float2(h2[j]); - out[2 * j] = f.x; - out[2 * j + 1] = f.y; - } -} -__device__ __forceinline__ void load8_q8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) { - const int8_t* codes = (value ? p.v_q : p.k_q) + row * HD + d0; - const uint16_t sbits = (value ? p.v_scale : p.k_scale)[row * (HD / KV_Q8_GROUP) + d0 / KV_Q8_GROUP]; - const float sc = __half2float(__ushort_as_half(sbits)); - const uint2 raw = *reinterpret_cast(codes); - const int8_t* c = reinterpret_cast(&raw); -#pragma unroll - for (int j = 0; j < 8; ++j) out[j] = (float) c[j] * sc; -} -__device__ __forceinline__ void load8_q4(const QsaAttnPools& p, bool value, long long row, int d0, float* out) { - constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0); - const int b = d0 / QK4_0; - const int rem = d0 % QK4_0; - const block_q4_0* blk = reinterpret_cast((value ? p.v_q4 : p.k_q4) + row * bytes_per_head) + b; - const float d = __half2float(__ushort_as_half(blk->d)); - const int j = (rem == 0 || rem == 16) ? 0 : 8; - const uint8_t* bytes = blk->qs + j; - if (rem < 16) { -#pragma unroll - for (int k = 0; k < 8; ++k) out[k] = (float) ((int)(bytes[k] & 0x0F) - 8) * d; - } else { -#pragma unroll - for (int k = 0; k < 8; ++k) out[k] = (float) ((int)(bytes[k] >> 4) - 8) * d; - } -} -template -__device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) { - if constexpr (KV_MODE == 0) load8_f16(p, value, row, d0, out); - else if constexpr (KV_MODE == 1) load8_q8(p, value, row, d0, out); - else if constexpr (KV_MODE == 3) { - // hybrid K8V4: both sides are defined - K unrotated INT8, V rotated Q4_0 - so a value=true call - // reads the Q4_0 pool instead of dereferencing the null v_q (no call site does today; PR review) - if (value) load8_q4(p, value, row, d0, out); - else load8_q8(p, value, row, d0, out); - } else load8_q4(p, value, row, d0, out); -} - -template -__global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __restrict__ q, QsaAttnPools p, - const int32_t* __restrict__ ids, - const int32_t* __restrict__ step, int n_kv_heads, - int page_size, float scale, float* __restrict__ part_acc, - float* __restrict__ part_m, float* __restrict__ part_l, - int n_chunks, int cap = 0, long long scratch_stride = 0) { - // 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, then probabilities - __shared__ long long srow[CHUNK]; // pool row of each cell (page, kv head, slot) - __shared__ float srun_m[G], srun_l[G], sfac[G]; // the running max / sum per head, and this sub-chunk's rescale - const int n_ids = __ldg(step + kStepWidth); - const int chunk = blockIdx.x, kvh = blockIdx.y; - const int t = threadIdx.x, lane = t & 31, warp = t >> 5; - // this block's span: the selection in ceil(n_ids / 64) sub-chunks, spread over the n_chunks blocks - const int span = ((((n_ids + CHUNK - 1) / CHUNK) + n_chunks - 1) / n_chunks) * CHUNK; - const int begin = chunk * span; - const int end = min(begin + span, n_ids); - const int 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; - 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(p, false, srow[c], lane * 8, k8); -#pragma unroll - for (int h = 0; h < G; ++h) { - const float4 qa = *reinterpret_cast(&sq[h][lane * 8]); - const float4 qb = *reinterpret_cast(&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(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]; -} - -// PR #540 (sskver): the same attention with fewer shuffles and less shared-memory traffic, bit for bit the kernel -// above (same operands, same order); +7% prompt speed on a V100, where this kernel reads every prompt chunk. It -// uses more registers (80 vs 38 on sm_70), so it runs on cards below sm_75 only, and exists only in the experimental -// build (-DSTRATA_EXPERIMENTAL_SM60=ON): the ready-made engine keeps exactly the kernel above. -#if defined(STRATA_EXPERIMENTAL_SM60) -// The 12 heads' lane sums (`part[12..15]` zero), reduce-scattered with warp_sum's pairing order (xor 16, 8, 4, 2, 1): -// every output adds the same two operands at every level, so each sum is bit for bit warp_sum's (float add commutes), -// for 16 shuffles instead of 12 x 5. Lane l ends holding head head_of_lane(l); lanes l and l^1 agree. -__device__ __forceinline__ float reduce12(const float (&part)[16], int lane) { - float r8[8]; -#pragma unroll - for (int i = 0; i < 8; ++i) { - const bool hi = (lane & 16) != 0; - r8[i] = (hi ? part[i + 8] : part[i]) + __shfl_xor_sync(0xffffffffu, hi ? part[i] : part[i + 8], 16); - } - float r4[4]; -#pragma unroll - for (int i = 0; i < 4; ++i) { - const bool hi = (lane & 8) != 0; - r4[i] = (hi ? r8[i + 4] : r8[i]) + __shfl_xor_sync(0xffffffffu, hi ? r8[i] : r8[i + 4], 8); - } - float r2[2]; -#pragma unroll - for (int i = 0; i < 2; ++i) { - const bool hi = (lane & 4) != 0; - r2[i] = (hi ? r4[i + 2] : r4[i]) + __shfl_xor_sync(0xffffffffu, hi ? r4[i] : r4[i + 2], 4); - } - const bool hi2 = (lane & 2) != 0; - const float r1 = (hi2 ? r2[1] : r2[0]) + __shfl_xor_sync(0xffffffffu, hi2 ? r2[0] : r2[1], 2); - return r1 + __shfl_xor_sync(0xffffffffu, r1, 1); -} -__device__ __forceinline__ int head_of_lane(int lane) { - return ((lane >> 4) & 1) * 8 + ((lane >> 3) & 1) * 4 + ((lane >> 2) & 1) * 2 + ((lane >> 1) & 1); -} - -// One V element of pool row `row`, dimension `d` (the value loop's own thread index), per KV format. -template -__device__ __forceinline__ float load_v1(const QsaAttnPools& p, long long row, int d) { - if constexpr (KV_MODE == 0) { - return __half2float(__ushort_as_half(p.v_pool[row * HD + d])); - } else if constexpr (KV_MODE == 1) { - const float sc = __half2float(__ushort_as_half(p.v_scale[row * (HD / KV_Q8_GROUP) + d / KV_Q8_GROUP])); - return (float) p.v_q[row * HD + d] * 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 = d / QK4_0; - const int rem = d % QK4_0; - const block_q4_0* blk = reinterpret_cast(p.v_q4 + row * bytes_per_head) + b; - const float dd = __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); - return (float) nibble * dd; - } -} - -template -__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(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(&sq[h][lane * 8]); - const float4 qb = *reinterpret_cast(&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(p, false, srow[c], lane * 8, k8); - float part[16]; -#pragma unroll - for (int h = 0; h < G; ++h) { - const float4 qa = *reinterpret_cast(&sq[h][lane * 8]); - const float4 qb = *reinterpret_cast(&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(spt[c]); - acc[0] = fmaf(w.x, v, acc[0]); acc[1] = fmaf(w.y, v, acc[1]); - } else { - const float4* w4 = reinterpret_cast(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(p, r0, t), v1 = load_v1(p, r1, t); - const float v2 = load_v1(p, r2, t), v3 = load_v1(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(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 -__global__ void __launch_bounds__(THREADS) attn_chunk_kernel_pre75_single(const float* __restrict__ q, QsaAttnPools p, - const int32_t* __restrict__ ids, - const int32_t* __restrict__ step, int n_kv_heads, - int page_size, float scale, float* __restrict__ part_acc, - float* __restrict__ part_m, float* __restrict__ part_l, - int n_chunks, int cap = 0, long long scratch_stride = 0) { - // batched form: query blockIdx.z, with its own q row, selection, step and scratch - q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD; - if (ids != nullptr) ids += (size_t) blockIdx.z * (size_t) cap; // null: the identity (dense attention) - step += (size_t) blockIdx.z * kStepCount; - part_acc += (size_t) blockIdx.z * (size_t) scratch_stride; - part_m += (size_t) blockIdx.z * (size_t) scratch_stride; - part_l += (size_t) blockIdx.z * (size_t) scratch_stride; - static_assert(G == 2 || G % 4 == 0, "the value loop reads the weights as float4 (one float2 at G 2)"); - __shared__ __align__(16) float sq[G][HD]; // 12 KB at G 12: this KV head's query heads (dead once the scores are done) - __shared__ 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 - // __syncthreads that ends the score phase, the last reader of sq, so they share its storage (64 x 12 of its 256 x 12 - // floats) and the block's shared memory stays what it was before the cell-major layout. - float (*const spt)[G] = reinterpret_cast(&sq[0][0]); - static_assert(CHUNK * G <= G * HD, "spt must fit in sq"); - 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); - const int slot = kvh * n_chunks + chunk; - if (n_here <= 0) { - if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; } - return; - } - for (int i = t; i < G * HD; i += THREADS) sq[i / HD][i % HD] = q[(size_t) (kvh * G) * HD + i]; - if (t < 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 (24 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) - const int hd = head_of_lane(lane); - 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(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(&sq[h][lane * 8]); - const float4 qb = *reinterpret_cast(&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(p, false, srow[c], lane * 8, k8); - float part[16]; -#pragma unroll - for (int h = 0; h < G; ++h) { - const float4 qa = *reinterpret_cast(&sq[h][lane * 8]); - const float4 qb = *reinterpret_cast(&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 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; - spt[lane][h] = ea; - spt[lane + 32][h] = 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 G heads. - float acc[G]; -#pragma unroll - for (int h = 0; h < G; ++h) acc[h] = 0.0f; - // One cell's G weights (broadcast float4 loads) into the G accumulators; the cells are folded in - // 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(spt[c]); - acc[0] = fmaf(w.x, v, acc[0]); acc[1] = fmaf(w.y, v, acc[1]); - } else { - const float4* w4 = reinterpret_cast(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(p, r0, t), v1 = load_v1(p, r1, t); - const float v2 = load_v1(p, r2, t), v3 = load_v1(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(p, srow[c], t)); - } -#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 -__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, - float* __restrict__ attn, long long scratch_stride = 0) { - part_acc += (size_t) blockIdx.y * (size_t) scratch_stride; - part_m += (size_t) blockIdx.y * (size_t) scratch_stride; - part_l += (size_t) blockIdx.y * (size_t) scratch_stride; - attn += (size_t) blockIdx.y * (size_t) gridDim.x * HD; - const int h = blockIdx.x; // global query head - const int kvh = h / G, hl = h % G; - const int d = threadIdx.x; - float M = -FLT_MAX; - for (int c = 0; c < n_chunks; ++c) M = fmaxf(M, part_m[(kvh * n_chunks + c) * G + hl]); - float L = 0.0f, acc = 0.0f; - for (int c = 0; c < n_chunks; ++c) { - const int slot = kvh * n_chunks + c; - const float m = part_m[slot * G + hl]; - if (m == -FLT_MAX) continue; - const float w = __expf(m - M); - L = fmaf(part_l[slot * G + hl], w, L); - acc = fmaf(part_acc[((size_t) slot * G + hl) * HD + d], w, acc); - } - attn[(size_t) h * HD + d] = L > 0.0f ? acc / L : 0.0f; -} - -#if defined(STRATA_EXPERIMENTAL_SM60) -// the current device is below sm_75 (per device: a layer split can mix cards); STRATA_ATTN_PRE75=0 turns PR #540's -// kernel off (A/B) -bool pre75_attn() { - static const bool off = [] { - const char* e = std::getenv("STRATA_ATTN_PRE75"); - return e != nullptr && e[0] == '0'; - }(); - static int cc[64] = {}; - int dev = 0; - if (off) return false; - if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } - if (cc[dev] == 0) { - int major = 0, minor = 0; - if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess || - cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) { - cudaGetLastError(); - return false; - } - cc[dev] = 10 * major + minor; - } - return cc[dev] < 75; -} -#define STRATA_ATTN_CHUNK(M, G) (pre75_attn() ? (!dense || n_chunks < kMaxChunks ? attn_chunk_kernel_pre75_single : attn_chunk_kernel_pre75) : attn_chunk_kernel) -#else -#define STRATA_ATTN_CHUNK(M, G) attn_chunk_kernel -#endif - -int kv_mode_of(const QsaAttnPools& pools) { - return pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 : (pools.k_q != nullptr ? 1 : 0)); -} - -template -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; - float* part_m = scratch + (size_t) n_chunks * s.n_head * HD; - float* part_l = part_m + (size_t) n_chunks * s.n_head; - const float scale = 1.0f / sqrtf((float) HD); - const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q); - if (kv_mode == 3) - STRATA_ATTN_CHUNK(3, G)<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, - scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); - else if (kv_mode == 2) - STRATA_ATTN_CHUNK(2, G)<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, - scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); - else if (kv_mode == 1) - STRATA_ATTN_CHUNK(1, G)<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, - scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); - else - STRATA_ATTN_CHUNK(0, G)<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, - scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); - attn_merge_kernel<<>>(part_acc, part_m, part_l, n_chunks, - attn, stride); -} - -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) { - 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) { - 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 unsigned bx = (unsigned) std::min((cap + 255) / 256, 64); - identity_ids_kernel<<>>(ids, steps, (long long) cap); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "qsa_identity_ids: %s\n", cudaGetErrorString(e)); - std::exit(1); - } -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/qsa_prompt_attn.cu b/src/kernels/cuda/qsa_prompt_attn.cu deleted file mode 100644 index a6bd3eb..0000000 --- a/src/kernels/cuda/qsa_prompt_attn.cu +++ /dev/null @@ -1,1499 +0,0 @@ -// src/kernels/cuda/qsa_prompt_attn.cu - see include/strata/kernels/qsa_prompt_attn.hpp. -#include "strata/core/emulate.hpp" -#include -#include -#include "strata/kernels/qsa_prompt_attn.hpp" -#include "strata/kernels/kv_q8.hpp" -#include "strata/kernels/kv_q4.hpp" - -#include -#include -#include - -#include -#include -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int HD = 256; // head_dim -// `G`, the query heads per KV head, is a template parameter of every kernel below (2, 8, 12: qsa_attn_group); the -// MMA tiles are 16 query rows, so every G <= 16 pads with zero rows exactly as 12 did. -#ifndef D1_CH -#define D1_CH 32 -#endif -constexpr int CH = D1_CH; // cells per chunk -constexpr int THREADS = 128; // 4 warps: scores by cell (8 each), p.v by dimension (64 each = one int8 scale group) -constexpr int QS = HD + 8; // q row stride in halves (bank-conflict-free fragment loads) - -// The MMA below needs sm_75 or newer (Turing runs it as two k=8 steps); cp.async needs sm_80. Builds for pre-sm_75 -// cards compile the MMA to a trap; qsa_prompt_attn_batch refuses such a device at run time, so the old kernel runs -// there. Turing compiles cp_async16 to a trap as well and takes the v1 kernel instead of launch_i8. -#if defined(__HIPCC__) // AMD: no mma.sync / cp.async; the host keeps the old kernel (below) -#define STRATA_PA_SM80 0 -#elif !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 -#define STRATA_PA_SM80 1 -#else -#define STRATA_PA_SM80 0 -#endif - -// m16n8k16 with f16 inputs needs sm_80. Turing (sm_75) has m16n8k8 with the SAME A/B/C register mapping, so the -// k=16 step is two k=8 steps on the fragments as they are already laid out: a[0]/a[1] are rows gid/gid+8 at k columns -// 2*tig..2*tig+1 (b[0]'s k rows), a[2]/a[3] the same rows at k columns 2*tig+8..2*tig+9 (b[1]'s k rows). The -// products then add into the same FP32 C registers in the order hi-part-0, hi-part-1, which is the order the k16 -// instruction accumulates in as well - but the sum now rounds twice, so the two paths do not agree bit for bit. -__device__ __forceinline__ void mma16816(float* c, const uint32_t* a, const uint32_t* b) { -#if !STRATA_PA_SM80 && (defined(__HIPCC__) || !defined(__CUDA_ARCH__) || __CUDA_ARCH__ < 750) - __trap(); // AMD and pre-Turing builds: no mma.sync (the host keeps the old kernel there) -#elif !STRATA_PA_SM80 - asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" - : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) - : "r"(a[0]), "r"(a[1]), "r"(b[0])); - asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" - : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) - : "r"(a[2]), "r"(a[3]), "r"(b[1])); -#else - asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, " - "{%0,%1,%2,%3};\n" - : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) - : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1])); -#endif -} - -// Two int8 codes (low byte first) as an exact half2: 1024 + (c + 128) built in the mantissa, minus 1152. -__device__ __forceinline__ uint32_t i8x2_to_h2(uint32_t x) { - uint32_t y = ((x & 0xffu) | ((x & 0xff00u) << 8)) ^ 0x00800080u; - y |= 0x64006400u; - __half2 h = *reinterpret_cast<__half2*>(&y); - h = __hsub2(h, __halves2half2(__float2half(1152.f), __float2half(1152.f))); - return *reinterpret_cast(&h); -} - -__device__ __forceinline__ uint32_t pack_h2(float lo_k, float hi_k) { // element k in the low half - __half2 h = __floats2half2_rn(lo_k, hi_k); - return *reinterpret_cast(&h); -} - -// KV_MODE 1: int8 codes + fp16 scale per 64 values. KV_MODE 0: fp16 values (scales 1). -// KV_MODE 3 (hybrid K8V4): K as mode 1, V as mode 0 - the row's q4_0 blocks are dequantized to fp16 at -// gather, so everything downstream of the load is the mode-0 V path; the caller un-rotates the output. -// KV_MODE 4 (Q4_0 K and V, `--kv q4_0`): mode 1 with a scale per 32 values - each q4_0 block's codes enter as exact -// int8 (code - 8) and its fp16 scale is applied in FP32, as mode 1's are; the caller rotates q and un-rotates the -// output (kv_q4.hpp). -template -struct Smem { - using KElem = typename std::conditional::type; - using VElem = typename std::conditional::type; - static constexpr int KROW = KV_MODE == 0 ? HD + 8 : HD + 16; // elements; 16-byte aligned rows, banks spread - static constexpr int VROW = (KV_MODE == 1 || KV_MODE == 4) ? HD + 16 : HD + 8; - static constexpr int NG = KV_MODE == 4 ? HD / QK4_0 : 4; // scale groups per row (q4_0: 8 of 32, else 4 of 64) - __half qh[16][QS]; - __half ql[16][QS]; - KElem k[CH][KROW]; - VElem v[CH][VROW]; - float ks[CH][NG]; - float vs[CH][NG]; - float s[16][CH + 1]; - float qmax[THREADS / 32]; - float alpha[16]; - float lsum[16]; - float mrow[16]; - long long row[CH]; -}; - -template -__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, - int page_size, float scale_log2, float* __restrict__ attn, - int cap) { - extern __shared__ __align__(16) unsigned char smem_raw[]; - Smem& S = *reinterpret_cast*>(smem_raw); - const int qi = blockIdx.x, kvh = blockIdx.y; - const int n_head = n_kv_heads * G; - q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; - attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; - 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; - - // q: 12 heads + 4 zero rows, scaled by a power of two that puts its largest value near 2^14 (exact, and the - // lo halves stay out of FP16's subnormal range), then split into hi + lo halves - float qm = 0.0f; - for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i])); -#pragma unroll - for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o)); - if (lane == 0) S.qmax[warp] = qm; - __syncthreads(); - qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3])); - int qe = 0; - if (qm > 0.0f) frexpf(qm, &qe); // qm < 2^qe - const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14); - for (int i = t; i < 16 * HD; i += THREADS) { - const int h = i / HD, d = i % HD; - const float x = h < G ? q[(size_t) h * HD + d] * qup : 0.0f; - const __half hi = __float2half_rn(x); - S.qh[h][d] = hi; - S.ql[h][d] = __float2half_rn(x - __half2float(hi)); - } - if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; } - - float acc[8][4]; -#pragma unroll - for (int j = 0; j < 8; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f; - - for (int c0 = 0; c0 < n; c0 += CH) { - const int nh = min(CH, n - c0); - if (t < CH) { - long long r = -1; - if (t < nh) { - const int cell = ids != nullptr ? ids[c0 + t] : c0 + t; // null ids: the identity (dense) - const long long page = (long long) p.page_table[cell / page_size]; - r = (page * n_kv_heads + kvh) * page_size + (cell % page_size); - } - S.row[t] = r; - } - __syncthreads(); // rows ready; the previous chunk's p.v is done with k, v, s - // gather the chunk's K and V rows (16-byte pieces; K8V4's V as q4_0 blocks dequantized to fp16) - // and their scales - if constexpr (KV_MODE == 4) { - // q4_0 K and V: one (K or V, cell, block) per item - the block's 16 code bytes (2-byte aligned: eight - // 16-bit loads) become 32 exact int8 codes (element j in the low nibble of byte j, j + 16 in the high - // one), its fp16 scale goes to ks/vs - constexpr int BLKS = HD / QK4_0; - constexpr int BYTES = BLKS * (int) sizeof(block_q4_0); - for (int i = t; i < 2 * CH * BLKS; i += THREADS) { - const int kv = i / (CH * BLKS), rem = i % (CH * BLKS), c = rem / BLKS, b = rem % BLKS; - const long long r = S.row[c]; - uint4 lo = make_uint4(0, 0, 0, 0), hi = make_uint4(0, 0, 0, 0); - float d = 0.0f; - if (r >= 0) { - const block_q4_0* blk = reinterpret_cast((kv == 0 ? p.k_q4 : p.v_q4) + r * BYTES) + b; - d = __half2float(__ushort_as_half(__ldg(&blk->d))); - const uint16_t* q16 = reinterpret_cast(blk->qs); - uint32_t w[4]; -#pragma unroll - for (int j = 0; j < 4; ++j) - w[j] = (uint32_t) __ldg(q16 + 2 * j) | ((uint32_t) __ldg(q16 + 2 * j + 1) << 16); - // per byte: the low nibble minus 8 is element j, the high one minus 8 element j + 16 - lo = make_uint4(__vsub4(w[0] & 0x0F0F0F0Fu, 0x08080808u), __vsub4(w[1] & 0x0F0F0F0Fu, 0x08080808u), - __vsub4(w[2] & 0x0F0F0F0Fu, 0x08080808u), __vsub4(w[3] & 0x0F0F0F0Fu, 0x08080808u)); - hi = make_uint4(__vsub4((w[0] >> 4) & 0x0F0F0F0Fu, 0x08080808u), - __vsub4((w[1] >> 4) & 0x0F0F0F0Fu, 0x08080808u), - __vsub4((w[2] >> 4) & 0x0F0F0F0Fu, 0x08080808u), - __vsub4((w[3] >> 4) & 0x0F0F0F0Fu, 0x08080808u)); - } - int8_t* dst = kv == 0 ? &S.k[c][b * QK4_0] : &S.v[c][b * QK4_0]; - reinterpret_cast(dst)[0] = lo; - reinterpret_cast(dst)[1] = hi; - (kv == 0 ? S.ks : S.vs)[c][b] = d; - } - } else { - constexpr int KPIECES = HD * (int) sizeof(typename Smem::KElem) / 16; // per K row - for (int i = t; i < CH * KPIECES; i += THREADS) { - const int c = i / KPIECES, pc = i % KPIECES; - const long long r = S.row[c]; - uint4 kx = make_uint4(0, 0, 0, 0); - if (r >= 0) { - if constexpr (KV_MODE == 0) - kx = __ldg(reinterpret_cast(p.k_pool + r * HD) + pc); - else // modes 1 and 3: the K side is INT8 - kx = __ldg(reinterpret_cast(p.k_q + r * HD) + pc); - } - *reinterpret_cast(reinterpret_cast(&S.k[c][0]) + pc * 16) = kx; - } - if constexpr (KV_MODE == 3) { // V: dequantize the row's q4_0 blocks straight into the fp16 V row - constexpr int BLKS = HD / QK4_0; - constexpr int BYTES = BLKS * (int) sizeof(block_q4_0); - for (int i = t; i < CH * BLKS; i += THREADS) { - const int c = i / BLKS, b = i % BLKS; - const long long r = S.row[c]; -#pragma unroll - for (int j = 0; j < QK4_0; ++j) S.v[c][b * QK4_0 + j] = __half(0); - if (r >= 0) { - const block_q4_0* blk = reinterpret_cast(p.v_q4 + r * BYTES) + b; - const float d = __half2float(__ushort_as_half(blk->d)); -#pragma unroll - for (int j = 0; j < QK4_0 / 2; ++j) { - S.v[c][b * QK4_0 + j] = __float2half_rn((float) ((int)(blk->qs[j] & 0x0F) - 8) * d); - S.v[c][b * QK4_0 + j + QK4_0 / 2] = - __float2half_rn((float) ((int)(blk->qs[j] >> 4) - 8) * d); - } - } - } - } else { - constexpr int VPIECES = HD * (int) sizeof(typename Smem::VElem) / 16; // per V row - for (int i = t; i < CH * VPIECES; i += THREADS) { - const int c = i / VPIECES, pc = i % VPIECES; - const long long r = S.row[c]; - uint4 vx = make_uint4(0, 0, 0, 0); - if (r >= 0) { - if constexpr (KV_MODE == 1) - vx = __ldg(reinterpret_cast(p.v_q + r * HD) + pc); - else - vx = __ldg(reinterpret_cast(p.v_pool + r * HD) + pc); - } - *reinterpret_cast(reinterpret_cast(&S.v[c][0]) + pc * 16) = vx; - } - } - for (int i = t; i < CH * 4; i += THREADS) { - const int c = i / 4, g = i % 4; - const long long r = S.row[c]; - float a = 0.0f, b = 0.0f; - if (r >= 0) { - if constexpr (KV_MODE == 1) { - a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g])); - b = __half2float(__ushort_as_half(p.v_scale[r * (HD / KV_Q8_GROUP) + g])); - } else if constexpr (KV_MODE == 3) { // K as int8, V dequantized to fp16 (scale 1) - a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g])); - b = 1.0f; - } else { - a = b = 1.0f; - } - } - S.ks[c][g] = a; - S.vs[c][g] = b; - } - } - __syncthreads(); - // scores: warp w takes cells 8w..8w+7 (one n-tile) over all 256 dims, per scale group (64 dims; q4_0's 32) - constexpr int NG = Smem::NG, KPG = HD / 16 / NG; // groups per row, 16-dim MMA steps per group -#pragma unroll - for (int nt = 0; nt < CH / 32; ++nt) { - const int cb = (warp + 4 * nt) * 8; - float sc[4] = {0.f, 0.f, 0.f, 0.f}; -#pragma unroll - for (int g = 0; g < NG; ++g) { - float tg[4] = {0.f, 0.f, 0.f, 0.f}; -#pragma unroll - for (int kk = 0; kk < KPG; ++kk) { - const int k0 = (g * KPG + kk) * 16; - uint32_t ah[4], al[4], b[2]; - ah[0] = *reinterpret_cast(&S.qh[gid][k0 + 2 * tig]); - ah[1] = *reinterpret_cast(&S.qh[gid + 8][k0 + 2 * tig]); - ah[2] = *reinterpret_cast(&S.qh[gid][k0 + 2 * tig + 8]); - ah[3] = *reinterpret_cast(&S.qh[gid + 8][k0 + 2 * tig + 8]); - al[0] = *reinterpret_cast(&S.ql[gid][k0 + 2 * tig]); - al[1] = *reinterpret_cast(&S.ql[gid + 8][k0 + 2 * tig]); - al[2] = *reinterpret_cast(&S.ql[gid][k0 + 2 * tig + 8]); - al[3] = *reinterpret_cast(&S.ql[gid + 8][k0 + 2 * tig + 8]); - if constexpr (KV_MODE != 0) { // modes 1 and 3: the K side is INT8 codes - b[0] = i8x2_to_h2(*reinterpret_cast(&S.k[cb + gid][k0 + 2 * tig])); - b[1] = i8x2_to_h2(*reinterpret_cast(&S.k[cb + gid][k0 + 2 * tig + 8])); - } else { - b[0] = *reinterpret_cast(&S.k[cb + gid][k0 + 2 * tig]); - b[1] = *reinterpret_cast(&S.k[cb + gid][k0 + 2 * tig + 8]); - } - mma16816(tg, ah, b); -#ifndef D1_NO_QLO - mma16816(tg, al, b); -#endif - } - const float s0 = S.ks[cb + 2 * tig][g], s1 = S.ks[cb + 2 * tig + 1][g]; - sc[0] = fmaf(tg[0], s0, sc[0]); - sc[1] = fmaf(tg[1], s1, sc[1]); - sc[2] = fmaf(tg[2], s0, sc[2]); - sc[3] = fmaf(tg[3], s1, sc[3]); - } - const int c = cb + 2 * tig; - S.s[gid][c] = c < nh ? sc[0] * qdown : -INFINITY; - S.s[gid][c + 1] = c + 1 < nh ? sc[1] * qdown : -INFINITY; - S.s[gid + 8][c] = c < nh ? sc[2] * qdown : -INFINITY; - S.s[gid + 8][c + 1] = c + 1 < nh ? sc[3] * qdown : -INFINITY; - } - __syncthreads(); - // online softmax: row t/8, 4 cells per thread, 8 threads per row (lanes 8r..8r+7 of a warp) - { - constexpr int PER = CH / 8; - const int r = t >> 3, sub = t & 7; - float x[PER], mx = -INFINITY; -#pragma unroll - for (int j = 0; j < PER; ++j) { x[j] = S.s[r][sub * PER + j]; mx = fmaxf(mx, x[j]); } -#pragma unroll - for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o)); - const float m_old = S.mrow[r]; - const float m_new = fmaxf(m_old, mx); - float sum = 0.0f; -#pragma unroll - for (int j = 0; j < PER; ++j) { - const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new); - S.s[r][sub * PER + j] = e; - sum += e; - } -#pragma unroll - for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); - __syncwarp(); - if (sub == 0) { - const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new); - S.alpha[r] = a; - S.lsum[r] = fmaf(S.lsum[r], a, sum); - S.mrow[r] = m_new; - } - } - __syncthreads(); - // p.v: warp w owns dims [64w, 64w+64), which is int8 scale group w (q4_0: groups 2w and 2w+1, four n-tiles - // each). A group's scale is folded into p relative to the chunk's largest magnitude (q4_0's scales are signed: - // ggml's d = max / -8), times 2^14 (|p'| <= 2^14: inside FP16's range, its lo half out of the subnormals); the - // chunk's sum is then added to the running one in FP32 with the factor taken back out - { - constexpr int GPW = NG / 4, JPG = 8 / GPW; // scale groups per warp, n-tiles per group - float vdown_g[GPW]; - float tmp[8][4]; -#pragma unroll - for (int j = 0; j < 8; ++j) tmp[j][0] = tmp[j][1] = tmp[j][2] = tmp[j][3] = 0.0f; -#pragma unroll - for (int gi = 0; gi < GPW; ++gi) { - const int vg = warp * GPW + gi; - float vmax = 0.0f; -#pragma unroll - for (int c = lane; c < CH; c += 32) vmax = fmaxf(vmax, fabsf(S.vs[c][vg])); -#pragma unroll - for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o)); - const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f; - vdown_g[gi] = vmax * (1.0f / 16384.0f); -#pragma unroll - for (int ks = 0; ks < CH / 16; ++ks) { - const int cA = ks * 16 + 2 * tig, cB = cA + 8; - const float w0 = S.vs[cA][vg] * vup, w1 = S.vs[cA + 1][vg] * vup, w2 = S.vs[cB][vg] * vup, - w3 = S.vs[cB + 1][vg] * vup; - const float p00 = S.s[gid][cA] * w0, p01 = S.s[gid][cA + 1] * w1; - const float p10 = S.s[gid + 8][cA] * w0, p11 = S.s[gid + 8][cA + 1] * w1; - const float p02 = S.s[gid][cB] * w2, p03 = S.s[gid][cB + 1] * w3; - const float p12 = S.s[gid + 8][cB] * w2, p13 = S.s[gid + 8][cB + 1] * w3; - uint32_t ah[4], al[4]; - ah[0] = pack_h2(p00, p01); - ah[1] = pack_h2(p10, p11); - ah[2] = pack_h2(p02, p03); - ah[3] = pack_h2(p12, p13); - { - const __half2* h = reinterpret_cast(ah); - float2 f; - f = __half22float2(h[0]); al[0] = pack_h2(p00 - f.x, p01 - f.y); - f = __half22float2(h[1]); al[1] = pack_h2(p10 - f.x, p11 - f.y); - f = __half22float2(h[2]); al[2] = pack_h2(p02 - f.x, p03 - f.y); - f = __half22float2(h[3]); al[3] = pack_h2(p12 - f.x, p13 - f.y); - } -#pragma unroll - for (int jj = 0; jj < JPG; ++jj) { - const int j = gi * JPG + jj; - const int d = warp * 64 + j * 8 + gid; - uint32_t b[2]; - if constexpr (KV_MODE == 1 || KV_MODE == 4) { - const uint32_t x0 = (uint8_t) S.v[cA][d] | ((uint32_t) (uint8_t) S.v[cA + 1][d] << 8); - const uint32_t x1 = (uint8_t) S.v[cB][d] | ((uint32_t) (uint8_t) S.v[cB + 1][d] << 8); - b[0] = i8x2_to_h2(x0); - b[1] = i8x2_to_h2(x1); - } else { - const __half2 h0 = __halves2half2(S.v[cA][d], S.v[cA + 1][d]); - const __half2 h1 = __halves2half2(S.v[cB][d], S.v[cB + 1][d]); - b[0] = *reinterpret_cast(&h0); - b[1] = *reinterpret_cast(&h1); - } - mma16816(tmp[j], ah, b); -#ifndef D1_NO_PLO - mma16816(tmp[j], al, b); -#endif - } - } - } - const float a0 = S.alpha[gid], a1 = S.alpha[gid + 8]; -#pragma unroll - for (int j = 0; j < 8; ++j) { - const float vdown = vdown_g[j / JPG]; - acc[j][0] = fmaf(acc[j][0], a0, tmp[j][0] * vdown); - acc[j][1] = fmaf(acc[j][1], a0, tmp[j][1] * vdown); - acc[j][2] = fmaf(acc[j][2], a1, tmp[j][2] * vdown); - acc[j][3] = fmaf(acc[j][3], a1, tmp[j][3] * vdown); - } - } - } - __syncthreads(); - const float l0 = S.lsum[gid], l1 = S.lsum[gid + 8]; - const float i0 = l0 > 0.0f ? 1.0f / l0 : 0.0f, i1 = l1 > 0.0f ? 1.0f / l1 : 0.0f; -#pragma unroll - for (int j = 0; j < 8; ++j) { - const int d = warp * 64 + j * 8 + 2 * tig; - if (gid < G) // G < 8 (the fixtures' 4 / 2): rows past G belong to the next KV head's output - *reinterpret_cast(attn + (size_t) gid * HD + d) = make_float2(acc[j][0] * i0, acc[j][1] * i0); - if (gid + 8 < G) - *reinterpret_cast(attn + (size_t) (gid + 8) * HD + d) = make_float2(acc[j][2] * i1, acc[j][3] * i1); - } -} - -// ---- v2 (int8 KV): warp w owns dims [64w, 64w+64) for both q.k and p.v, which is also int8 scale group w. So a -// warp needs only its own 64-byte slice of each K and V row: it gathers it itself with cp.async into its own -// double-buffered stage while it computes the previous chunk, and q stays in registers. Only the q.k partial sums -// (one per dim group) cross warps, and they are added in a fixed order: the result is deterministic. -constexpr int CH2 = 32; - -struct Smem2 { - int8_t kv[2][4][2][CH2][64]; // stage, warp, K/V, cell, 64 dims in 16-byte pieces XOR-swizzled by the cell - float sc[2][4][2][CH2]; // stage, warp, K/V scale of the cell for the warp's group - float part[4][16][CH2 + 1]; // q.k per dim group - float p[16][CH2 + 1]; - float qmax[4]; - float alpha[16]; - float lsum[16]; - float mrow[16]; -}; - -__device__ __forceinline__ int swz(int cell, int byte) { // byte offset of (cell, byte) in a stage slice - return cell * 64 + ((((byte >> 4) ^ (cell >> 1)) & 3) << 4) + (byte & 15); -} -__device__ __forceinline__ void cp_async16(void* smem, const void* gmem, bool valid) { -#if !STRATA_PA_SM80 - __trap(); -#else - const unsigned sa = (unsigned) __cvta_generic_to_shared(smem); - asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" ::"r"(sa), "l"(gmem), "r"(valid ? 16 : 0)); -#endif -} -__device__ __forceinline__ void cp_async_commit() { -#if STRATA_PA_SM80 - asm volatile("cp.async.commit_group;\n" ::); -#endif -} -__device__ __forceinline__ void cp_async_wait1() { -#if STRATA_PA_SM80 - asm volatile("cp.async.wait_group 1;\n" ::); -#endif -} - -template -__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, - int page_size, float scale_log2, - float* __restrict__ attn, int cap) { - extern __shared__ __align__(16) unsigned char smem_raw[]; - Smem2& S = *reinterpret_cast(smem_raw); - const int qi = blockIdx.x, kvh = blockIdx.y; - const int n_head = n_kv_heads * G; - q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; - attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; - 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; - const int dim0 = warp * 64; - - // q: the power-of-two prescale over all 12 heads (as v1), then this warp's 64 dims as hi/lo A fragments - float qm = 0.0f; - for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i])); -#pragma unroll - for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o)); - if (lane == 0) S.qmax[warp] = qm; - if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; } - __syncthreads(); - qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3])); - int qe = 0; - if (qm > 0.0f) frexpf(qm, &qe); - const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14); - uint32_t qh[4][4], ql[4][4]; -#pragma unroll - for (int kk = 0; kk < 4; ++kk) { -#pragma unroll - for (int r = 0; r < 4; ++r) { - const int row = gid + (r & 1) * 8, col = dim0 + kk * 16 + 2 * tig + (r >> 1) * 8; - float2 x = make_float2(0.f, 0.f); - if (row < G) x = *reinterpret_cast(q + (size_t) row * HD + col); - x.x *= qup; - x.y *= qup; - const __half2 hi = __floats2half2_rn(x.x, x.y); - const float2 hf = __half22float2(hi); - const __half2 lo = __floats2half2_rn(x.x - hf.x, x.y - hf.y); - qh[kk][r] = *reinterpret_cast(&hi); - ql[kk][r] = *reinterpret_cast(&lo); - } - } - - // the chunk pipeline: cells two chunks ahead, their pool rows one chunk ahead, the data (cp.async) one ahead - const int n_chunks = (n + CH2 - 1) / CH2; - auto cell_of = [&](int c) -> int { return c < n ? (ids != nullptr ? __ldg(ids + c) : c) : -1; }; // null ids: identity - auto row_of = [&](int cell) -> long long { - if (cell < 0) return -1; - const long long page = (long long) __ldg(p.page_table + cell / page_size); - return (page * n_kv_heads + kvh) * page_size + (cell % page_size); - }; - auto issue = [&](long long r, int st, float& ksr, float& vsr) { -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int idx = lane + 32 * j, cell = idx >> 2, pc = idx & 3; - const long long rr = __shfl_sync(0xffffffffu, r, cell); - const bool ok = rr >= 0; - const size_t off = ok ? (size_t) rr * HD + dim0 + pc * 16 : 0; - cp_async16(&S.kv[st][warp][0][0][0] + swz(cell, pc * 16), p.k_q + off, ok); - cp_async16(&S.kv[st][warp][1][0][0] + swz(cell, pc * 16), p.v_q + off, ok); - } - ksr = r >= 0 ? __half2float(__ushort_as_half(__ldg(p.k_scale + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f; - vsr = r >= 0 ? __half2float(__ushort_as_half(__ldg(p.v_scale + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f; - }; - float ksn, vsn; - issue(row_of(cell_of(lane)), 0, ksn, vsn); - cp_async_commit(); - S.sc[0][warp][0][lane] = ksn; - S.sc[0][warp][1][lane] = vsn; - long long r_next = row_of(cell_of(CH2 + lane)); - int cell_next2 = cell_of(2 * CH2 + lane); - - float acc[8][4]; -#pragma unroll - for (int j = 0; j < 8; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f; - - for (int ci = 0; ci < n_chunks; ++ci) { - const int st = ci & 1, c0 = ci * CH2; - const bool more = ci + 1 < n_chunks; - if (more) issue(r_next, st ^ 1, ksn, vsn); - cp_async_commit(); - r_next = row_of(cell_next2); - cell_next2 = cell_of((ci + 3) * CH2 + lane); - cp_async_wait1(); - __syncwarp(); - const int8_t* K = &S.kv[st][warp][0][0][0]; - const int8_t* V = &S.kv[st][warp][1][0][0]; - // q.k over this warp's 64 dims, times the cell's K scale for this group -#pragma unroll - for (int nt = 0; nt < CH2 / 8; ++nt) { - float tg[4] = {0.f, 0.f, 0.f, 0.f}; - const int cell = nt * 8 + gid; -#pragma unroll - for (int kk = 0; kk < 4; ++kk) { - uint32_t b[2]; - b[0] = i8x2_to_h2(*reinterpret_cast(K + swz(cell, kk * 16 + 2 * tig))); - b[1] = i8x2_to_h2(*reinterpret_cast(K + swz(cell, kk * 16 + 2 * tig + 8))); - mma16816(tg, qh[kk], b); - mma16816(tg, ql[kk], b); - } - const int c = nt * 8 + 2 * tig; - const float s0 = S.sc[st][warp][0][c], s1 = S.sc[st][warp][0][c + 1]; - S.part[warp][gid][c] = tg[0] * s0; - S.part[warp][gid][c + 1] = tg[1] * s1; - S.part[warp][gid + 8][c] = tg[2] * s0; - S.part[warp][gid + 8][c + 1] = tg[3] * s1; - } - __syncthreads(); - // online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread - { - const int r = t >> 3, sub = t & 7; - float x[4], mx = -INFINITY; -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int c = sub * 4 + j; - x[j] = c0 + c < n ? (((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c]) * qdown - : -INFINITY; - mx = fmaxf(mx, x[j]); - } -#pragma unroll - for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o)); - const float m_old = S.mrow[r]; - const float m_new = fmaxf(m_old, mx); - float sum = 0.0f; -#pragma unroll - for (int j = 0; j < 4; ++j) { - const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new); - S.p[r][sub * 4 + j] = e; - sum += e; - } -#pragma unroll - for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); - __syncwarp(); - if (sub == 0) { - const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new); - S.alpha[r] = a; - S.lsum[r] = fmaf(S.lsum[r], a, sum); - S.mrow[r] = m_new; - } - } - __syncthreads(); - // p.v over this warp's 64 dims (as v1) - { - float vmax = S.sc[st][warp][1][lane]; -#pragma unroll - for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o)); - const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f); - float tmp[8][4]; -#pragma unroll - for (int j = 0; j < 8; ++j) tmp[j][0] = tmp[j][1] = tmp[j][2] = tmp[j][3] = 0.0f; -#pragma unroll - for (int ks = 0; ks < CH2 / 16; ++ks) { - const int cA = ks * 16 + 2 * tig, cB = cA + 8; - const float w0 = S.sc[st][warp][1][cA] * vup, w1 = S.sc[st][warp][1][cA + 1] * vup, - w2 = S.sc[st][warp][1][cB] * vup, w3 = S.sc[st][warp][1][cB + 1] * vup; - const float p00 = S.p[gid][cA] * w0, p01 = S.p[gid][cA + 1] * w1; - const float p10 = S.p[gid + 8][cA] * w0, p11 = S.p[gid + 8][cA + 1] * w1; - const float p02 = S.p[gid][cB] * w2, p03 = S.p[gid][cB + 1] * w3; - const float p12 = S.p[gid + 8][cB] * w2, p13 = S.p[gid + 8][cB + 1] * w3; - uint32_t ah[4], al[4]; - ah[0] = pack_h2(p00, p01); - ah[1] = pack_h2(p10, p11); - ah[2] = pack_h2(p02, p03); - ah[3] = pack_h2(p12, p13); - { - const __half2* h = reinterpret_cast(ah); - float2 f; - f = __half22float2(h[0]); al[0] = pack_h2(p00 - f.x, p01 - f.y); - f = __half22float2(h[1]); al[1] = pack_h2(p10 - f.x, p11 - f.y); - f = __half22float2(h[2]); al[2] = pack_h2(p02 - f.x, p03 - f.y); - f = __half22float2(h[3]); al[3] = pack_h2(p12 - f.x, p13 - f.y); - } -#pragma unroll - for (int j = 0; j < 8; ++j) { - const int d = j * 8 + gid; - const uint32_t x0 = (uint8_t) V[swz(cA, d)] | ((uint32_t) (uint8_t) V[swz(cA + 1, d)] << 8); - const uint32_t x1 = (uint8_t) V[swz(cB, d)] | ((uint32_t) (uint8_t) V[swz(cB + 1, d)] << 8); - uint32_t b[2]; - b[0] = i8x2_to_h2(x0); - b[1] = i8x2_to_h2(x1); - mma16816(tmp[j], ah, b); - mma16816(tmp[j], al, b); - } - } - const float a0 = S.alpha[gid], a1 = S.alpha[gid + 8]; -#pragma unroll - for (int j = 0; j < 8; ++j) { - acc[j][0] = fmaf(acc[j][0], a0, tmp[j][0] * vdown); - acc[j][1] = fmaf(acc[j][1], a0, tmp[j][1] * vdown); - acc[j][2] = fmaf(acc[j][2], a1, tmp[j][2] * vdown); - acc[j][3] = fmaf(acc[j][3], a1, tmp[j][3] * vdown); - } - } - if (more) { - S.sc[st ^ 1][warp][0][lane] = ksn; - S.sc[st ^ 1][warp][1][lane] = vsn; - } - __syncwarp(); - } - __syncthreads(); - const float l0 = S.lsum[gid], l1 = S.lsum[gid + 8]; - const float i0 = l0 > 0.0f ? 1.0f / l0 : 0.0f, i1 = l1 > 0.0f ? 1.0f / l1 : 0.0f; -#pragma unroll - for (int j = 0; j < 8; ++j) { - const int d = dim0 + j * 8 + 2 * tig; - if (gid < G) // G < 8 (the fixtures' 4 / 2): rows past G belong to the next KV head's output - *reinterpret_cast(attn + (size_t) gid * HD + d) = make_float2(acc[j][0] * i0, acc[j][1] * i0); - if (gid + 8 < G) - *reinterpret_cast(attn + (size_t) (gid + 8) * HD + d) = make_float2(acc[j][2] * i1, acc[j][3] * i1); - } -} - -template -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) - int dev = 0; - cudaGetDevice(&dev); - const int bytes = (int) sizeof(Smem2); - if (dev < 0 || dev >= 64) return false; - if (!attr[dev]) { - if (cudaFuncSetAttribute(prompt_attn_i8_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) != - cudaSuccess) { - cudaGetLastError(); - return false; - } - attr[dev] = true; - } - const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD); - for (int64_t q0 = 0; q0 < n_q; q0 += 65535) { - const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535; - prompt_attn_i8_kernel<<>>( - 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(); - if (e != cudaSuccess) { - std::fprintf(stderr, "qsa_prompt_attn_batch: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - return true; -} - -template -bool launch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, - const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) { - static bool attr[64] = {}; // per device, as above - int dev = 0; - cudaGetDevice(&dev); - const int bytes = (int) sizeof(Smem); - if (dev < 0 || dev >= 64) return false; - if (!attr[dev]) { - if (cudaFuncSetAttribute(prompt_attn_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) != - cudaSuccess) { - cudaGetLastError(); - return false; - } - attr[dev] = true; - } - const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD); - for (int64_t q0 = 0; q0 < n_q; q0 += 65535) { - const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535; - prompt_attn_kernel<<>>( - 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(); - if (e != cudaSuccess) { - std::fprintf(stderr, "qsa_prompt_attn_batch: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - return true; -} - - -// PR #600: compiled only into the experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON), the one build that runs on a -// Volta card; the ready-made engine has none of it (no extra kernels to load, the same code as before). -#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) -// ---- sm_70 (Volta): v1's structure on mma.m8n8k4 ------------------------------------------------------------------ -// Volta's tensor cores only have m8n8k4 (FP16 in, FP32 accumulate): per warp FOUR independent 8x8x4 products, one per -// quad-pair (QP q = lanes 4q..4q+3 and 4q+16..4q+19; thread j = (lane & 3) + 4 * (lane >> 4) within it). Layout, measured on -// a V100 (tools-free microtest, and equal to turbomind's SM70_MMA_884): the thread holds row j of A (k 0..3 as two -// registers) and column j of B (k 0..3); C register i is row (lane & 1) + 4 * (lane >> 4) + 2 * ((i >> 1) & 1), -// column (lane & 2) + 4 * (i >> 2) + (i & 1) of its QP's 8x8 tile. -// q.k: warp w owns dims [64w, 64w+64) = int8 scale group w; QP q takes cells 8q..8q+7 of the 32-cell chunk; 16 k-steps -// of 4 dims, two 8-row blocks (12 heads + 4 zero rows), q as hi + lo halves. The warp's partial (times the -// cells' K scale) goes to S.part[w]; the softmax adds the four groups in a fixed order (deterministic). -// p.v: warp w owns dims [64w, 64w+64) again; QP q takes the 16 dims 64w+16q.. (two n-tiles of 8); k = the 32 cells in -// steps of 4; p carries the V scale (as v1) and is split into hi + lo halves. -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 && __CUDA_ARCH__ < 750 -#define STRATA_PA_VOLTA 1 -#else -#define STRATA_PA_VOLTA 0 -#endif - -__device__ __forceinline__ void mma884(float* c, uint32_t a0, uint32_t a1, uint32_t b0, uint32_t b1) { -#if STRATA_PA_VOLTA - asm volatile("mma.sync.aligned.m8n8k4.row.col.f32.f16.f16.f32 {%0,%1,%2,%3,%4,%5,%6,%7}, {%8,%9}, {%10,%11}, " - "{%0,%1,%2,%3,%4,%5,%6,%7};\n" - : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]), "+f"(c[4]), "+f"(c[5]), "+f"(c[6]), "+f"(c[7]) - : "r"(a0), "r"(a1), "r"(b0), "r"(b1)); -#else - __trap(); // m8n8k4 is a Volta instruction; the host only launches this kernel on sm_70 -#endif -} - -template -struct Smem70 { - using KElem = typename std::conditional::type; - using VElem = typename std::conditional::type; - static constexpr int KROW = KV_MODE == 0 ? HD + 8 : HD + 16; - static constexpr int VROW = KV_MODE == 1 ? HD + 16 : HD + 8; - __half qh[16][QS]; - __half ql[16][QS]; - KElem k[CH][KROW]; - VElem v[CH][VROW]; - float ks[CH][4]; - float vs[CH][4]; - float part[4][16][CH + 4]; // q.k per dim group (scaled by the cell's K scale) - float s[16][CH + 4]; // the chunk's probabilities - float qmax[THREADS / 32]; - float alpha[16]; - float lsum[16]; - float mrow[16]; - long long row[CH]; -}; - -template -__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, - int page_size, float scale_log2, - float* __restrict__ attn, int cap) { - extern __shared__ __align__(16) unsigned char smem_raw[]; - Smem70& S = *reinterpret_cast*>(smem_raw); - const int qi = blockIdx.x, kvh = blockIdx.y; - const int n_head = n_kv_heads * G; - q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; - attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; - 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 - const int crow = (lane & 1) + 4 * (lane >> 4); // C row of register 0 (+2 per register pair) - const int ccol = lane & 2; // C column of register 0 (+4 per half, +1 per reg) - - // q: 12 heads + 4 zero rows, scaled by a power of two that puts its largest value near 2^14 (exact, and the - // lo halves stay out of FP16's subnormal range), then split into hi + lo halves - float qm = 0.0f; - for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i])); -#pragma unroll - for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o)); - if (lane == 0) S.qmax[warp] = qm; - __syncthreads(); - qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3])); - int qe = 0; - if (qm > 0.0f) frexpf(qm, &qe); // qm < 2^qe - const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14); - for (int i = t; i < 16 * HD; i += THREADS) { - const int h = i / HD, d = i % HD; - const float x = h < G ? q[(size_t) h * HD + d] * qup : 0.0f; - const __half hi = __float2half_rn(x); - S.qh[h][d] = hi; - S.ql[h][d] = __float2half_rn(x - __half2float(hi)); - } - if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; } - - float acc[2][2][8]; -#pragma unroll - for (int rb = 0; rb < 2; ++rb) -#pragma unroll - for (int nt = 0; nt < 2; ++nt) -#pragma unroll - for (int i = 0; i < 8; ++i) acc[rb][nt][i] = 0.0f; - - for (int c0 = 0; c0 < n; c0 += CH) { - const int nh = min(CH, n - c0); - if (t < CH) { - long long r = -1; - if (t < nh) { - const int cell = ids != nullptr ? ids[c0 + t] : c0 + t; // null ids: the identity (dense) - const long long page = (long long) p.page_table[cell / page_size]; - r = (page * n_kv_heads + kvh) * page_size + (cell % page_size); - } - S.row[t] = r; - } - __syncthreads(); // rows ready; the previous chunk's p.v is done with k, v, s - // gather the chunk's K and V rows (16-byte pieces; K8V4's V as q4_0 blocks dequantized to fp16) - // and their scales - { - constexpr int KPIECES = HD * (int) sizeof(typename Smem::KElem) / 16; // per K row - for (int i = t; i < CH * KPIECES; i += THREADS) { - const int c = i / KPIECES, pc = i % KPIECES; - const long long r = S.row[c]; - uint4 kx = make_uint4(0, 0, 0, 0); - if (r >= 0) { - if constexpr (KV_MODE == 0) - kx = __ldg(reinterpret_cast(p.k_pool + r * HD) + pc); - else // modes 1 and 3: the K side is INT8 - kx = __ldg(reinterpret_cast(p.k_q + r * HD) + pc); - } - *reinterpret_cast(reinterpret_cast(&S.k[c][0]) + pc * 16) = kx; - } - if constexpr (KV_MODE == 3) { // V: dequantize the row's q4_0 blocks straight into the fp16 V row - constexpr int BLKS = HD / QK4_0; - constexpr int BYTES = BLKS * (int) sizeof(block_q4_0); - for (int i = t; i < CH * BLKS; i += THREADS) { - const int c = i / BLKS, b = i % BLKS; - const long long r = S.row[c]; -#pragma unroll - for (int j = 0; j < QK4_0; ++j) S.v[c][b * QK4_0 + j] = __half(0); - if (r >= 0) { - const block_q4_0* blk = reinterpret_cast(p.v_q4 + r * BYTES) + b; - const float d = __half2float(__ushort_as_half(blk->d)); -#pragma unroll - for (int j = 0; j < QK4_0 / 2; ++j) { - S.v[c][b * QK4_0 + j] = __float2half_rn((float) ((int)(blk->qs[j] & 0x0F) - 8) * d); - S.v[c][b * QK4_0 + j + QK4_0 / 2] = - __float2half_rn((float) ((int)(blk->qs[j] >> 4) - 8) * d); - } - } - } - } else { - constexpr int VPIECES = HD * (int) sizeof(typename Smem::VElem) / 16; // per V row - for (int i = t; i < CH * VPIECES; i += THREADS) { - const int c = i / VPIECES, pc = i % VPIECES; - const long long r = S.row[c]; - uint4 vx = make_uint4(0, 0, 0, 0); - if (r >= 0) { - if constexpr (KV_MODE == 1) - vx = __ldg(reinterpret_cast(p.v_q + r * HD) + pc); - else - vx = __ldg(reinterpret_cast(p.v_pool + r * HD) + pc); - } - *reinterpret_cast(reinterpret_cast(&S.v[c][0]) + pc * 16) = vx; - } - } - for (int i = t; i < CH * 4; i += THREADS) { - const int c = i / 4, g = i % 4; - const long long r = S.row[c]; - float a = 0.0f, b = 0.0f; - if (r >= 0) { - if constexpr (KV_MODE == 1) { - a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g])); - b = __half2float(__ushort_as_half(p.v_scale[r * (HD / KV_Q8_GROUP) + g])); - } else if constexpr (KV_MODE == 3) { // K as int8, V dequantized to fp16 (scale 1) - a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g])); - b = 1.0f; - } else { - a = b = 1.0f; - } - } - S.ks[c][g] = a; - S.vs[c][g] = b; - } - } - __syncthreads(); - // scores: warp w = dim group w (64 dims), QP q = cells 8q..8q+7 - { - float tg[2][8]; -#pragma unroll - for (int rb = 0; rb < 2; ++rb) -#pragma unroll - for (int i = 0; i < 8; ++i) tg[rb][i] = 0.0f; - const int cell_b = qp * 8 + jj; -#pragma unroll - for (int ks = 0; ks < 16; ++ks) { - const int d0 = warp * 64 + ks * 4; - uint32_t b0, b1; - if constexpr (KV_MODE != 0) { // modes 1 and 3: the K side is INT8 codes, exact in FP16 - const uint32_t raw = *reinterpret_cast(&S.k[cell_b][d0]); - b0 = i8x2_to_h2(raw & 0xffffu); - b1 = i8x2_to_h2(raw >> 16); - } else { - const uint2 raw = *reinterpret_cast(&S.k[cell_b][d0]); - b0 = raw.x; - b1 = raw.y; - } -#pragma unroll - for (int rb = 0; rb < 2; ++rb) { - const uint2 ah = *reinterpret_cast(&S.qh[rb * 8 + jj][d0]); - const uint2 al = *reinterpret_cast(&S.ql[rb * 8 + jj][d0]); - mma884(tg[rb], ah.x, ah.y, b0, b1); - mma884(tg[rb], al.x, al.y, b0, b1); - } - } -#pragma unroll - for (int rb = 0; rb < 2; ++rb) -#pragma unroll - for (int i = 0; i < 8; ++i) { - const int row = rb * 8 + crow + 2 * ((i >> 1) & 1); - const int cell = qp * 8 + ccol + 4 * (i >> 2) + (i & 1); - S.part[warp][row][cell] = tg[rb][i] * S.ks[cell][warp]; - } - } - __syncthreads(); - // online softmax: row t/8, 4 cells per thread, 8 threads per row (lanes 8r..8r+7 of a warp) - { - constexpr int PER = CH / 8; - const int r = t >> 3, sub = t & 7; - float x[PER], mx = -INFINITY; -#pragma unroll - for (int j = 0; j < PER; ++j) { - const int c = sub * PER + j; - const float sum4 = ((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c]; - x[j] = c < nh ? sum4 * qdown : -INFINITY; - mx = fmaxf(mx, x[j]); - } -#pragma unroll - for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o)); - const float m_old = S.mrow[r]; - const float m_new = fmaxf(m_old, mx); - float sum = 0.0f; -#pragma unroll - for (int j = 0; j < PER; ++j) { - const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new); - S.s[r][sub * PER + j] = e; - sum += e; - } -#pragma unroll - for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); - __syncwarp(); - if (sub == 0) { - const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new); - S.alpha[r] = a; - S.lsum[r] = fmaf(S.lsum[r], a, sum); - S.mrow[r] = m_new; - } - } - __syncthreads(); - __syncthreads(); - // p.v: warp w owns dims [64w, 64w+64) (int8 scale group w), QP q its 16 dims 64w+16q..; the V scale is folded - // into p relative to the chunk's largest, times 2^14 (as v1) - { - float vmax = 0.0f; -#pragma unroll - for (int c = lane; c < CH; c += 32) vmax = fmaxf(vmax, S.vs[c][warp]); -#pragma unroll - for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o)); - const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f); - float tmp[2][2][8]; -#pragma unroll - for (int rb = 0; rb < 2; ++rb) -#pragma unroll - for (int nt = 0; nt < 2; ++nt) -#pragma unroll - for (int i = 0; i < 8; ++i) tmp[rb][nt][i] = 0.0f; -#pragma unroll - for (int ks = 0; ks < CH / 4; ++ks) { - const int c0 = ks * 4; - float w[4]; -#pragma unroll - for (int e = 0; e < 4; ++e) w[e] = S.vs[c0 + e][warp] * vup; - uint2 ah[2], al[2]; -#pragma unroll - for (int rb = 0; rb < 2; ++rb) { - const float4 pv = *reinterpret_cast(&S.s[rb * 8 + jj][c0]); - const float p0 = pv.x * w[0], p1 = pv.y * w[1], p2 = pv.z * w[2], p3 = pv.w * w[3]; - ah[rb].x = pack_h2(p0, p1); - ah[rb].y = pack_h2(p2, p3); - const float2 f01 = __half22float2(*reinterpret_cast(&ah[rb].x)); - const float2 f23 = __half22float2(*reinterpret_cast(&ah[rb].y)); - al[rb].x = pack_h2(p0 - f01.x, p1 - f01.y); - al[rb].y = pack_h2(p2 - f23.x, p3 - f23.y); - } -#pragma unroll - for (int nt = 0; nt < 2; ++nt) { - const int d = warp * 64 + qp * 16 + nt * 8 + jj; - uint32_t b0, b1; - if constexpr (KV_MODE == 1) { - const uint32_t x0 = (uint8_t) S.v[c0][d] | ((uint32_t) (uint8_t) S.v[c0 + 1][d] << 8); - const uint32_t x1 = (uint8_t) S.v[c0 + 2][d] | ((uint32_t) (uint8_t) S.v[c0 + 3][d] << 8); - b0 = i8x2_to_h2(x0); - b1 = i8x2_to_h2(x1); - } else { - const __half2 h0 = __halves2half2(S.v[c0][d], S.v[c0 + 1][d]); - const __half2 h1 = __halves2half2(S.v[c0 + 2][d], S.v[c0 + 3][d]); - b0 = *reinterpret_cast(&h0); - b1 = *reinterpret_cast(&h1); - } -#pragma unroll - for (int rb = 0; rb < 2; ++rb) { - mma884(tmp[rb][nt], ah[rb].x, ah[rb].y, b0, b1); - mma884(tmp[rb][nt], al[rb].x, al[rb].y, b0, b1); - } - } - } -#pragma unroll - for (int rb = 0; rb < 2; ++rb) { - float a_[2]; - a_[0] = S.alpha[rb * 8 + crow]; - a_[1] = S.alpha[rb * 8 + crow + 2]; -#pragma unroll - for (int nt = 0; nt < 2; ++nt) -#pragma unroll - for (int i = 0; i < 8; ++i) - acc[rb][nt][i] = fmaf(acc[rb][nt][i], a_[(i >> 1) & 1], tmp[rb][nt][i] * vdown); - } - } - } - __syncthreads(); -#pragma unroll - for (int rb = 0; rb < 2; ++rb) -#pragma unroll - for (int h = 0; h < 2; ++h) { - const int row = rb * 8 + crow + 2 * h; - if (row >= G) continue; - const float l = S.lsum[row]; - const float inv = l > 0.0f ? 1.0f / l : 0.0f; -#pragma unroll - for (int nt = 0; nt < 2; ++nt) -#pragma unroll - for (int hh = 0; hh < 2; ++hh) { - const int i = hh * 4 + h * 2; // registers i, i+1: row h, columns ccol + 4 * hh + {0, 1} - const int d = warp * 64 + qp * 16 + nt * 8 + ccol + 4 * hh; - *reinterpret_cast(attn + (size_t) row * HD + d) = - make_float2(acc[rb][nt][i] * inv, acc[rb][nt][i + 1] * inv); - } - } -} - -template -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] = {}; - int dev = 0; - cudaGetDevice(&dev); - const int bytes = (int) sizeof(Smem70); - if (dev < 0 || dev >= 64) return false; - if (!attr[dev]) { - if (cudaFuncSetAttribute(prompt_attn_v70_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) != - cudaSuccess) { - cudaGetLastError(); - return false; - } - attr[dev] = true; - } - const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD); - for (int64_t q0 = 0; q0 < n_q; q0 += 65535) { - const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535; - prompt_attn_v70_kernel<<>>( - 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(); - if (e != cudaSuccess) { - std::fprintf(stderr, "qsa_prompt_attn_batch (sm_70): %s\n", cudaGetErrorString(e)); - std::exit(1); - } - return true; -} -#else // AMD, or a build without STRATA_EXPERIMENTAL_SM60: no m8n8k4 kernel (the caller keeps the old one) -template -bool launch70(const float*, const QsaAttnPools&, const int32_t*, const int32_t*, int64_t, const QsaShapes&, float*, - int64_t, cudaStream_t) { - return false; -} -#endif // !__HIPCC__ && STRATA_EXPERIMENTAL_SM60 - -#if defined(__HIPCC__) -// ---- S6: the int8-KV prompt attention on RDNA4 matrix cores (opt-in: STRATA_HIP_WMMA=1, gfx12 only). The design of -// the v2 kernel above with gfx12's v_wmma_f32_16x16x16_f16 (wave32) in place of m16n8k16: wave w owns dims -// [64w, 64w+64) (int8 scale group w) for q.k and p.v; q and p are split into FP16 hi + lo parts, the int8 codes enter -// exactly as FP16, the scales are applied in FP32 and the four groups' q.k partials are added in a fixed order. -// FP32-level accuracy, deterministic, but not bitwise equal to qsa_decode_attn_batch (another summation order). -// Fragment layout (16x16x16, wave32, checked on gfx1201): A lane l holds A[l % 16][(l / 16) * 8 + i], B lane l holds -// B[(l / 16) * 8 + i][l % 16], C/D lane l holds D[(l / 16) * 8 + i][l % 16], i = 0..7. -#if defined(__gfx1200__) || defined(__gfx1201__) -#define STRATA_PA_WMMA 1 -#else -#define STRATA_PA_WMMA 0 -#endif -typedef _Float16 wh8 __attribute__((ext_vector_type(8))); -typedef float wf8 __attribute__((ext_vector_type(8))); -constexpr int WCH = 32; // cells per chunk (two 16-cell tiles) -constexpr int WVS = 80; // staged V row stride in bytes (64 codes, 16-byte aligned, banks spread) -struct alignas(16) SmemW { - float part[4][16][WCH + 1]; // q.k per dim group - float p[16][WCH + 1]; - float vs[4][WCH]; // V scale per (group, cell) - int valid[WCH]; // the cell has a resident pool row - uint8_t v[4][WCH][WVS]; // per wave: the chunk's V codes of its group, one row per cell - float qmax[4]; - float alpha[16]; - float lsum[16]; - float mrow[16]; -}; - -__device__ __forceinline__ wf8 wmma_f16(wh8 a, wh8 b, wf8 c) { -#if STRATA_PA_WMMA - return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); -#else - __builtin_trap(); - return c; -#endif -} - -__device__ __forceinline__ wh8 i8x8_to_h8(uint2 x) { // exact: |code| <= 128 - wh8 h; -#pragma unroll - for (int i = 0; i < 4; ++i) { - h[i] = (_Float16) (int) (int8_t) (x.x >> (8 * i)); - h[4 + i] = (_Float16) (int) (int8_t) (x.y >> (8 * i)); - } - return h; -} - -template -__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, - int page_size, float scale_log2, - float* __restrict__ attn, int cap) { -#if STRATA_PA_WMMA - __shared__ SmemW S; - const int qi = blockIdx.x, kvh = blockIdx.y; - const int n_head = n_kv_heads * G; - q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; - attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; - 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 - const int dim0 = warp * 64; - - float qm = 0.0f; - for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i])); -#pragma unroll - for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o)); - if (lane == 0) S.qmax[warp] = qm; - if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; } - __syncthreads(); - qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3])); - int qe = 0; - if (qm > 0.0f) frexpf(qm, &qe); - const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14); - // q A fragments of this wave's 64 dims: row = col (heads 12..15 zero), k = dim0 + kk*16 + half*8 + i - wh8 qh[4], ql[4]; -#pragma unroll - for (int kk = 0; kk < 4; ++kk) { - float x[8]; - if (col < G) { - const float4* src = reinterpret_cast(q + (size_t) col * HD + dim0 + kk * 16 + half * 8); - const float4 a = src[0], b = src[1]; - x[0] = a.x; x[1] = a.y; x[2] = a.z; x[3] = a.w; x[4] = b.x; x[5] = b.y; x[6] = b.z; x[7] = b.w; - } else { -#pragma unroll - for (int i = 0; i < 8; ++i) x[i] = 0.0f; - } -#pragma unroll - for (int i = 0; i < 8; ++i) { - const float v = x[i] * qup; - const _Float16 hi = (_Float16) v; - qh[kk][i] = hi; - ql[kk][i] = (_Float16) (v - (float) hi); - } - } - - wf8 acc[4]; -#pragma unroll - for (int j = 0; j < 4; ++j) acc[j] = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; - - const int n_chunks = (n + WCH - 1) / WCH; - for (int ci = 0; ci < n_chunks; ++ci) { - const int c0 = ci * WCH; - // this lane's cell of the chunk (lane = cell index): its pool row, or -1 (past the selection, or a block the - // KV streaming left non-resident: masked as in the decode kernel) - long long myrow = -1; - if (c0 + lane < n) { - const int cell = ids != nullptr ? __ldg(ids + c0 + lane) : c0 + lane; // null ids: the identity - const 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); - } - // stage this wave's V slice of the chunk (64 bytes of each row) and the V scale; the K fragments come straight - // from global memory (8 consecutive codes per lane) - { - uint4 v0 = make_uint4(0, 0, 0, 0), v1 = v0, v2 = v0, v3 = v0; - float vsc = 0.0f; - if (myrow >= 0) { - const uint4* src = reinterpret_cast(p.v_q + myrow * HD + dim0); - v0 = __ldg(src); v1 = __ldg(src + 1); v2 = __ldg(src + 2); v3 = __ldg(src + 3); - vsc = __half2float(__ushort_as_half(__ldg(p.v_scale + myrow * (HD / KV_Q8_GROUP) + warp))); - } - uint4* dst = reinterpret_cast(&S.v[warp][lane][0]); - dst[0] = v0; dst[1] = v1; dst[2] = v2; dst[3] = v3; - S.vs[warp][lane] = vsc; - if (warp == 0) S.valid[lane] = myrow >= 0; - } - // q.k over this wave's 64 dims for two 16-cell tiles, times the cell's K scale for this group -#pragma unroll - for (int nt = 0; nt < 2; ++nt) { - const long long rr = __shfl(myrow, nt * 16 + col); - wf8 s = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; - float ksc = 0.0f; - if (rr >= 0) ksc = __half2float(__ushort_as_half(__ldg(p.k_scale + rr * (HD / KV_Q8_GROUP) + warp))); -#pragma unroll - for (int kk = 0; kk < 4; ++kk) { - uint2 kx = make_uint2(0, 0); - if (rr >= 0) kx = __ldg(reinterpret_cast(p.k_q + rr * HD + dim0 + kk * 16 + half * 8)); - const wh8 b = i8x8_to_h8(kx); - s = wmma_f16(qh[kk], b, s); - s = wmma_f16(ql[kk], b, s); - } -#pragma unroll - for (int i = 0; i < 8; ++i) S.part[warp][half * 8 + i][nt * 16 + col] = s[i] * ksc; - } - __syncthreads(); - // online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread - { - const int r = t >> 3, sub = t & 7; - float x[4], mx = -INFINITY; -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int c = sub * 4 + j; - // past the selection, or a masked cell (non-resident page, as in the decode kernel): no weight - x[j] = S.valid[c] ? (((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c]) * qdown - : -INFINITY; - mx = fmaxf(mx, x[j]); - } -#pragma unroll - for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o)); - const float m_old = S.mrow[r]; - const float m_new = fmaxf(m_old, mx); - float sum = 0.0f; -#pragma unroll - for (int j = 0; j < 4; ++j) { - const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new); - S.p[r][sub * 4 + j] = e; - sum += e; - } -#pragma unroll - for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); - if (sub == 0) { - const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new); - S.alpha[r] = a; - S.lsum[r] = fmaf(S.lsum[r], a, sum); - S.mrow[r] = m_new; - } - } - __syncthreads(); - // p.v over this wave's 64 dims: 4 tiles of 16 dims, 2 k-steps of 16 cells - { - float vmax = S.vs[warp][lane]; -#pragma unroll - for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o)); - const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f); - wf8 tmp[4]; -#pragma unroll - for (int j = 0; j < 4; ++j) tmp[j] = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; -#pragma unroll - for (int ks = 0; ks < 2; ++ks) { - const int cb = ks * 16 + half * 8; // this lane's 8 cells - wh8 ah, al; -#pragma unroll - for (int i = 0; i < 8; ++i) { - const float pv = S.p[col][cb + i] * (S.vs[warp][cb + i] * vup); - const _Float16 hi = (_Float16) pv; - ah[i] = hi; - al[i] = (_Float16) (pv - (float) hi); - } -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int d = j * 16 + col; - wh8 b; -#pragma unroll - for (int i = 0; i < 8; ++i) b[i] = (_Float16) (int) (int8_t) S.v[warp][cb + i][d]; - tmp[j] = wmma_f16(ah, b, tmp[j]); - tmp[j] = wmma_f16(al, b, tmp[j]); - } - } - float a[8]; -#pragma unroll - for (int i = 0; i < 8; ++i) a[i] = S.alpha[half * 8 + i]; -#pragma unroll - for (int j = 0; j < 4; ++j) -#pragma unroll - for (int i = 0; i < 8; ++i) acc[j][i] = fmaf(acc[j][i], a[i], tmp[j][i] * vdown); - } - // no barrier here: `v`/`vs` are this wave's own, and `p`/`alpha`/`valid` are rewritten only after the next - // chunk's first barrier (which every wave reaches after its p.v) - } - float inv[8]; -#pragma unroll - for (int i = 0; i < 8; ++i) { - const float l = S.lsum[half * 8 + i]; - inv[i] = l > 0.0f ? 1.0f / l : 0.0f; - } -#pragma unroll - for (int j = 0; j < 4; ++j) -#pragma unroll - for (int i = 0; i < 8; ++i) { - const int row = half * 8 + i; - if (row < G) attn[(size_t) row * HD + dim0 + j * 16 + col] = acc[j][i] * inv[i]; - } -#else - __builtin_trap(); -#endif -} - -// gfx12 (RDNA4) only, and only on request: the output differs from the default kernel's in its last bits -bool hip_wmma_usable() { - static const bool want = [] { - const char* e = std::getenv("STRATA_HIP_WMMA"); - return e != nullptr && e[0] == '1'; - }(); - if (!want) return false; - static int arch[64] = {}; // 0 unknown, 1 gfx12, 2 other - int dev = 0; - if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= 64) { (void) hipGetLastError(); return false; } - if (arch[dev] == 0) { - hipDeviceProp_t prop{}; - if (hipGetDeviceProperties(&prop, dev) != hipSuccess) { (void) hipGetLastError(); return false; } - arch[dev] = std::strncmp(prop.gcnArchName, "gfx12", 5) == 0 ? 1 : 2; - static bool told = false; - if (!told) { - told = true; - std::fprintf(stderr, "strata: STRATA_HIP_WMMA: the prompt attention on matrix cores %s (%s)\n", - arch[dev] == 1 ? "on" : "unavailable", prop.gcnArchName); - } - } - return arch[dev] == 1; -} - -template -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<<>>( - 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(); - if (e != cudaSuccess) { - std::fprintf(stderr, "qsa_prompt_attn_batch (wmma): %s\n", cudaGetErrorString(e)); - std::exit(1); - } - return true; -} -#endif - -template -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(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(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, - int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, void* stream) { - if (n_q <= 0) return true; - bool volta = false, turing = false; // per call, from the CURRENT device (a layer split can mix Turing with newer cards) - { // sm_75 or newer: the MMA above compiles for both. sm_80+ runs the cp.async kernel (launch_i8); Turing has - // no cp.async, so it runs the v1 kernel (launch<1>, same accuracy, another summation order). An older card - // keeps the old kernel. - // #371: the compute capability with its minor - sm_70 (V100) has no m16n8k8 (the kernels trap below sm_75) -#if defined(STRATA_HIP_GFX906) - return false; // gfx906: the tensor-core and WMMA kernels are not for it; the FP32 kernel runs -#endif - static int cc[64] = {}; - int dev = 0; - if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } - if (cc[dev] == 0) { - int major = 0, minor = 0; - if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess || - cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) { - cudaGetLastError(); - return false; - } - // STRATA_QSA_WARP=1|attn (an A/B arm): the pre-sm_80 kernels on any card, as RTX 20 runs them - const char* w = std::getenv("STRATA_QSA_WARP"); - cc[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "attn")) ? 75 - : 10 * strata::cc_major_of(major) + strata::cc_minor_of(minor); - } - if (cc[dev] < 70) return false; - volta = cc[dev] < 75; // sm_70: the m8n8k4 kernel (STRATA_PA_VOLTA); STRATA_QSA_WARP=1 still forces the old one - turing = cc[dev] < 80; - } - // Qwen3.6: the query heads per KV head from the geometry (2, 8, 12); any other ratio falls back to the decode - // kernel, which refuses it by name. - char why[256]; - const int G = qsa_attn_group(s, why, sizeof why); - if (G == 12) return dispatch<12>(q, pools, ids, steps, cap, s, attn, n_q, stream, volta, turing); - if (G == 8) return dispatch<8>(q, pools, ids, steps, cap, s, attn, n_q, stream, volta, turing); - if (G == 2) return dispatch<2>(q, pools, ids, steps, cap, s, attn, n_q, stream, volta, turing); - return false; -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cu deleted file mode 100644 index 56222c5..0000000 --- a/src/kernels/cuda/qsa_select.cu +++ /dev/null @@ -1,1237 +0,0 @@ -// src/kernels/cuda/qsa_select.cu - see include/strata/kernels/qsa_select.hpp. -#include "strata/core/emulate.hpp" -#include -#include -#include "strata/kernels/qsa_select.hpp" - -#include - -#include -#include -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int IDX_DIM = 128, IDX_HEADS = 4, R = 4; -constexpr int SCORE_WARPS = 8; -constexpr int TOPK_T = 256; - -__device__ __forceinline__ uint32_t order_key(float s) { - const float v = s + 0.0f; - if (!(v == v)) return 0u; - const uint32_t b = __float_as_uint(v); - return (b & 0x80000000u) ? ~b : (b | 0x80000000u); -} - -__global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_kernel(const float* __restrict__ pooled, - const float* __restrict__ dead, - const float* __restrict__ q_idx, - const int32_t* __restrict__ steps, - int64_t max_blocks, float* __restrict__ out) { - const int64_t qi = blockIdx.y; - const int32_t* st = steps + qi * kStepCount; - const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid]; - const int64_t b = (int64_t) blockIdx.x * SCORE_WARPS + (threadIdx.x >> 5); - if (b > n_bid || b >= max_blocks) return; - const int lane = threadIdx.x & 31; - const float* key = (b == n_bid) ? dead : pooled + b * IDX_DIM; - const float4 k4 = *reinterpret_cast(key + lane * 4); - const float* q = q_idx + qi * IDX_HEADS * IDX_DIM + lane * 4; - float score = 0.0f; -#pragma unroll - for (int h = 0; h < IDX_HEADS; ++h) { - const float4 q4 = *reinterpret_cast(q + h * IDX_DIM); - float d = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w; -#pragma unroll - for (int o = 16; o > 0; o >>= 1) d += __shfl_xor_sync(0xffffffffu, d, o); - score += d > 0.0f ? d : 0.0f; - } - if (lane == 0) { - if (b == n_bid && n_kv % R != 0) score += 1e9f; - out[qi * max_blocks + b] = score; - } -} - -__global__ void __launch_bounds__(TOPK_T) block_topk_kernel(const float* __restrict__ scores, - const int32_t* __restrict__ steps, int64_t max_blocks, - int64_t cap, int32_t* __restrict__ ids) { - __shared__ int hist[256]; - __shared__ int s_a[TOPK_T], s_b[TOPK_T]; - __shared__ int s_digit, s_above; - const int64_t qi = blockIdx.x; - const int32_t* st = steps + qi * kStepCount; - const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth]; - int32_t* out = ids + qi * cap; - const int t = threadIdx.x; - if (n_kv <= width) { // everything is selected: the identity, ascending - for (int64_t j = t; j < n_kv; j += TOPK_T) out[j] = (int32_t) j; - return; - } - const float* sc = scores + qi * max_blocks; - const int64_t nb = n_bid + 1; // blocks 0..n_bid, the last possibly empty - const int64_t per = (nb + TOPK_T - 1) / TOPK_T; - const int64_t b0 = (int64_t) t * per, b1 = (b0 + per < nb) ? b0 + per : nb; - auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); }; - // ---- radix select: the largest key thr with (cells with key >= thr) >= width, 8 bits at a time - uint32_t prefix = 0; - int above = 0; // cells strictly above the digits fixed so far - for (int shift = 24; shift >= 0; shift -= 8) { - for (int i = t; i < 256; i += TOPK_T) hist[i] = 0; - __syncthreads(); - const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8)); - for (int64_t b = b0; b < b1; ++b) { - const int w = weight(b); - if (w == 0) continue; - const uint32_t k = order_key(sc[b]); - if ((k & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[(k >> shift) & 255], w); - } - __syncthreads(); - if (t == 0) { - int cum = above, d = 255; - for (; d > 0; --d) { - if (cum + hist[d] >= width) break; - cum += hist[d]; - } - s_digit = d; - s_above = cum; - } - __syncthreads(); - prefix |= (uint32_t) s_digit << shift; - above = s_above; - __syncthreads(); - } - const uint32_t thr = prefix; - const int64_t eq_budget = width - above; // cells equal to thr that fit, lowest index first - // ---- per-thread counts of cells above and at the threshold, then their exclusive prefixes - int gt = 0, eq = 0; - for (int64_t b = b0; b < b1; ++b) { - const int w = weight(b); - if (w == 0) continue; - const uint32_t k = order_key(sc[b]); - if (k > thr) gt += w; - else if (k == thr) eq += w; - } - s_a[t] = gt; - s_b[t] = eq; - __syncthreads(); - if (t == 0) { - int ag = 0, ae = 0; - for (int i = 0; i < TOPK_T; ++i) { - const int g = s_a[i], e = s_b[i]; - s_a[i] = ag; s_b[i] = ae; - ag += g; ae += e; - } - } - __syncthreads(); - const int64_t eq_before = s_b[t]; - int64_t my_eq = eq_budget - eq_before; - if (my_eq < 0) my_eq = 0; - if (my_eq > eq) my_eq = eq; - const int sel = gt + (int) my_eq; - __syncthreads(); - s_a[t] = sel; - __syncthreads(); - if (t == 0) { - int a = 0; - for (int i = 0; i < TOPK_T; ++i) { const int c = s_a[i]; s_a[i] = a; a += c; } - } - __syncthreads(); - int64_t wpos = s_a[t]; - int64_t eq_left = my_eq; - for (int64_t b = b0; b < b1; ++b) { - const int w = weight(b); - if (w == 0) continue; - const uint32_t k = order_key(sc[b]); - if (k > thr) { - for (int c = 0; c < w; ++c) out[wpos++] = (int32_t) (b * R + c); - } else if (k == thr) { - for (int c = 0; c < w && eq_left > 0; ++c, --eq_left) out[wpos++] = (int32_t) (b * R + c); - } - } -} - - -// ---- QSA select on tensor cores (perf-review, after D-1): the block scores of many queries are one GEMM, -// rows (query, indexer head) x columns (blocks), K = 128, with relu per head summed. 3xTF32 (each operand split -// into a TF32 hi and lo part, hi*hi + hi*lo + lo*hi) keeps FP32-level accuracy; the summation order differs from -// the warp kernel, so a score can move in its last bits and a near-tie can select differently (not bitwise). -// Blocks < n_bid only; the tail block n_bid (the `dead` key, +1e9) is scored by the warp kernel's own code. -constexpr int TC_QT = 16; // queries per CTA (one m16 tile per indexer head) -constexpr int TC_NB = 32; // blocks per tile (4 warps x n8) -constexpr int TC_ITER = 4; // tiles per CTA (the query tile is loaded once) -constexpr int TC_QS = IDX_HEADS * IDX_DIM + 4; // query row stride in floats -constexpr int TC_KS = IDX_DIM + 4; // key row stride - -// TF32 conversion and MMA need sm_80: below it they compile to a trap and qsa_block_scores_tc refuses the device -#if defined(__HIPCC__) // AMD: no mma.sync / cp.async; the host keeps the warp kernel (below) -#define STRATA_SEL_SM80 0 -#elif !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 -#define STRATA_SEL_SM80 1 -#else -#define STRATA_SEL_SM80 0 -#endif -__device__ __forceinline__ uint32_t tf32_hi(float x) { -#if STRATA_SEL_SM80 - uint32_t r; - asm("cvt.rna.tf32.f32 %0, %1;" : "=r"(r) : "f"(x)); - return r; -#else - return __float_as_uint(x); -#endif -} -__device__ __forceinline__ void mma_tf32(float* c, const uint32_t* a, const uint32_t* b) { -#if !STRATA_SEL_SM80 - __trap(); -#else - asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, " - "{%0,%1,%2,%3};\n" - : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) - : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1])); -#endif -} - -__global__ void __launch_bounds__(128) block_scores_tc_kernel(const float* __restrict__ pooled, - const float* __restrict__ q_idx, - const int32_t* __restrict__ steps, int64_t nq, - int64_t max_blocks, int64_t reach, - float* __restrict__ out) { - extern __shared__ __align__(16) float sm[]; - float* sQ = sm; // [TC_QT][TC_QS] - float* sK = sm + TC_QT * TC_QS; // [TC_NB][TC_KS] - __shared__ int s_nbid[TC_QT]; - const int t = threadIdx.x, lane = t & 31, warp = t >> 5, gid = lane >> 2, tig = lane & 3; - const int64_t q0 = (int64_t) blockIdx.y * TC_QT; - for (int i = t; i < TC_QT * IDX_HEADS * IDX_DIM / 4; i += 128) { - const int r = i / (IDX_HEADS * IDX_DIM / 4), c = i % (IDX_HEADS * IDX_DIM / 4); - float4 v = make_float4(0.f, 0.f, 0.f, 0.f); - if (q0 + r < nq) v = reinterpret_cast(q_idx + (q0 + r) * IDX_HEADS * IDX_DIM)[c]; - *reinterpret_cast(sQ + r * TC_QS + c * 4) = v; - } - if (t < TC_QT) s_nbid[t] = q0 + t < nq ? steps[(q0 + t) * kStepCount + kStepNBid] : 0; - int lo_nbid = 0x7fffffff, hi_nbid = 0; - __syncthreads(); - for (int i = 0; i < TC_QT; ++i) { - if (q0 + i >= nq) break; - lo_nbid = min(lo_nbid, s_nbid[i]); - hi_nbid = max(hi_nbid, s_nbid[i]); - } - for (int it = 0; it < TC_ITER; ++it) { - const int64_t b0 = ((int64_t) blockIdx.x * TC_ITER + it) * TC_NB; - if (b0 >= reach || b0 >= hi_nbid) break; // blocks >= every query's n_bid: nothing to score - __syncthreads(); // the previous tile's reads are done - for (int i = t; i < TC_NB * IDX_DIM / 4; i += 128) { - const int r = i / (IDX_DIM / 4), c = i % (IDX_DIM / 4); - float4 v = make_float4(0.f, 0.f, 0.f, 0.f); - if (b0 + r < hi_nbid) v = reinterpret_cast(pooled + (b0 + r) * IDX_DIM)[c]; - *reinterpret_cast(sK + r * TC_KS + c * 4) = v; - } - __syncthreads(); - float acc[IDX_HEADS][4]; -#pragma unroll - for (int h = 0; h < IDX_HEADS; ++h) acc[h][0] = acc[h][1] = acc[h][2] = acc[h][3] = 0.f; - const float* kr = sK + (warp * 8 + gid) * TC_KS; -#pragma unroll 4 - for (int k0 = 0; k0 < IDX_DIM; k0 += 8) { - const float kx0 = kr[k0 + tig], kx1 = kr[k0 + tig + 4]; - uint32_t bh[2], bl[2]; - bh[0] = tf32_hi(kx0); - bh[1] = tf32_hi(kx1); - bl[0] = tf32_hi(kx0 - __uint_as_float(bh[0])); - bl[1] = tf32_hi(kx1 - __uint_as_float(bh[1])); -#pragma unroll - for (int h = 0; h < IDX_HEADS; ++h) { - const float* qa = sQ + h * IDX_DIM + k0 + tig; - const float x0 = qa[gid * TC_QS], x1 = qa[(gid + 8) * TC_QS]; - const float x2 = qa[gid * TC_QS + 4], x3 = qa[(gid + 8) * TC_QS + 4]; - uint32_t ah[4], al[4]; - ah[0] = tf32_hi(x0); ah[1] = tf32_hi(x1); ah[2] = tf32_hi(x2); ah[3] = tf32_hi(x3); - al[0] = tf32_hi(x0 - __uint_as_float(ah[0])); - al[1] = tf32_hi(x1 - __uint_as_float(ah[1])); - al[2] = tf32_hi(x2 - __uint_as_float(ah[2])); - al[3] = tf32_hi(x3 - __uint_as_float(ah[3])); - mma_tf32(acc[h], al, bh); - mma_tf32(acc[h], ah, bl); - mma_tf32(acc[h], ah, bh); - } - } - // relu per head, heads added in order (as the warp kernel), written where the block completed for the query - const int64_t bc = b0 + warp * 8 + 2 * tig; -#pragma unroll - for (int half = 0; half < 2; ++half) { - const int qr = gid + half * 8; - const int64_t qi = q0 + qr; - if (qi >= nq) continue; - const int nb = s_nbid[qr]; -#pragma unroll - for (int j = 0; j < 2; ++j) { - const int64_t b = bc + j; - if (b >= nb || b >= max_blocks) continue; - float score = 0.0f; -#pragma unroll - for (int h = 0; h < IDX_HEADS; ++h) { - const float d = acc[h][half * 2 + j]; - score += d > 0.0f ? d : 0.0f; - } - out[qi * max_blocks + b] = score; - } - } - } -} - -#if defined(__HIPCC__) -// ---- gfx12 (RDNA4: gfx1200 / gfx1201) scorer on v_wmma_f32_16x16x16_bf16 (wave32). Same GEMM as above: for a tile of 16 -// queries, every block's score is sum over the 4 indexer heads of relu(q_h . k), K = 128. FP32-level accuracy from a -// three-way bf16 split of both operands (x = hi + mid + lo EXACTLY - the top 8, next 8 and last 8 bits of the fp32 -// mantissa, so bf16's fp32-sized exponent range needs no scaling) and the six products of order <= 2, smallest first; -// like the TF32 kernel it sums in another order than the warp kernel (not bitwise). The tail block n_bid is the warp -// kernel's arithmetic (block_scores_tail_kernel). -// D = A x B with A = 16 key blocks (row l%16 of a lane, k = 8*(l/16)+i), B = 16 queries (column l%16, same k): -// a lane ends up with 8 consecutive blocks of ONE query, written as one run. No LDS for keys: a lane reads its -// 32-byte slice of the key row from global (the 16 query tiles of a launch re-read them from L2); the queries are -// split once per CTA into LDS. -#if defined(__gfx1200__) || defined(__gfx1201__) -#define STRATA_SEL_GFX12 1 -#else -#define STRATA_SEL_GFX12 0 -#endif -typedef short sel_s8 __attribute__((ext_vector_type(8))); -typedef float sel_f8 __attribute__((ext_vector_type(8))); -typedef uint32_t sel_u4 __attribute__((ext_vector_type(4))); -constexpr int WQT = 16; // queries per CTA (the N of one WMMA) -constexpr int WITER = 4; // key tiles per warp (the CTA covers 4 warps * WITER * 16 blocks) -constexpr int WQS = IDX_DIM + 8; // bf16 elements per LDS row: 272 bytes, conflict-free 16-byte reads - -__device__ __forceinline__ sel_f8 wmma_bf16(const sel_s8& a, const sel_s8& b, const sel_f8& c) { -#if STRATA_SEL_GFX12 - return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c); -#else - __trap(); - return c; -#endif -} -// the bf16 pieces of x as fp32 bit patterns whose upper 16 bits are the bf16 (lower 16 are zero) -__device__ __forceinline__ void split3(float x, uint32_t& hi, uint32_t& mid, uint32_t& lo) { - hi = __float_as_uint(x) & 0xffff0000u; - const float r1 = x - __uint_as_float(hi); // exact - mid = __float_as_uint(r1) & 0xffff0000u; - lo = __float_as_uint(r1 - __uint_as_float(mid)) & 0xffff0000u; // exact: at most 8 significant bits left -} -__device__ __forceinline__ uint32_t pack_bf16x2(uint32_t a, uint32_t b) { // low half = a's bf16, high half = b's -#if STRATA_SEL_GFX12 - return __builtin_amdgcn_perm(b, a, 0x07060302u); -#else - return (a >> 16) | (b & 0xffff0000u); -#endif -} - -__global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __restrict__ pooled, - const float* __restrict__ q_idx, - const int32_t* __restrict__ steps, int64_t nq, - int64_t max_blocks, int64_t reach, - float* __restrict__ out) { - __shared__ __align__(16) uint16_t sq[3][IDX_HEADS][WQT][WQS]; // hi / mid / lo, [head][query][dim] - __shared__ int s_nbid[WQT]; - const int t = threadIdx.x, lane = t & 31, warp = t >> 5, l16 = lane & 15, g = lane >> 4; - const int64_t q0 = (int64_t) blockIdx.y * WQT; - for (int i = t; i < WQT * IDX_HEADS * IDX_DIM / 4; i += 128) { - const int row = i / (IDX_DIM / 4), c = i % (IDX_DIM / 4); - const int qr = row / IDX_HEADS, h = row % IDX_HEADS; - float4 v = make_float4(0.f, 0.f, 0.f, 0.f); - if (q0 + qr < nq) v = reinterpret_cast(q_idx + (q0 + qr) * IDX_HEADS * IDX_DIM)[h * (IDX_DIM / 4) + c]; - const float x[4] = {v.x, v.y, v.z, v.w}; - uint32_t hb[4], mb[4], lb[4]; -#pragma unroll - for (int j = 0; j < 4; ++j) split3(x[j], hb[j], mb[j], lb[j]); - *reinterpret_cast(&sq[0][h][qr][c * 4]) = make_uint2(pack_bf16x2(hb[0], hb[1]), pack_bf16x2(hb[2], hb[3])); - *reinterpret_cast(&sq[1][h][qr][c * 4]) = make_uint2(pack_bf16x2(mb[0], mb[1]), pack_bf16x2(mb[2], mb[3])); - *reinterpret_cast(&sq[2][h][qr][c * 4]) = make_uint2(pack_bf16x2(lb[0], lb[1]), pack_bf16x2(lb[2], lb[3])); - } - if (t < WQT) s_nbid[t] = q0 + t < nq ? steps[(q0 + t) * kStepCount + kStepNBid] : 0; - __syncthreads(); - int hi_nbid = 0; -#pragma unroll - for (int i = 0; i < WQT; ++i) hi_nbid = max(hi_nbid, s_nbid[i]); - const int64_t qi = q0 + l16; - const int nb_q = s_nbid[l16]; - for (int it = 0; it < WITER; ++it) { - const int64_t b0 = (((int64_t) blockIdx.x * WITER + it) * 4 + warp) * 16; - if (b0 >= reach || b0 >= hi_nbid) break; // warp-uniform; later tiles start higher - const int64_t row = b0 + l16; - const bool rv = row < hi_nbid && row < max_blocks; - const float* kp = pooled + (rv ? row : 0) * IDX_DIM + g * 8; - // acc: the hi*hi products; cor: the five smaller ones (<= 2^-8 of it). Kept apart and added once at the end: a - // correction summed into the big accumulator is rounded to ITS ulp at every one of the 48 steps (measured: 8e-7 - // of the score scale; apart, near the warp kernel's) - sel_f8 acc[IDX_HEADS], cor[IDX_HEADS]; -#pragma unroll - for (int h = 0; h < IDX_HEADS; ++h) acc[h] = cor[h] = sel_f8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; -#pragma unroll 2 - for (int kk = 0; kk < IDX_DIM / 16; ++kk) { - float4 k0 = make_float4(0.f, 0.f, 0.f, 0.f), k1 = k0; - if (rv) { - k0 = *reinterpret_cast(kp + kk * 16); - k1 = *reinterpret_cast(kp + kk * 16 + 4); - } - const float x[8] = {k0.x, k0.y, k0.z, k0.w, k1.x, k1.y, k1.z, k1.w}; - uint32_t hb[8], mb[8], lb[8]; -#pragma unroll - for (int j = 0; j < 8; ++j) split3(x[j], hb[j], mb[j], lb[j]); - sel_u4 ah, am, al; -#pragma unroll - for (int j = 0; j < 4; ++j) { - ah[j] = pack_bf16x2(hb[2 * j], hb[2 * j + 1]); - am[j] = pack_bf16x2(mb[2 * j], mb[2 * j + 1]); - al[j] = pack_bf16x2(lb[2 * j], lb[2 * j + 1]); - } - const sel_s8 Ah = __builtin_bit_cast(sel_s8, ah), Am = __builtin_bit_cast(sel_s8, am), - Al = __builtin_bit_cast(sel_s8, al); -#pragma unroll - for (int h = 0; h < IDX_HEADS; ++h) { - const sel_s8 Bh = *reinterpret_cast(&sq[0][h][l16][kk * 16 + g * 8]); - const sel_s8 Bm = *reinterpret_cast(&sq[1][h][l16][kk * 16 + g * 8]); - const sel_s8 Bl = *reinterpret_cast(&sq[2][h][l16][kk * 16 + g * 8]); - cor[h] = wmma_bf16(Al, Bh, cor[h]); - cor[h] = wmma_bf16(Ah, Bl, cor[h]); - cor[h] = wmma_bf16(Am, Bm, cor[h]); - cor[h] = wmma_bf16(Ah, Bm, cor[h]); - cor[h] = wmma_bf16(Am, Bh, cor[h]); - acc[h] = wmma_bf16(Ah, Bh, acc[h]); - } - } - // relu per head, heads added in order (as the warp kernel); this lane: query qi, blocks b0 + 8g .. 8g+7 - if (qi < nq) { -#pragma unroll - for (int i = 0; i < 8; ++i) { - const int64_t b = b0 + g * 8 + i; - if (b >= nb_q || b >= max_blocks) continue; - float score = 0.0f; -#pragma unroll - for (int h = 0; h < IDX_HEADS; ++h) { - const float d = acc[h][i] + cor[h][i]; - score += d > 0.0f ? d : 0.0f; - } - out[qi * max_blocks + b] = score; - } - } - } -} - -// the gfx12 kernel needs gfx1200/gfx1201 code objects and a gfx12 device (gfx1100 has WMMA too, with another layout) -bool sel_gfx12_device() { - static int ok[64] = {}; // per device: 0 unknown, 1 yes, 2 no - int dev = 0; - if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } - if (ok[dev] == 0) { - cudaDeviceProp prop; - ok[dev] = (cudaGetDeviceProperties(&prop, dev) == cudaSuccess && - (std::strncmp(prop.gcnArchName, "gfx1200", 7) == 0 || std::strncmp(prop.gcnArchName, "gfx1201", 7) == 0)) - ? 1 : 2; - cudaGetLastError(); - } - return ok[dev] == 1; -} -#endif // __HIPCC__ - -// the tail block n_bid of each query: exactly block_scores_kernel's arithmetic for that block -__global__ void __launch_bounds__(32) block_scores_tail_kernel(const float* __restrict__ dead, - const float* __restrict__ q_idx, - const int32_t* __restrict__ steps, - int64_t max_blocks, float* __restrict__ out) { - const int64_t qi = blockIdx.x; - const int32_t* st = steps + qi * kStepCount; - const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid]; - if (n_bid >= max_blocks) return; - const int lane = threadIdx.x & 31; - const float4 k4 = *reinterpret_cast(dead + lane * 4); - const float* q = q_idx + qi * IDX_HEADS * IDX_DIM + lane * 4; - float score = 0.0f; -#pragma unroll - for (int h = 0; h < IDX_HEADS; ++h) { - const float4 q4 = *reinterpret_cast(q + h * IDX_DIM); - float d = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w; -#pragma unroll - for (int o = 16; o > 0; o >>= 1) d += __shfl_xor_sync(0xffffffffu, d, o); - score += d > 0.0f ? d : 0.0f; - } - if (lane == 0) { - if (n_kv % R != 0) score += 1e9f; - out[qi * max_blocks + n_bid] = score; - } -} - -// ---- the same top-k with each query's keys read once: 1,024 threads hold up to TK_PER consecutive blocks' keys in -// registers (contexts up to 4 * 1024 * TK_PER cells), per-warp histograms, block-wide scans. The selection rule is -// block_topk_kernel's (radix threshold, ties to the lowest index, cells ascending): identical ids. -constexpr int TK_T = 1024; -constexpr int TK_PER = 33; -#if defined(__HIPCC__) -// AMD (RDNA, wave32): a 1,024-thread block may use 192 VGPRs per lane, so the keys of 66 blocks per thread fit - contexts -// up to 4 * 1024 * 66 = 270,336 cells (the 262,144 --max-context) keep the register kernel. NVIDIA's 64 registers per -// thread at 1,024 threads allow only TK_PER. -constexpr int TK_PER_MAX = 66; -#else -constexpr int TK_PER_MAX = TK_PER; -#endif - -__device__ __forceinline__ int block_excl_scan(int v, int* s_warp, int& total) { - const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; - int x = v; -#pragma unroll - for (int o = 1; o < 32; o <<= 1) { - const int y = __shfl_up_sync(0xffffffffu, x, o); - if (lane >= o) x += y; - } - if (lane == 31) s_warp[warp] = x; - __syncthreads(); - if (warp == 0) { - int w = s_warp[lane]; - int z = w; -#pragma unroll - for (int o = 1; o < 32; o <<= 1) { - const int y = __shfl_up_sync(0xffffffffu, z, o); - if (lane >= o) z += y; - } - s_warp[lane] = z - w; // exclusive per warp - if (lane == 31) s_warp[32] = z; // total - } - __syncthreads(); - const int r = s_warp[warp] + x - v; - total = s_warp[32]; - __syncthreads(); - return r; -} - -template -__global__ void __launch_bounds__(TK_T) block_topk_reg_kernel(const float* __restrict__ scores, - const int32_t* __restrict__ steps, int64_t max_blocks, - int64_t cap, int32_t* __restrict__ ids) { - __shared__ int hist[TK_T / 32][256]; - __shared__ int s_warp[33]; - __shared__ int s_digit, s_above; - const int64_t qi = blockIdx.x; - const int32_t* st = steps + qi * kStepCount; - const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth]; - int32_t* out = ids + qi * cap; - const int t = threadIdx.x, lane = t & 31, warp = t >> 5; - if (n_kv <= width) { - for (int64_t j = t; j < n_kv; j += TK_T) out[j] = (int32_t) j; - return; - } - const float* sc = scores + qi * max_blocks; - const int64_t nb = n_bid + 1; - const int64_t per = (nb + TK_T - 1) / TK_T; // <= PER (the caller checks) - const int64_t b0 = (int64_t) t * per, b1 = (b0 + per < nb) ? b0 + per : nb; - uint32_t key[PER]; -#pragma unroll - for (int j = 0; j < PER; ++j) key[j] = (b0 + j < b1) ? order_key(sc[b0 + j]) : 0u; - auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); }; - uint32_t prefix = 0; - int above = 0; - for (int shift = 24; shift >= 0; shift -= 8) { - for (int i = lane; i < 256; i += 32) hist[warp][i] = 0; - __syncwarp(); - const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8)); -#pragma unroll - for (int j = 0; j < PER; ++j) { - const int64_t b = b0 + j; - if (b >= b1) break; - const int w = weight(b); - if (w == 0) continue; - if ((key[j] & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[warp][(key[j] >> shift) & 255], w); - } - __syncthreads(); - if (t < 256) { // fold the warps' histograms into warp 0's - int s = 0; - for (int w2 = 0; w2 < TK_T / 32; ++w2) s += hist[w2][t]; - hist[0][t] = s; - } - __syncthreads(); - if (t == 0) { - int cum = above, d = 255; - for (; d > 0; --d) { - if (cum + hist[0][d] >= width) break; - cum += hist[0][d]; - } - s_digit = d; - s_above = cum; - } - __syncthreads(); - prefix |= (uint32_t) s_digit << shift; - above = s_above; - __syncthreads(); - } - const uint32_t thr = prefix; - const int64_t eq_budget = width - above; - int gt = 0, eq = 0; -#pragma unroll - for (int j = 0; j < PER; ++j) { - const int64_t b = b0 + j; - if (b >= b1) break; - const int w = weight(b); - if (w == 0) continue; - if (key[j] > thr) gt += w; - else if (key[j] == thr) eq += w; - } - int tot; - const int eq_before = block_excl_scan(eq, s_warp, tot); - int64_t my_eq = eq_budget - eq_before; - if (my_eq < 0) my_eq = 0; - if (my_eq > eq) my_eq = eq; - const int sel = gt + (int) my_eq; - int64_t wpos = block_excl_scan(sel, s_warp, tot); - int64_t eq_left = my_eq; -#pragma unroll - for (int j = 0; j < PER; ++j) { - const int64_t b = b0 + j; - if (b >= b1) break; - const int w = weight(b); - if (w == 0) continue; - if (key[j] > thr) { - for (int c = 0; c < w; ++c) out[wpos++] = (int32_t) (b * R + c); - } else if (key[j] == thr) { - for (int c = 0; c < w && eq_left > 0; ++c, --eq_left) out[wpos++] = (int32_t) (b * R + c); - } - } -} - -#if !defined(__HIPCC__) -// ---- a query with more blocks than the register kernel holds (contexts past 4 * 1024 * TK_PER cells): the register -// kernel's threads, per-warp histograms and warp scans, with each key read from memory again on every pass. A -// histogram has no order, so on the four radix passes thread t reads blocks t, t + 1024, ...: a warp reads 32 -// neighbours at a time. The cells are emitted ascending in the order (warp, row, lane): warp w holds the `per` rows -// of 32 consecutive blocks from block w * 32 * per. block_topk_kernel's selection rule (radix threshold, ties to the -// lowest index): identical ids. -__global__ void __launch_bounds__(TK_T) block_topk_wide_kernel(const float* __restrict__ scores, - const int32_t* __restrict__ steps, int64_t max_blocks, - int64_t cap, int32_t* __restrict__ ids) { - __shared__ int hist[TK_T / 32][256]; - __shared__ int s_gt[TK_T / 32], s_eq[TK_T / 32]; - __shared__ int s_digit, s_above; - const int64_t qi = blockIdx.x; - const int32_t* st = steps + qi * kStepCount; - const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth]; - int32_t* out = ids + qi * cap; - const int t = threadIdx.x, lane = t & 31, warp = t >> 5; - if (n_kv <= width) { - for (int64_t j = t; j < n_kv; j += TK_T) out[j] = (int32_t) j; - return; - } - const float* sc = scores + qi * max_blocks; - const int64_t nb = n_bid + 1; - const int64_t per = (nb + TK_T - 1) / TK_T; // rows of 32 blocks per warp - auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); }; - uint32_t prefix = 0; - int above = 0; - for (int shift = 24; shift >= 0; shift -= 8) { - for (int i = lane; i < 256; i += 32) hist[warp][i] = 0; - __syncwarp(); - const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8)); - for (int64_t b = t; b < nb; b += TK_T) { - const int w = weight(b); - if (w == 0) continue; - const uint32_t k = order_key(sc[b]); - if ((k & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[warp][(k >> shift) & 255], w); - } - __syncthreads(); - if (t < 256) { // fold the warps' histograms into warp 0's - int sum = 0; - for (int w2 = 0; w2 < TK_T / 32; ++w2) sum += hist[w2][t]; - hist[0][t] = sum; - } - __syncthreads(); - if (t == 0) { - int cum = above, d = 255; - for (; d > 0; --d) { - if (cum + hist[0][d] >= width) break; - cum += hist[0][d]; - } - s_digit = d; - s_above = cum; - } - __syncthreads(); - prefix |= (uint32_t) s_digit << shift; - above = s_above; - __syncthreads(); - } - const uint32_t thr = prefix; - const int eq_budget = (int) (width - above); // cells equal to thr that fit, lowest index first - const int64_t w0 = (int64_t) warp * 32 * per; - int gt = 0, eq = 0; - for (int64_t b = w0 + lane; b < nb && b < w0 + 32 * per; b += 32) { - const int w = weight(b); - if (w == 0) continue; - const uint32_t k = order_key(sc[b]); - if (k > thr) gt += w; - else if (k == thr) eq += w; - } -#pragma unroll - for (int o = 16; o > 0; o >>= 1) { - gt += __shfl_xor_sync(0xffffffffu, gt, o); - eq += __shfl_xor_sync(0xffffffffu, eq, o); - } - if (lane == 0) { s_gt[warp] = gt; s_eq[warp] = eq; } - __syncthreads(); - if (t == 0) { // per warp: the selected cells and the tied cells before it - int eb = 0, sb = 0; - for (int w2 = 0; w2 < TK_T / 32; ++w2) { - const int g2 = s_gt[w2], e2 = s_eq[w2]; - const int take = eq_budget - eb < 0 ? 0 : (eq_budget - eb > e2 ? e2 : eq_budget - eb); - s_gt[w2] = sb; - s_eq[w2] = eb; - sb += g2 + take; - eb += e2; - } - } - __syncthreads(); - int run_sel = s_gt[warp], run_eq = s_eq[warp]; - for (int64_t r0 = w0; r0 < nb && r0 < w0 + 32 * per; r0 += 32) { - const int64_t b = r0 + lane; - const int w = b < nb ? weight(b) : 0; - const uint32_t k = w ? order_key(sc[b]) : 0u; - const int my_gt = (w && k > thr) ? w : 0, my_eq = (w && k == thr) ? w : 0; - if (__ballot_sync(0xffffffffu, (my_gt | my_eq) != 0) == 0u) continue; // a row without a selected block - int pe = my_eq; // tied cells up to and with this lane -#pragma unroll - for (int o = 1; o < 32; o <<= 1) { - const int y = __shfl_up_sync(0xffffffffu, pe, o); - if (lane >= o) pe += y; - } - const int left = eq_budget - (run_eq + pe - my_eq); - const int take = left < 0 ? 0 : (left > my_eq ? my_eq : left); - const int my_sel = my_gt + take; - int ps = my_sel; -#pragma unroll - for (int o = 1; o < 32; o <<= 1) { - const int y = __shfl_up_sync(0xffffffffu, ps, o); - if (lane >= o) ps += y; - } - int32_t* dst = out + run_sel + ps - my_sel; - for (int c = 0; c < my_sel; ++c) dst[c] = (int32_t) (b * R + c); - run_eq += __shfl_sync(0xffffffffu, pe, 31); - run_sel += __shfl_sync(0xffffffffu, ps, 31); - } -} -#endif - - -// Block scores with every key block read ONCE for all of a call's queries (block_scores_kernel's grid is -// (max_blocks / 8) x nq: ~24,600 mostly-idle blocks per layer at a decode window, each key re-read per query). A fixed -// grid strides over the blocks; per (block, query) the same arithmetic in the same order as block_scores_kernel. -// qsa_block_scores takes it for every call without an active-block count and at most MQ queries: the captured decode -// window, the uncaptured decode, and prefill's pooled16 call. -constexpr int MQ = 8; -__global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_multi_kernel(const float* __restrict__ pooled, - const float* __restrict__ dead, - const float* __restrict__ q_idx, - const int32_t* __restrict__ steps, int nq, - int64_t max_blocks, float* __restrict__ out) { - __shared__ __align__(16) float qs[MQ * IDX_HEADS * IDX_DIM]; - __shared__ int64_t s_nkv[MQ], s_nbid[MQ]; - for (int i = threadIdx.x; i < nq * IDX_HEADS * IDX_DIM; i += blockDim.x) qs[i] = q_idx[i]; - if (threadIdx.x < nq) { - s_nkv[threadIdx.x] = steps[threadIdx.x * kStepCount + kStepNKv]; - s_nbid[threadIdx.x] = steps[threadIdx.x * kStepCount + kStepNBid]; - } - __syncthreads(); - int64_t top = 0; - for (int q = 0; q < nq; ++q) top = s_nbid[q] > top ? s_nbid[q] : top; - const int lane = threadIdx.x & 31; - const int64_t wstride = (int64_t) gridDim.x * SCORE_WARPS; - for (int64_t b = (int64_t) blockIdx.x * SCORE_WARPS + (threadIdx.x >> 5); b <= top && b < max_blocks; b += wstride) { - const float4 kp = *reinterpret_cast(pooled + b * IDX_DIM + lane * 4); - const float4 kd = *reinterpret_cast(dead + lane * 4); - for (int qi = 0; qi < nq; ++qi) { - const int64_t n_bid = s_nbid[qi]; - if (b > n_bid) continue; - const float4 k4 = (b == n_bid) ? kd : kp; - const float* q = qs + qi * IDX_HEADS * IDX_DIM + lane * 4; - float score = 0.0f; -#pragma unroll - for (int h = 0; h < IDX_HEADS; ++h) { - const float4 q4 = *reinterpret_cast(q + h * IDX_DIM); - float d = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w; -#pragma unroll - for (int o = 16; o > 0; o >>= 1) d += __shfl_xor_sync(0xffffffffu, d, o); - score += d > 0.0f ? d : 0.0f; - } - if (lane == 0) { - if (b == n_bid && s_nkv[qi] % R != 0) score += 1e9f; - out[qi * max_blocks + b] = score; - } - } - } -} - -#if !defined(__HIPCC__) -// ---- the decode top-k on a thread-block cluster (sm_90+; S19). One CTA per query (block_topk_reg_kernel, or -// block_topk_kernel above 33,792 blocks: a --max-context over ~135K) makes four radix passes and two scans over up to -// 65,538 blocks on ONE SM while the rest of the GPU idles - a decode window has 1-5 queries. Here a cluster of CL_N -// CTAs shares a query: CTA r holds the keys of blocks [r * per, (r + 1) * per) in shared memory, builds the digit -// histogram of its keys, and PUSHES it into slot r of every CTA's `hin` (distributed shared memory); after one cluster -// barrier each CTA sums the CL_N slots itself, so all of them take the same digit. The emit pass needs each CTA's -// cells above / at the threshold: pushed the same way, then each CTA offsets its own by the ranks before it. -// RTX 5070, per call at capacity = context (decode_cluster_parity --bench): 21.9 -> 15.6 us at 32K, 58 -> 18 at 128K, -// 200 -> 22 at 262K (the one-CTA kernels' digit search was serial, too: one thread over 256 bins per pass). -// -// IDENTICAL IDS, by construction rather than by luck: the threshold thr (the width-th largest key, cells counted with -// their weights) and `above` (cells with a larger key) are pure functions of the multiset of (key, weight) - integer -// histograms, summed in any order - and the digit rule is block_topk_kernel's, written as a scan (the largest digit d -// whose cells at or above it reach `need`; 0 when none). The cells emitted are then fixed: every cell of a block with -// key > thr, and the first eq_budget = width - above cells at thr in ascending order (a block at thr may be cut), -// written in ascending cell order. Position of a thread's first cell = (cells above thr before it) + min(cells at thr -// before it, eq_budget): the telescoped sum of the reference's per-thread clamp. NaN keys are 0 (order_key) as there. -// -// Barriers: barrier.cluster arrive / wait (each CTA's threads all take part; it also orders the CTA's own shared -// memory, so it doubles as __syncthreads). Phase 0 is a relaxed arrive at entry, waited before the first remote store -// (a CTA's shared memory exists once it runs). Pushes go out before the arrive that releases them, and nothing reads -// another CTA's memory after the last wait - so a CTA may exit without a closing barrier (a wait counts the threads -// that have not exited). `hin` alternates by pass parity: CTA x reads slot buffer p&1 in pass p before arriving at -// pass p+1's barrier, and nobody writes buffer p&1 again (pass p+2) before waiting on that barrier. -constexpr int CL_N = 8; // CTAs per query (the portable cluster size) -constexpr int CL_T = 1024; // threads per CTA -constexpr int CL_MAXQ = 16; // larger calls (prefill sub-batches) fill the GPU with one CTA per query already -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900 -#define STRATA_SEL_CLUSTER 1 -#else -#define STRATA_SEL_CLUSTER 0 // an older target's code is a trap; qsa_block_topk_cluster never launches it there -#endif - -#if STRATA_SEL_CLUSTER -__device__ __forceinline__ void cl_arrive_relaxed() { - asm volatile("barrier.cluster.arrive.relaxed.aligned;\n" ::: "memory"); -} -__device__ __forceinline__ void cl_arrive() { asm volatile("barrier.cluster.arrive.release.aligned;\n" ::: "memory"); } -__device__ __forceinline__ void cl_wait() { asm volatile("barrier.cluster.wait.acquire.aligned;\n" ::: "memory"); } -__device__ __forceinline__ unsigned cl_rank() { - unsigned r; - asm volatile("mov.u32 %0, %%cluster_ctarank;\n" : "=r"(r)); - return r; -} -template __device__ __forceinline__ T* cl_map(T* p, unsigned rank) { // p in CTA `rank`'s shared memory - uint64_t o; - asm volatile("mapa.u64 %0, %1, %2;\n" : "=l"(o) : "l"((uint64_t) p), "r"(rank)); - return reinterpret_cast(o); -} -// exclusive block scan of a 64-bit value over CL_T threads; `total` = the CTA's sum -__device__ __forceinline__ unsigned long long cl_excl_scan64(unsigned long long v, unsigned long long* s_warp, - unsigned long long& total) { - const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; - unsigned long long x = v; -#pragma unroll - for (int o = 1; o < 32; o <<= 1) { - const unsigned long long y = __shfl_up_sync(0xffffffffu, x, o); - if (lane >= o) x += y; - } - if (lane == 31) s_warp[warp] = x; - __syncthreads(); - if (warp == 0) { - const unsigned long long w = s_warp[lane]; - unsigned long long z = w; -#pragma unroll - for (int o = 1; o < 32; o <<= 1) { - const unsigned long long y = __shfl_up_sync(0xffffffffu, z, o); - if (lane >= o) z += y; - } - s_warp[lane] = z - w; - if (lane == 31) s_warp[32] = z; - } - __syncthreads(); - total = s_warp[32]; - return s_warp[warp] + x - v; -} -#endif - -// grid (CL_N, nq), cluster (CL_N, 1, 1), CL_T threads, dynamic shared memory: ceil(max_blocks / CL_N) keys -__global__ void __launch_bounds__(CL_T) block_topk_cluster_kernel(const float* __restrict__ scores, - const int32_t* __restrict__ steps, int64_t max_blocks, - int64_t cap, int32_t* __restrict__ ids) { -#if STRATA_SEL_CLUSTER - extern __shared__ uint32_t keys[]; // this CTA's blocks' keys - __shared__ __align__(16) int hin[2][CL_N][256]; // the cluster's histograms, slot = the pushing rank - __shared__ __align__(16) int hloc[2][256]; // this CTA's histogram - __shared__ unsigned long long cnt[CL_N]; // per rank: its cells above thr (low 32 bits) and at it (high) - __shared__ unsigned long long s_warp[33]; - __shared__ uint32_t s_prefix; - __shared__ int s_above; - const unsigned rank = cl_rank(); - const int t = threadIdx.x, lane = t & 31, warp = t >> 5; - cl_arrive_relaxed(); // phase 0: this CTA runs - const int64_t qi = blockIdx.y; - const int32_t* st = steps + qi * kStepCount; - const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth]; - int32_t* out = ids + qi * cap; - if (n_kv <= width) { // the identity, split over the cluster; no remote access - for (int64_t j = (int64_t) rank * CL_T + t; j < n_kv; j += (int64_t) CL_N * CL_T) out[j] = (int32_t) j; - return; - } - // the tail block n_bid weighs its cells (0..3); with none it is not a candidate (the reference skips w == 0) - const int wtail = (int) (n_kv - n_bid * R); - const int64_t nbe = n_bid + (wtail > 0 ? 1 : 0); - const int64_t per = (nbe + CL_N - 1) / CL_N; // <= ceil(max_blocks / CL_N), the keys the host sized - const int64_t lo = (int64_t) rank * per < nbe ? (int64_t) rank * per : nbe; - const int64_t hi = lo + per < nbe ? lo + per : nbe; - const int n = (int) (hi - lo); - const int tail_i = (wtail > 0 && n_bid >= lo && n_bid < hi) ? (int) (n_bid - lo) : -1; - const float* sc = scores + qi * max_blocks + lo; - for (int i = t; i < n; i += CL_T) keys[i] = order_key(sc[i]); - for (int i = t; i < 2 * 256; i += CL_T) (&hloc[0][0])[i] = 0; - __syncthreads(); - uint32_t prefix = 0; - int above = 0; // cells strictly above the digits fixed so far - for (int pass = 0; pass < 4; ++pass) { - const int shift = 24 - 8 * pass; - const uint32_t hmask = pass == 0 ? 0u : (0xffffffffu << (shift + 8)); - int* hl = hloc[pass & 1]; - // warp-aggregated: the scores share their top bits, so plain atomics would queue on a few bins - for (int i0 = 0; i0 < n; i0 += CL_T) { - const int i = i0 + t; - int bin = -1; - if (i < n) { - const uint32_t k = keys[i]; - if ((k & hmask) == prefix) bin = (int) ((k >> shift) & 255); - } - const unsigned same = __match_any_sync(0xffffffffu, bin); - if (bin >= 0 && lane == __ffs(same) - 1) atomicAdd(&hl[bin], __popc(same) * R); - if (bin >= 0 && i == tail_i) atomicAdd(&hl[bin], wtail - R); - } - __syncthreads(); - if (pass == 0) cl_wait(); // phase 0 done: every CTA's shared memory is there - for (int i = t; i < CL_N * 64; i += CL_T) { // the histogram into slot `rank` of every CTA, as int4 - const int dst = i >> 6, c = i & 63; - *cl_map(reinterpret_cast(&hin[pass & 1][rank][0]) + c, (unsigned) dst) = - reinterpret_cast(hl)[c]; - } - for (int i = t; i < 256; i += CL_T) hloc[(pass + 1) & 1][i] = 0; - cl_arrive(); - cl_wait(); - if (warp == 0) { - // lane L owns digits 255 - 8L down to 248 - 8L; the digit holding the need-th cell from the top - const int need = (int) width - above; - int tot[8], part = 0; -#pragma unroll - for (int k = 0; k < 8; ++k) { - const int d = 255 - 8 * lane - k; - int v = 0; -#pragma unroll - for (int r = 0; r < CL_N; ++r) v += hin[pass & 1][r][d]; - tot[k] = v; - part += v; - } - int incl = part; -#pragma unroll - for (int o = 1; o < 32; o <<= 1) { - const int y = __shfl_up_sync(0xffffffffu, incl, o); - if (lane >= o) incl += y; - } - const int excl = incl - part; - const unsigned hit = __ballot_sync(0xffffffffu, excl < need && incl >= need); - // no hit cannot happen (the cells total n_kv > width); the reference would then take digit 0 - const int who = hit ? __ffs(hit) - 1 : 31; - if (lane == who) { - int acc = excl, k = 0; - for (; k < 7; ++k) { - if (acc + tot[k] >= need) break; - acc += tot[k]; - } - s_prefix = prefix | ((uint32_t) (255 - 8 * lane - k) << shift); - s_above = above + acc; - } - } - __syncthreads(); - prefix = s_prefix; - above = s_above; - } - const uint32_t thr = prefix; - const int64_t eq_budget = width - above; // cells at thr that fit, lowest index first - // each thread a contiguous run of the CTA's keys; an odd run length keeps the shared reads conflict-free - int seg = (n + CL_T - 1) / CL_T; - if ((seg & 1) == 0 && seg > 0) ++seg; - const int s0 = t * seg < n ? t * seg : n, s1 = s0 + seg < n ? s0 + seg : n; - uint32_t gt = 0, eq = 0; - for (int i = s0; i < s1; ++i) { - const uint32_t k = keys[i], w = i == tail_i ? (uint32_t) wtail : (uint32_t) R; - if (k > thr) gt += w; - else if (k == thr) eq += w; - } - unsigned long long cta; - const unsigned long long before = - cl_excl_scan64((unsigned long long) gt | ((unsigned long long) eq << 32), s_warp, cta); - if (t < CL_N) *cl_map(&cnt[rank], (unsigned) t) = cta; - cl_arrive(); - cl_wait(); - int64_t gt_off = 0, eq_off = 0; - for (unsigned r = 0; r < rank; ++r) { - gt_off += (int64_t) (cnt[r] & 0xffffffffu); - eq_off += (int64_t) (cnt[r] >> 32); - } - const int64_t eq_before = eq_off + (int64_t) (before >> 32); - int64_t wpos = gt_off + (int64_t) (before & 0xffffffffu) + (eq_before < eq_budget ? eq_before : eq_budget); - int64_t eq_left = eq_budget - eq_before; - if (eq_left < 0) eq_left = 0; - for (int i = s0; i < s1; ++i) { - const uint32_t k = keys[i]; - const int w = i == tail_i ? wtail : R; - const int64_t b = lo + i; - if (k > thr) { - for (int c = 0; c < w; ++c) out[wpos++] = (int32_t) (b * R + c); - } else if (k == thr) { - for (int c = 0; c < w && eq_left > 0; ++c, --eq_left) out[wpos++] = (int32_t) (b * R + c); - } - } -#else - (void) scores; (void) steps; (void) max_blocks; (void) cap; (void) ids; - __trap(); -#endif -} -#endif // !__HIPCC__ -} // namespace - -void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq, - int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks) { - if (nq <= 0) return; - if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R || nq > 65535) { - std::fprintf(stderr, "qsa_block_scores: unsupported indexer geometry\n"); - std::exit(1); - } - // a block past a query's n_bid returns at once: the grid need only reach the batch's largest n_bid (C-1) - static const bool multi = [] { const char* v = std::getenv("STRATA_SCORES_MULTI"); return v == nullptr || std::atoi(v) != 0; }(); - if (multi && nq <= MQ && active_blocks <= 0) { // no active count: decode (captured or not) and prefill's pooled16 - block_scores_multi_kernel<<<256, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(pooled, dead, q_idx, steps, (int) nq, - max_blocks, scores); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores multi: %s\n", cudaGetErrorString(e)); std::exit(1); } - return; - } - const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks; - const dim3 grid((unsigned) ((reach + SCORE_WARPS - 1) / SCORE_WARPS), (unsigned) nq); - block_scores_kernel<<>>(pooled, dead, q_idx, steps, max_blocks, - scores); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores: %s\n", cudaGetErrorString(e)); std::exit(1); } -} - -bool qsa_block_scores_tc(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq, - int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks) { - if (nq <= 0) return true; - if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R || nq > 65535 * TC_QT) return false; -#if defined(__HIPCC__) - // AMD: the gfx12 (RDNA4) WMMA scorer, opt-in (STRATA_SELECT_WMMA=1): it selects slightly differently from the warp - // kernel (254/256 queries the same), so the default keeps the warp kernel; every other target keeps it too (false) - static const bool wmma_on = [] { - const char* v = std::getenv("STRATA_SELECT_WMMA"); - return v != nullptr && v[0] != '\0' && v[0] != '0'; - }(); - if (!wmma_on || !sel_gfx12_device()) return false; - { - const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks; - const int64_t per = (int64_t) 4 * WITER * 16; - const dim3 grid((unsigned) ((reach + per - 1) / per), (unsigned) ((nq + WQT - 1) / WQT)); - block_scores_wmma_kernel<<>>(pooled, q_idx, steps, nq, max_blocks, reach, scores); - block_scores_tail_kernel<<<(unsigned) nq, 32, 0, (cudaStream_t) stream>>>(dead, q_idx, steps, max_blocks, scores); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores_tc: %s\n", cudaGetErrorString(e)); std::exit(1); } - return true; - } -#else - { // sm_80 or newer (TF32 MMA); an older card keeps the warp kernel - static int cc_major[64] = {}; - int dev = 0; - if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } - if (cc_major[dev] == 0) { - int major = 0; - if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess) { - cudaGetLastError(); - return false; - } - // STRATA_QSA_WARP=1|select (an A/B arm): the pre-sm_80 kernels on any card, as RTX 20 runs them - const char* w = std::getenv("STRATA_QSA_WARP"); - cc_major[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "select")) ? 7 : strata::cc_major_of(major); - } - if (cc_major[dev] < 8) return false; - } - static bool attr[64] = {}; // the shared-memory opt-in is per device (a layer split runs it on several) - int adev = 0; - cudaGetDevice(&adev); - const int bytes = (TC_QT * TC_QS + TC_NB * TC_KS) * (int) sizeof(float); - if (!attr[adev]) { - if (cudaFuncSetAttribute(block_scores_tc_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) != - cudaSuccess) { - cudaGetLastError(); - return false; - } - attr[adev] = true; - } - const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks; - const int64_t per = (int64_t) TC_NB * TC_ITER; - const dim3 grid((unsigned) ((reach + per - 1) / per), (unsigned) ((nq + TC_QT - 1) / TC_QT)); - block_scores_tc_kernel<<>>(pooled, q_idx, steps, nq, max_blocks, reach, - scores); - block_scores_tail_kernel<<<(unsigned) nq, 32, 0, (cudaStream_t) stream>>>(dead, q_idx, steps, max_blocks, scores); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores_tc: %s\n", cudaGetErrorString(e)); std::exit(1); } - return true; -#endif -} - -void qsa_block_topk_ref(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, - const QsaShapes& s, int32_t* ids, void* stream) { - if (nq <= 0) return; - if (s.idx_block != R || cap < qsa_selection_width(kTopkMaxCells, s)) { - std::fprintf(stderr, "qsa_block_topk: unsupported geometry or cap\n"); - std::exit(1); - } - block_topk_kernel<<<(unsigned) nq, TOPK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk: %s\n", cudaGetErrorString(e)); std::exit(1); } -} - -#if !defined(__HIPCC__) -// Only Turing has a retained model measurement for this CUDA dispatch. Other CUDA devices keep the capacity rule -// (the RTX 5070 regression below). Cache the properties per calling thread; layer-split device switches are checked. -static bool topk_active_turing_device() { - int dev = 0; - if (cudaGetDevice(&dev) != cudaSuccess) return false; - static thread_local int cached_device = -1; - static thread_local bool turing = false; - if (dev != cached_device) { - cudaDeviceProp prop{}; - if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess) return false; - turing = prop.major == 7 && prop.minor == 5; - cached_device = dev; - } - return turing; -} -#endif - -bool qsa_block_topk_cluster(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, - const QsaShapes& s, int32_t* ids, void* stream) { -#if defined(__HIPCC__) - (void) scores; (void) steps; (void) nq; (void) max_blocks; (void) cap; (void) s; (void) ids; (void) stream; - return false; -#else - if (nq <= 0) return true; - if (s.idx_block != R || cap < qsa_selection_width(kTopkMaxCells, s) || nq > 65535 || max_blocks <= 0) return false; - const size_t smem = (size_t) ((max_blocks + CL_N - 1) / CL_N) * sizeof(uint32_t); - // Per device (a layer split runs on several): 1 the cluster kernel runs here, 2 it does not. It needs sm_90+ (the - // card's, or STRATA_EMULATE_CC's) AND code built for it: a build with only older code JIT-compiles their PTX, whose - // copy of this kernel is a trap - the function's PTX version says which. `opt`: the dynamic shared memory opted in. - static int ok[64] = {}; - static size_t opt[64] = {}; - int dev = 0; - if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } - if (ok[dev] == 0) { - int major = 0; - cudaFuncAttributes fa{}; - const bool code = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess && - strata::cc_major_of(major) >= 9 && - cudaFuncGetAttributes(&fa, block_topk_cluster_kernel) == cudaSuccess && fa.ptxVersion >= 90 && - fa.binaryVersion >= 90; - cudaGetLastError(); - ok[dev] = code ? 1 : 2; - } - if (ok[dev] != 1) return false; - if (smem > opt[dev]) { // a larger capacity: opt in, and check that a cluster of CL_N such CTAs can be resident - int clusters = 0; - cudaLaunchConfig_t q{}; - cudaLaunchAttribute qa[1]; - qa[0].id = cudaLaunchAttributeClusterDimension; - qa[0].val.clusterDim.x = CL_N; - qa[0].val.clusterDim.y = 1; - qa[0].val.clusterDim.z = 1; - q.gridDim = dim3(CL_N, 1, 1); - q.blockDim = dim3(CL_T, 1, 1); - q.dynamicSmemBytes = smem; - q.attrs = qa; - q.numAttrs = 1; - if (cudaFuncSetAttribute(block_topk_cluster_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem) != - cudaSuccess || - cudaOccupancyMaxActiveClusters(&clusters, block_topk_cluster_kernel, &q) != cudaSuccess || clusters < 1) { - cudaGetLastError(); - return false; // this capacity takes the one-CTA kernels; a smaller one may still fit - } - opt[dev] = smem; - } - cudaLaunchConfig_t cfg{}; - cudaLaunchAttribute at[1]; - at[0].id = cudaLaunchAttributeClusterDimension; - at[0].val.clusterDim.x = CL_N; - at[0].val.clusterDim.y = 1; - at[0].val.clusterDim.z = 1; - cfg.gridDim = dim3(CL_N, (unsigned) nq, 1); - cfg.blockDim = dim3(CL_T, 1, 1); - cfg.dynamicSmemBytes = smem; - cfg.stream = (cudaStream_t) stream; - cfg.attrs = at; - cfg.numAttrs = 1; - const cudaError_t e = cudaLaunchKernelEx(&cfg, block_topk_cluster_kernel, scores, steps, max_blocks, cap, ids); - if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk cluster: %s\n", cudaGetErrorString(e)); std::exit(1); } - return true; -#endif -} - -void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, - const QsaShapes& s, int32_t* ids, void* stream, int64_t active_blocks) { - // keys in registers when every query's blocks fit (contexts up to ~135K cells), else (CUDA) the same threads - // reading them from memory; the same ids. STRATA_TOPK_OLD=1: the original kernel - static const bool old = std::getenv("STRATA_TOPK_OLD") != nullptr; - if (nq <= 0) return; -#if !defined(__HIPCC__) - // sm_90+: a cluster of CL_N CTAs per query for the calls of a few queries (decode windows); the same ids. - // STRATA_QSA_CLUSTER=0: the one-CTA kernels below - static const bool cluster = [] { - const char* v = std::getenv("STRATA_QSA_CLUSTER"); - return !v || std::atoi(v) != 0; - }(); - if (cluster && !old && nq <= CL_MAXQ && qsa_block_topk_cluster(scores, steps, nq, max_blocks, cap, s, ids, stream)) - return; -#endif - // the blocks a query can have: the call's active count when the caller knows it (the prompt path), else the capacity. - // Decode (no count) keeps the capacity rule and the original register width: nothing changes there. -#if defined(__HIPCC__) - const bool counted = active_blocks > 0; -#else - // Turing: --max-context 262144 makes the stride 65538, even while a 131K prompt's active blocks fit in - // TK_T * TK_PER registers. Use the prefill bound on sm_75, keeping max_blocks as the score-row stride. - // Other CUDA devices keep 0.1.32's capacity rule: #337 was measured on RDNA4, and RTX 5070 64K prompts were - // 1-3% slower. Decode/captured graphs omit the bound and never query the device here. - static const bool capacity_guard = std::getenv("STRATA_TOPK_CAPACITY_GUARD") != nullptr; - // STRATA_TOPK_ACTIVE_ANY=1 (tests): the Turing dispatch on any CUDA card, so qsa_topk_active_parity checks it - // on whatever card runs the tests (the kernels are the same on every architecture) - static const bool any_card = [] { const char* v = std::getenv("STRATA_TOPK_ACTIVE_ANY"); return v && v[0] == '1'; }(); - const bool counted = !capacity_guard && active_blocks > 0 && active_blocks <= max_blocks && - (any_card || topk_active_turing_device()); -#endif - const int64_t reach = counted && active_blocks < max_blocks ? active_blocks : max_blocks; - const int64_t fit = (int64_t) TK_T * (counted ? TK_PER_MAX : TK_PER); -#if defined(__HIPCC__) - constexpr int64_t kRegMinBlocks = 7168; // gfx1201: below ~28K cells the 1,024-thread kernel's fixed cost loses to the ref - const bool too_small = counted && reach < kRegMinBlocks; - if (old || too_small || reach > fit) { -#else - constexpr int64_t kWideMinBlocks = 4608; // RTX 3060: a prompt batch below ~18K cells is faster on the ref - const bool too_small = reach > fit && active_blocks > 0 && active_blocks < kWideMinBlocks; - if (old || too_small) { -#endif - qsa_block_topk_ref(scores, steps, nq, max_blocks, cap, s, ids, stream); - return; - } - if (s.idx_block != R || cap < qsa_selection_width(kTopkMaxCells, s)) { - std::fprintf(stderr, "qsa_block_topk: unsupported geometry or cap\n"); - std::exit(1); - } -#if !defined(__HIPCC__) - if (reach > fit) // past the register kernel's reach - block_topk_wide_kernel<<<(unsigned) nq, TK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids); - else -#endif - if (reach <= (int64_t) TK_T * TK_PER) - block_topk_reg_kernel<<<(unsigned) nq, TK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids); - else - block_topk_reg_kernel<<<(unsigned) nq, TK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk: %s\n", cudaGetErrorString(e)); std::exit(1); } -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/quantize_act.cu b/src/kernels/cuda/quantize_act.cu deleted file mode 100644 index ddd14df..0000000 --- a/src/kernels/cuda/quantize_act.cu +++ /dev/null @@ -1,313 +0,0 @@ -// src/kernels/cuda/quantize_act.cu - P2.S2: quantize an activation the way ggml converts src1. -// -// WHY THIS EXISTS AT ALL. `ggml_mul_mat` converts the ACTIVATION (src1) to the weight's `vec_dot_type` -// before the dot product - the rule established over rounds 119-136 and written into `ref/quant.py` as -// `apply_src1`. The CPU expert path already honours it (`bench/micro/cpu_s2.cpp` quantizes to int8 and uses -// `vpdpbusd`), and its P0.T2 parity passes at 1.461e-06. The GPU kernels added in rounds 166-177 take FP16 -// activations instead. **Left that way, the two paths would compute different numbers for different experts -// of the SAME token** - not a tolerance question, an inconsistency inside one forward pass. -// -// Q2_0 IS THE CASE THAT MATTERS: the routed experts are all Q2_0, `Q2_0 -> Q8_0`, and that is 31.64 GiB of the -// 38 GiB pack. Q8_K (for the K-quants and IQ4_XS) is the other half of the table and is not here yet. -// -// THE THREE SUBTLETIES, each of which was paid for once already and is transcribed rather than recalled: -// -// 1. `d32 = amax / 127.0f` is computed in FP32, and the QUANTIZED INTEGERS divide by **d32**, not by the -// fp16-rounded value that gets stored. Conflating the two shifts every quant near a rounding boundary - -// measured against ggml's own bytes, 18 of 80 blocks differed, and because Q2_0 experts convert to Q8_0 -// the error landed in all 48 MoE blocks and made the end-to-end KL WORSE. -// 2. The reference divides in FLOAT64 (`blk.astype(np.float64) / float(np.float32(d32))`) and rounds with -// `rint` - half to even. This kernel therefore divides in double too: an FP32 division followed by -// `rintf` differs from the reference wherever the f32 quotient rounds across a .5 boundary. -// 3. The DEQUANTIZED value is `q * d16`, the fp16 scale, not `q * d32`. The block stores fp16 and that is -// what a reader multiplies by. -#include "strata/kernels/quantize_act.hpp" -#include "strata/kernels/f16_bits.hpp" - -#include - -#include -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int QK8_0 = 32; - -// THE fp16 CONVERSION LIVES IN `strata/kernels/f16_bits.hpp`, and this file used to carry its own copy. -// -// Round 198 found the private copy wrong in a way no fixture here could see: it tested `if (exp >= 31)` to -// detect an out-of-range exponent, which conflates an f32 INF/NAN (raw exponent 255) with a FINITE value too -// large for fp16. Every finite overflow - 1e30, 65536, 1e45 - came back as a NaN instead of saturating to -// inf, and this file's fixture is O(1) throughout, so it passed. A numpy-generated oracle caught it on its -// first run. Three copies of a converter whose failure mode is silent wrong bits was two copies too many. - - -__global__ void quantize_q8_0_kernel(const float* __restrict__ x, uint8_t* __restrict__ blocks, - long long n_blocks) { - const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x; - if (b >= n_blocks) return; - const float* xb = x + b * QK8_0; - uint8_t* out = blocks + b * 34; // { fp16 d ; int8 qs[32] } - - float amax = 0.0f; - for (int i = 0; i < QK8_0; ++i) amax = fmaxf(amax, fabsf(xb[i])); - if (amax == 0.0f) { - // ggml leaves the block zeroed: d = 0 and every q = 0. Writing the fp16 zero explicitly rather than - // skipping keeps the block layout deterministic for the byte comparison. - const uint16_t zb = f16_from_f32(0.0f); - out[0] = (uint8_t) (zb & 0xFF); - out[1] = (uint8_t) (zb >> 8); - for (int i = 0; i < QK8_0; ++i) out[2 + i] = 0; - return; - } - const float d32 = amax / 127.0f; - const uint16_t d16bits = f16_from_f32(d32); - out[0] = (uint8_t) (d16bits & 0xFF); - out[1] = (uint8_t) (d16bits >> 8); - - // double division, matching the reference exactly (subtlety 2) - for (int i = 0; i < QK8_0; ++i) { - double q = rint((double) xb[i] / (double) d32); - if (q > 127.0) q = 127.0; - if (q < -128.0) q = -128.0; - out[2 + i] = (uint8_t) (int8_t) q; - } -} - -/// **THE HIT PATH'S QUANTIZER, AND IT EXISTS TO REPRODUCE `act_quant_q8_1` EXACTLY (R4.2h, round 331).** -/// -/// The engine computes every routed expert twice. MISSES go through `cpu/expert.cpp:138 act_quant_q8_1` -/// into the VNNI kernel; HITS went through `quantize_q8_0` above. **Those are not the same quantization**, -/// and round 330 measured the difference with both real implementations linked -/// (`bench/micro/act_quant_parity.cu`): -/// -/// int8 activations differing : 0 of 2560 <- this rule's ties are measure-zero -/// chunks whose SCALE differs : 80 of 80, max rel 4.761e-04 <- 2^-11: fp32 vs the block's fp16 -/// -/// The scale is the difference that matters: `ActQ::scale` is `float` and the CPU kernel multiplies by it -/// (`expert.cpp:92`), while `row_dot_s2_q8` read `f16_at(xb)` out of the `block_q8_0`. So this variant -/// writes the SAME 34-byte blocks (the kernel's indexing is unchanged) **and** a parallel fp32 scale array -/// carrying `d32` unrounded. -/// -/// It also adopts the CPU's ROUNDING RULE - multiply by the reciprocal, round half AWAY FROM ZERO - rather -/// than this file's `rint`. That is deliberate and it is the opposite of the direction the comment above -/// argues for. `quantize_q8_0` was tuned to match **ggml's Q8_0 bytes**, which is right for the pack and for -/// `moe_hit_parity`. This function's job is different: it must match **this engine's own CPU reference**, -/// because a hit and a miss for the same expert on the same layer have to produce the same number. The CPU -/// path is the reference - C1 passes on it - so the hit path is brought to it, not the reverse. -__global__ void quantize_q8_0_scaled_kernel(const float* __restrict__ x, uint8_t* __restrict__ blocks, - float* __restrict__ scales, long long n_blocks) { - const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x; - if (b >= n_blocks) return; - const float* xb = x + b * QK8_0; - uint8_t* out = blocks + b * 34; - - float amax = 0.0f; - for (int i = 0; i < QK8_0; ++i) amax = fmaxf(amax, fabsf(xb[i])); - // VERBATIM from `cpu/expert.cpp:144-145`, including the `amax > 0` guard, so the fp32 value written here - // is bit-identical to the `s` the CPU path used. - const float s = amax > 0.f ? amax / 127.f : 0.f; - const float inv = s > 0.f ? 1.f / s : 0.f; - scales[b] = s; - - const uint16_t d16bits = f16_from_f32(s); - out[0] = (uint8_t) (d16bits & 0xFF); - out[1] = (uint8_t) (d16bits >> 8); - for (int i = 0; i < QK8_0; ++i) { - // VERBATIM from `cpu/expert.cpp:159-162`: reciprocal multiply, then `t + copysign(0.5, t)` truncated - // toward zero, which is `lround`'s rule - round half away from zero. - const float t = xb[i] * inv; - const float r = t + (t >= 0.f ? 0.5f : -0.5f); - int v = (int) r; - v = v < -127 ? -127 : (v > 127 ? 127 : v); - out[2 + i] = (uint8_t) (int8_t) v; - } -} - -__global__ void dequant_q8_0_kernel(const uint8_t* __restrict__ blocks, float* __restrict__ x, - long long n_blocks) { - const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x; - if (b >= n_blocks) return; - const uint8_t* blk = blocks + b * 34; - const uint16_t dbits = (uint16_t) (blk[0] | (blk[1] << 8)); - const float d = f32_from_f16(dbits); - float* out = x + b * QK8_0; - for (int i = 0; i < QK8_0; ++i) out[i] = (float) (int8_t) blk[2 + i] * d; -} - -// ===================== Q8_K ===================== -// -// `block_q8_K` = { float d ; int8_t qs[256] ; int16_t bsums[16] } = 292 bytes, no padding -// (`static_assert` in ggml-common.h). QK_K = 256. - -constexpr int QK_K = 256; -constexpr int Q8K_BYTES = 292; - -/// ggml's `nearest_int` (ggml-quants.c L621), transcribed rather than replaced. -/// -/// The magic number is 1.5 * 2^23: adding it forces the mantissa's integer part into the low bits, and the -/// mask/subtract recover it. The reason it is transcribed and not written as `rintf` is that the two differ -/// on exact ties - and that is the whole point of the constant, so a "cleaner" rewrite would silently change -/// which way ties go. -__device__ __forceinline__ int nearest_int_dev(float fval) { - const float val = fval + 12582912.0f; - int i; - memcpy(&i, &val, 4); - return (i & 0x007fffff) - 0x00400000; -} - -__global__ void quantize_q8_K_kernel(const float* __restrict__ x, uint8_t* __restrict__ blocks, - long long n_blocks) { - const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x; - if (b >= n_blocks) return; - const float* xb = x + b * QK_K; - uint8_t* out = blocks + b * Q8K_BYTES; - float* d = (float*) out; - int8_t* qs = (int8_t*) (out + 4); - int16_t* bsums = (int16_t*) (out + 4 + QK_K); - - // `max` is the SIGNED value at the largest magnitude position, and the comparison is STRICTLY greater, - // so a tie keeps the FIRST maximum - which is what `np.argmax` does in the reference transcription too. - float max = 0.0f, amax = 0.0f; - for (int j = 0; j < QK_K; ++j) { - const float ax = fabsf(xb[j]); - if (ax > amax) { - amax = ax; - max = xb[j]; - } - } - if (amax == 0.0f) { - // ggml writes d = 0 and zeroes qs, then `continue`s - which LEAVES bsums UNWRITTEN. A zeroed block - // and an untouched one are indistinguishable to the dot product, but not to a byte comparison, so - // this zeroes bsums as well and the parity test's reference does the same. Recorded because it is a - // deliberate divergence from the letter of the source. - *d = 0.0f; - for (int j = 0; j < QK_K; ++j) qs[j] = 0; - for (int j = 0; j < QK_K / 16; ++j) bsums[j] = 0; - return; - } - const float iscale = -127.0f / max; // -127, NOT -128; see the header - for (int j = 0; j < QK_K; ++j) { - // `__fmul_rn`, NOT `iscale * xb[j]`. ggml computes the product, ROUNDS IT TO F32, and then adds - // 12582912.0f inside `nearest_int`. Written as a plain expression, nvcc CONTRACTS the multiply into - // the add as an FMA - which is a more accurate product but not the same one, and it flips the result - // wherever the true product sits just off a .5 boundary. The first version of this kernel differed - // from the reference in 1 element of 524,288 for exactly this reason, and `__fmul_rn` pins the - // rounding step the source actually performs. - const int v = nearest_int_dev(__fmul_rn(iscale, xb[j])); - qs[j] = (int8_t) min(127, v); // MIN only - the source has no lower clamp - } - for (int j = 0; j < QK_K / 16; ++j) { - int sum = 0; - for (int ii = 0; ii < 16; ++ii) sum += qs[j * 16 + ii]; - bsums[j] = (int16_t) sum; - } - *d = 1.0f / iscale; -} - -__global__ void dequant_q8_K_kernel(const uint8_t* __restrict__ blocks, float* __restrict__ x, - long long n_blocks) { - const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x; - if (b >= n_blocks) return; - const uint8_t* blk = blocks + b * Q8K_BYTES; - float d; - memcpy(&d, blk, 4); - const int8_t* qs = (const int8_t*) (blk + 4); - float* out = x + b * QK_K; - for (int i = 0; i < QK_K; ++i) out[i] = (float) qs[i] * d; -} - -} // namespace - -void quantize_q8_0(const float* x, uint8_t* blocks, int64_t n, void* stream) { - if (n <= 0) return; - if (n % QK8_0 != 0) { - std::fprintf(stderr, "quantize_q8_0: n %lld is not a multiple of %d\n", (long long) n, QK8_0); - std::exit(1); - } - const long long nb = n / QK8_0; - const int threads = 128; - const unsigned grid = (unsigned) ((nb + threads - 1) / threads); - quantize_q8_0_kernel<<>>(x, blocks, nb); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "quantize_q8_0 launch: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - if (stream == nullptr) cudaDeviceSynchronize(); -} - -/// See `quantize_q8_0_scaled_kernel`. Writes the same 34-byte `block_q8_0` layout as `quantize_q8_0`, plus -/// `scales[n/32]` carrying the fp32 `s` the CPU path used - so a hit can be computed with the CPU's -/// multiplier instead of the block's fp16 `d`. `scales` must not be null. -void quantize_q8_0_scaled(const float* x, uint8_t* blocks, float* scales, int64_t n, void* stream) { - if (n <= 0) return; - if (n % QK8_0 != 0) { - std::fprintf(stderr, "quantize_q8_0_scaled: n %lld is not a multiple of %d\n", (long long) n, QK8_0); - std::exit(1); - } - if (scales == nullptr) { - std::fprintf(stderr, "quantize_q8_0_scaled: scales is null\n"); - std::exit(1); - } - const long long nb = n / QK8_0; - const int threads = 128; - const unsigned grid = (unsigned) ((nb + threads - 1) / threads); - quantize_q8_0_scaled_kernel<<>>(x, blocks, scales, nb); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "quantize_q8_0_scaled launch: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - if (stream == nullptr) cudaDeviceSynchronize(); -} - -void dequant_q8_0(const uint8_t* blocks, float* x, int64_t n, void* stream) { - if (n <= 0) return; - const long long nb = n / QK8_0; - const int threads = 128; - const unsigned grid = (unsigned) ((nb + threads - 1) / threads); - dequant_q8_0_kernel<<>>(blocks, x, nb); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "dequant_q8_0 launch: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - if (stream == nullptr) cudaDeviceSynchronize(); -} - -void quantize_q8_K(const float* x, uint8_t* blocks, int64_t n, void* stream) { - if (n <= 0) return; - if (n % QK_K != 0) { - std::fprintf(stderr, "quantize_q8_K: n %lld is not a multiple of %d\n", (long long) n, QK_K); - std::exit(1); - } - const long long nb = n / QK_K; - const int threads = 64; // one block per thread, and a block is 256 elements - const unsigned grid = (unsigned) ((nb + threads - 1) / threads); - quantize_q8_K_kernel<<>>(x, blocks, nb); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "quantize_q8_K launch: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - if (stream == nullptr) cudaDeviceSynchronize(); -} - -void dequant_q8_K(const uint8_t* blocks, float* x, int64_t n, void* stream) { - if (n <= 0) return; - const long long nb = n / QK_K; - const int threads = 64; - const unsigned grid = (unsigned) ((nb + threads - 1) / threads); - dequant_q8_K_kernel<<>>(blocks, x, nb); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "dequant_q8_K launch: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - if (stream == nullptr) cudaDeviceSynchronize(); -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/rope.cu b/src/kernels/cuda/rope.cu deleted file mode 100644 index 807545e..0000000 --- a/src/kernels/cuda/rope.cu +++ /dev/null @@ -1,136 +0,0 @@ -// src/kernels/cuda/rope.cu - P2.S2: NEOX partial RoPE. -// -// Semantics from `ref/qsa.py` (`rope_freqs` + `rope_neox`), which `bench/micro/rope_xcheck` validates against -// the oracle: -// -// inv[i] = theta ** (-2i / n_rot) i in [0, n_rot/2) -// ang = pos * inv -// cos, sin = cos(ang), sin(ang) -// out[:half] = a*cos - b*sin a = x[:half], b = x[half:n_rot] -// out[half:n_rot] = a*sin + b*cos -// -// THE PAIRING IS NEOX - (i, i + n_rot/2), NOT the adjacent pair (2i, 2i+1). `ggml.h` writes NEOX -// n_dims=8 as [ccccssss]; the adjacent-pair ("NORMAL") ordering is the other common convention and choosing -// wrongly rotates the wrong dimensions together, which produces correctly-shaped output with scrambled -// content. It is also PARTIAL: only the first n_rot of head_dim are touched, here 64 of 256. -// -// WHY THE TABLE IS BUILT ON THE HOST. The reference computes the frequencies in FLOAT64 (`theta ** (...)` -// on a float64 arange, cos/sin in float64). Reproducing that on device means double-precision pow and cos, -// which are slow on a consumer GPU and - more to the point - not guaranteed to agree with the host's libm. -// Building the table once on the host and passing it in makes the TABLE exactly the reference's values and -// leaves the kernel a pure rotation, so each half can be checked tightly instead of both halves sharing one -// loose tolerance. The engine wants a cached table anyway: it is per (n_rot, theta, position), not per token. -// -// THE SCALED TABLE IS THE SAME IDEA WITH MORE MATH IN THE HOST LOOP. Linear rescales the angle by -// `freq_scale`; YaRN blends extrapolation and interpolation along the pairs (ggml's `rope_yarn`) and folds -// the mscale magnitude correction into the same cos/sin values. All of it float64, in the reference's -// order, so `rope_parity` can hold every variant to a bit-exact float64 transcription of the same spec. -#include "strata/kernels/rope.hpp" -#include "strata/kernels/mrope.hpp" - -#include - -#include -#include -#include - -namespace strata::kernels { - -namespace { -// The process's rope config (rope_scaling.hpp). One writer - the engine's startup thread, before -// session_init builds any table or captures any graph - and readers after it. -RopeScaling g_rope_scaling; -} // namespace - -void rope_scaling_set(const RopeScaling& scaling) { g_rope_scaling = scaling; } -const RopeScaling& rope_scaling() { return g_rope_scaling; } - -void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, float* sin_tab) { - const int half = n_rot / 2; - for (int p = 0; p < max_pos; ++p) { - for (int i = 0; i < half; ++i) { - // float64 throughout, in the reference's order: inv, then ang, then cos/sin - const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot); - const double ang = (double) p * inv; - cos_tab[(size_t) p * half + i] = (float) std::cos(ang); - sin_tab[(size_t) p * half + i] = (float) std::sin(ang); - } - } -} - -void build_rope_table(int n_rot, const RopeScaling& sc, int max_pos, float* cos_tab, float* sin_tab) { - if (sc.type == RopeScalingType::None) { - build_rope_table(n_rot, sc.freq_base, max_pos, cos_tab, sin_tab); // the original loop, verbatim - return; - } - const int half = n_rot / 2; - const double fs = sc.freq_scale(); - const double ms = sc.mscale(); - double cd[2]; - sc.corr_dims(n_rot, cd); - const bool correct = sc.ext_factor != 0; // ggml: the correction rides on ext_factor, not the type - for (int p = 0; p < max_pos; ++p) { - for (int i = 0; i < half; ++i) { - const double inv = std::pow(sc.freq_base, -2.0 * (double) i / (double) n_rot); - const double extrap = (double) p * inv; // the trained angle, ggml's theta_extrap - const double interp = fs * extrap; // ggml's theta_interp - double ang = interp; - if (correct) { - const double ramp = (double) rope_yarn_ramp((float) cd[0], (float) cd[1], i) * sc.ext_factor; - ang = interp * (1.0 - ramp) + extrap * ramp; - } - cos_tab[(size_t) p * half + i] = (float) (std::cos(ang) * ms); - sin_tab[(size_t) p * half + i] = (float) (std::sin(ang) * ms); - } - } -} - -namespace { - -// ONE THREAD PER ROW, not per (row, pair). The first version had one thread per pair and did the tail copy -// with hreadIdx.x strided loops - so up to 32 threads wrote into the SAME row, with no barrier between the -// copy and the rotation, and a thread's copy of orow[i] could land AFTER another thread had rotated it. A -// race that silently writes the unrotated value is worse than a wrong answer: it is intermittent. -// -// A row is head_dim floats (256 here) and there are batch x heads of them, so one thread per row is a -// handful of threads for a token and removes the ordering question entirely rather than synchronising it. -__global__ void rope_neox_kernel(const float* __restrict__ x, float* __restrict__ out, long long rows, - int head_dim, int n_rot, const float* __restrict__ cos_tab, - const float* __restrict__ sin_tab, const int* __restrict__ pos, - const int32_t* __restrict__ mtab) { - const long long r = (long long) blockIdx.x * blockDim.x + threadIdx.x; - if (r >= rows) return; - const int half = n_rot / 2; - const float* xr = x + r * head_dim; - float* orow = out + r * head_dim; - - for (int d = n_rot; d < head_dim; ++d) orow[d] = xr[d]; // the PARTIAL rotation's untouched tail - for (int i = 0; i < half; ++i) { - const size_t toff = (size_t) mrope_pos(mtab, pos[r], i) * half; // the image path's per-pair position - // THE PAIRING AND THE SIGNS COME FROM `rope_neox_pair`, shared with the indexer's pooling kernel. - rope_neox_pair(xr[i], xr[half + i], cos_tab[toff + i], sin_tab[toff + i], orow[i], orow[half + i]); - } -} - -} // namespace - -void rope_neox_apply(const float* x, float* out, int64_t rows, int head_dim, int n_rot, const float* cos_tab, - const float* sin_tab, const int* pos, void* stream) { - if (rows <= 0 || n_rot <= 0) return; - if (n_rot % 2 != 0 || n_rot > head_dim) { - std::fprintf(stderr, "rope_neox_apply: n_rot %d must be even and <= head_dim %d\n", n_rot, head_dim); - std::exit(1); - } - const int threads = 128; - const unsigned grid = (unsigned) ((rows + threads - 1) / threads); - rope_neox_kernel<<>>(x, out, rows, head_dim, n_rot, cos_tab, - sin_tab, pos, mrope_table()); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "rope_neox_apply launch: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - if (stream == nullptr) cudaDeviceSynchronize(); -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/router_top10.cu b/src/kernels/cuda/router_top10.cu deleted file mode 100644 index 720cec6..0000000 --- a/src/kernels/cuda/router_top10.cu +++ /dev/null @@ -1,497 +0,0 @@ -// src/kernels/cuda/router_top10.cu - P2.S2: the MoE router. -// -// P2.S2's spec: "BF16 GEMV, softmax / top-k / renormalize per docs/semantics.md; emits (expert_id, weight) x 10 -// per token". This is the softmax/top-k/renormalize half; the BF16 GEMV that produces the logits is a -// separate kernel and is NOT here. -// -// The semantics are transcribed from `ref/moe.py::router`, which is itself transcribed from llama-graph.cpp: -// -// p = softmax(logits) over ALL experts, not over the selected subset -// ids = stable argsort(-p)[:k] ties break by INDEX, ascending -// w = gather(p, ids) -// s = max(sum(w), 2**-14) ggml_clamp(..., 2**-14, INF) -// return ids, w / s -// -// The two-step structure matters and is not cosmetic: computing softmax over the selected subset instead is -// mathematically identical (softmax is shift-invariant) but it moves the renormalisation, and the CLAMP is -// part of the renormalisation. Reproducing the gather form is what makes the clamp land in the same place. -// -// WHY THIS IS NO LONGER "NAIVE BY DESIGN", AND WHAT THE OLD REASONING GOT WRONG. -// -// The first version was ONE THREAD PER TOKEN: k passes over the experts, each pass recomputing -// `exp((double) l[e] - mx)` for every expert. Its comment justified that with -// -// "5,120 operations per token against 2.36e9 weights of expert matvec - three orders of magnitude smaller -// than the thing it feeds, so the simplest correct version is also fast enough" -// -// **That is a statement about OPERATION COUNT and it says nothing about TIME, because all 5,120 operations were -// on ONE THREAD while the matvec has thousands.** Measured (round 218, stage-by-stage inside one block): -// -// moe_layer 4.077 ms router_top10 3.387 ms bf16 gemv 0.270 ms -// -// 3.39 ms per layer x 48 layers = 163 ms of a 289 ms token - **56% of the whole forward pass, in a kernel that -// reads 2.6 MB.** It was invisible in `router_top10_parity` because that test runs the kernel ONCE and checks -// the right ids, and invisible in every per-layer test for the same reason. -// -// WHAT IS PARALLELISED AND WHAT IS DELIBERATELY NOT: -// -// * the MAX is a tree reduction of `fmaxf`, which is exact and order-independent - bit-identical to the -// serial scan it replaces; -// * the 512 EXPONENTIALS are computed ONCE each, in parallel. The old kernel computed them ELEVEN TIMES -// (once for the softmax, then again inside every one of the k passes). This is where the 3.4 ms was; -// * the DOUBLE SUM is still accumulated on ONE thread in ASCENDING order. 512 double adds is about a -// microsecond and it keeps the accumulation order - and therefore the last bits - identical to the -// reference-faithful serial version. Parallelising it would be a free speedup and a silent change to the -// values, and the exp was the cost, not this; -// * the SELECTION is by RANK rather than by k repeated maxima: -// -// rank(e) = #{ f : p[f] > p[e] } + #{ f < e : p[f] == p[e] } -// -// which IS "stable descending argsort, ties by ascending index" - the same order the repeated-maximum loop -// produced - computed in ONE parallel pass over the experts instead of k serial ones. It is O(n^2) -// comparisons and that is the right trade here: n = 512, every comparison is independent, and the old -// version was O(k*n) with a serial `exp` inside. -#include "strata/kernels/router_top10.hpp" - -#include - -#include -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int RT_MAX_THREADS = 512; - -/// One BLOCK per token, so the reductions have somewhere to happen. `n_tokens` is 1 in decode; the grid keeps -/// the batch case working without a second code path. -__global__ void router_top10_kernel(const float* __restrict__ logits, int n_tokens, int n_expert, int k, - int* __restrict__ ids, float* __restrict__ weights) { - // **`s_taken` IS FIRST SO THE OTHER TWO KEEP THEIR ALIGNMENT WITHOUT AN OFFSET PARAMETER**, and `s_p`'s - // existing `s_ex + n_expert` stays correct because it is relative to `s_ex`. One byte per expert. - extern __shared__ unsigned char s_raw[]; - const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u; - unsigned char* s_taken = s_raw; - double* s_ex = (double*) (s_raw + taken_bytes); - __shared__ float s_red[RT_MAX_THREADS / 32]; - __shared__ int s_rid[RT_MAX_THREADS / 32]; - __shared__ double s_sum; - - const int t = blockIdx.x; - if (t >= n_tokens) return; - const int tid = threadIdx.x; - const int nt = blockDim.x; - const float* l = logits + (size_t) t * n_expert; - - // ---- softmax over ALL experts, for stability: the max. A tree of `fmaxf` is EXACT and order-independent, - // so this is bit-identical to the serial scan. - float mx = -INFINITY; - for (int e = tid; e < n_expert; e += nt) mx = fmaxf(mx, l[e]); - for (int off = 16; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_down_sync(0xffffffffu, mx, off)); - if ((tid & 31) == 0) s_red[tid >> 5] = mx; - __syncthreads(); - if (tid < 32) { - const int nw = (nt + 31) >> 5; - float v = (tid < nw) ? s_red[tid] : -INFINITY; - for (int off = 16; off > 0; off >>= 1) v = fmaxf(v, __shfl_down_sync(0xffffffffu, v, off)); - if (tid == 0) s_red[0] = v; - } - __syncthreads(); - mx = s_red[0]; - - // ---- THE 512 EXPONENTIALS, ONCE EACH AND IN PARALLEL. `exp` in double is software-emulated on this die - // and was 5,632 serial calls before; it is 512 parallel ones now. - for (int e = tid; e < n_expert; e += nt) s_ex[e] = exp((double) l[e] - (double) mx); - __syncthreads(); - - // ---- the sum, ascending, on one thread: see the note above on why this is NOT parallelised. - if (tid == 0) { - double sum = 0.0; - for (int e = 0; e < n_expert; ++e) sum += s_ex[e]; - s_sum = sum; - } - __syncthreads(); - const float inv = (float) (1.0 / s_sum); - - // ---- the selection, by rank. `p[e] = (float)(s_ex[e] * inv)` reproduces the old expression exactly: - // `(float)(exp((double) l[e] - (double) mx) * inv)` with `inv` a FLOAT. - // ---- p[] ONCE. The rank loop below compares every expert against every other, so computing - // `(float) (s_ex[f] * inv)` INSIDE it did **512 x 512 = 262,144** double multiplies and float converts per - // token per layer instead of 512 - and a consumer die runs FP64 at a small fraction of FP32, which is why - // this was worth more than the branch. The shared load stays either way; the ARITHMETIC is what goes. - // - // THIS IS BIT-IDENTICAL, not merely equivalent: `p[e]` is the same expression it was, computed once instead - // of 513 times, and the comparisons then see exactly the same floats. - float* s_p = (float*) (s_ex + n_expert); - for (int e = tid; e < n_expert; e += nt) s_p[e] = (float) (s_ex[e] * inv); - __syncthreads(); - - // ================================ THE SELECTION, IN k PASSES ================================ - // - // **THE RANK-BY-COUNTING LOOP COMPARED EVERY EXPERT AGAINST EVERY OTHER**: 512 x 512 = 262,144 shared - // loads and compares per token per layer, to choose ten things out of 512 - measured at 34.35 us, 63% of - // `moe_route`'s accounted cost and the largest single item in the R3 plan. The comment above records that - // the FP64 ARITHMETIC inside that loop was hoisted out once already ("262,144 double multiplies per token - // per layer instead of 512"); **the O(n^2) STRUCTURE was left, and it is the structure that costs.** - // - // `k` passes of a block-wide argmax is 10 x 512 = 5,120 compares - **51x less work** - and it produces the - // SAME ORDER. That is the whole correctness argument: scanning `e` ascending with a strict `>` keeps the - // LOWEST index on a tie, which is exactly the rule the rank loop spelled out as - // `else if (f < e && pf == pe) ++rank`. A stable descending top-k, ties by index. - for (int e = tid; e < n_expert; e += nt) s_taken[e] = 0; - __syncthreads(); - - for (int i = 0; i < k; ++i) { - float bv = -INFINITY; - int bi = n_expert; // a sentinel that loses to every real index - for (int e = tid; e < n_expert; e += nt) { - if (s_taken[e]) continue; - const float pe = s_p[e]; - if (pe > bv) { bv = pe; bi = e; } - } - for (int off = 16; off > 0; off >>= 1) { - const float ov = __shfl_down_sync(0xffffffffu, bv, off); - const int oi = __shfl_down_sync(0xffffffffu, bi, off); - if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; } - } - if ((tid & 31) == 0) { s_red[tid >> 5] = bv; s_rid[tid >> 5] = bi; } - __syncthreads(); - if (tid < 32) { - const int nw = (nt + 31) >> 5; - float v = (tid < nw) ? s_red[tid] : -INFINITY; - int ix = (tid < nw) ? s_rid[tid] : n_expert; - for (int off = 16; off > 0; off >>= 1) { - const float ov = __shfl_down_sync(0xffffffffu, v, off); - const int oi = __shfl_down_sync(0xffffffffu, ix, off); - if (ov > v || (ov == v && oi < ix)) { v = ov; ix = oi; } - } - if (tid == 0 && ix < n_expert) { - ids[(size_t) t * k + i] = ix; - weights[(size_t) t * k + i] = v; - s_taken[ix] = 1; - } - } - __syncthreads(); - } - __syncthreads(); - - // ---- renormalise, with ggml's lower clamp. Order preserved. - if (tid == 0) { - double s = 0.0; - for (int i = 0; i < k; ++i) s += (double) weights[(size_t) t * k + i]; - const double sc = fmax(s, 6.103515625e-05); // 2**-14 - for (int i = 0; i < k; ++i) - weights[(size_t) t * k + i] = (float) ((double) weights[(size_t) t * k + i] / sc); - } -} - - -#if defined(STRATA_HIP_GFX906) -// AMD (wave64): the same routing in ONE wavefront per token. The block-wide kernel above spends its time in -// barriers - 10 selection passes with two __syncthreads each over 8 logical warps - not in arithmetic (43 us per -// token on gfx906). Here every lane holds up to RW_PER probabilities in registers and each pass is a 64-lane -// butterfly argmax: no LDS round trip, no block barrier. Bit-identical to the kernel above: fmaxf trees are -// exact, the exponentials and the (float) products are the same expressions, the sum stays one serial ascending -// scan, and the argmax keeps the lowest index on a tie (a total order, so the butterfly's association is free). -constexpr int RW_PER = 8; // n_expert <= 64 * 8 -__global__ void __launch_bounds__(64) router_top10_wave_kernel(const float* __restrict__ logits, int n_tokens, - int n_expert, int k, int* __restrict__ ids, - float* __restrict__ weights) { - __shared__ double s_ex[64 * RW_PER]; - __shared__ double s_sum; - const int t = blockIdx.x; - if (t >= n_tokens) return; - const int lane = threadIdx.x; - const float* l = logits + (size_t) t * n_expert; - float lv[RW_PER]; - float mx = -INFINITY; -#pragma unroll - for (int j = 0; j < RW_PER; ++j) { - const int e = lane + 64 * j; - lv[j] = e < n_expert ? l[e] : -INFINITY; - mx = fmaxf(mx, lv[j]); - } -#pragma unroll - for (int off = 32; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_xor(mx, off, 64)); -#pragma unroll - for (int j = 0; j < RW_PER; ++j) { - const int e = lane + 64 * j; - if (e < n_expert) s_ex[e] = exp((double) lv[j] - (double) mx); - } - __syncthreads(); - if (lane == 0) { - double sum = 0.0; - for (int e = 0; e < n_expert; ++e) sum += s_ex[e]; - s_sum = sum; - } - __syncthreads(); - const float inv = (float) (1.0 / s_sum); - float p[RW_PER]; -#pragma unroll - for (int j = 0; j < RW_PER; ++j) { - const int e = lane + 64 * j; - p[j] = e < n_expert ? (float) (s_ex[e] * inv) : -INFINITY; - } - unsigned taken = 0; - for (int i = 0; i < k; ++i) { - float bv = -INFINITY; - int bi = n_expert; -#pragma unroll - for (int j = 0; j < RW_PER; ++j) { - const int e = lane + 64 * j; - if (e >= n_expert || (taken >> j & 1u)) continue; - if (p[j] > bv || (p[j] == bv && e < bi)) { bv = p[j]; bi = e; } - } -#pragma unroll - for (int off = 32; off > 0; off >>= 1) { - const float ov = __shfl_xor(bv, off, 64); - const int oi = __shfl_xor(bi, off, 64); - if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; } - } - if (bi >= n_expert) break; - if ((bi & 63) == lane) taken |= 1u << (bi >> 6); - if (lane == 0) { ids[(size_t) t * k + i] = bi; weights[(size_t) t * k + i] = bv; } - } - if (lane == 0) { - double s = 0.0; - for (int i = 0; i < k; ++i) s += (double) weights[(size_t) t * k + i]; - const double sc = fmax(s, 6.103515625e-05); // 2**-14 - for (int i = 0; i < k; ++i) - weights[(size_t) t * k + i] = (float) ((double) weights[(size_t) t * k + i] / sc); - } -} -#endif // STRATA_HIP_GFX906 - -#if defined(__HIPCC__) -// ---- S6, AMD: the same router, BIT-IDENTICAL, without its serial parts. Measured on RDNA4 (gfx1201) the kernel -// above took 39 us per call in decode (16% of the GPU's decode time): the ascending double sum is 512 dependent FP64 -// adds (~50 cycles each there), the ten selection passes are 20 block barriers, and the renormalisation re-reads its -// ten weights from global memory one by one. Here: -// * the sum's ONLY use is inv = (float) (1.0 / sum). Every term is positive and the largest is exactly 1 -// (exp(0)), so the serial sum and any other summation order both lie within 2^-43 (relative) of the exact sum -// (|serial - exact| <= 511u, |tree - exact| <= 21u, u = 2^-53). 1.0 / x and the float cast are monotone: when -// the bracket [tree (1 - 2^-40), tree (1 + 2^-40)] maps to ONE float, that float is the serial sum's. Otherwise -// (about 1 row in 1000 in the parity test, or a non-finite sum) thread 0 runs the serial sum as before; -// * the selection runs on wave 0 alone with the probabilities in registers (16 per lane): the largest p with the -// lowest index on ties is unique, so the butterfly finds the same expert as the block reduction did; -// * the renormalisation sums the ten weights in rank order from registers and divides them in parallel. -// Same expressions, same operands: the ids and weights are bitwise those of router_top10_kernel (hip_router_fast -// checks it on 65,536 rows with ties, near-ties, NaN rows and the forced serial path). STRATA_HIP_ROUTER_OLD=1: the -// kernel above. -template -__global__ void router_top10_fast_kernel(const float* __restrict__ logits, int n_tokens, int n_expert, int k, - int* __restrict__ ids, float* __restrict__ weights) { - extern __shared__ unsigned char s_raw[]; - const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u; - double* s_ex = (double*) (s_raw + taken_bytes); - __shared__ float s_red[RT_MAX_THREADS / 32]; - __shared__ double s_dred[RT_MAX_THREADS / 32]; - __shared__ float s_inv; - const int t = blockIdx.x; - if (t >= n_tokens) return; - const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; - const int nt = blockDim.x, nw = (nt + 31) >> 5; - const float* l = logits + (size_t) t * n_expert; - // the max: as router_top10_kernel (exact, order-independent) - float mx = -INFINITY; - for (int e = tid; e < n_expert; e += nt) mx = fmaxf(mx, l[e]); - for (int off = 16; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_down_sync(0xffffffffu, mx, off)); - if (lane == 0) s_red[warp] = mx; - __syncthreads(); - if (tid < 32) { - float v = (tid < nw) ? s_red[tid] : -INFINITY; - for (int off = 16; off > 0; off >>= 1) v = fmaxf(v, __shfl_down_sync(0xffffffffu, v, off)); - if (tid == 0) s_red[0] = v; - } - __syncthreads(); - mx = s_red[0]; - // the exponentials (the same expression), and a tree sum of them for the bracket - double part = 0.0; - for (int e = tid; e < n_expert; e += nt) { - const double x = exp((double) l[e] - (double) mx); - s_ex[e] = x; - part += x; - } - for (int off = 16; off > 0; off >>= 1) part += __shfl_xor_sync(0xffffffffu, part, off); - if (lane == 0) s_dred[warp] = part; - __syncthreads(); - double tot = 0.0; - for (int w = 0; w < nw; ++w) tot += s_dred[w]; - const double lo = tot * (1.0 - 0x1p-40), hi = tot * (1.0 + 0x1p-40); - const float f_lo = (float) (1.0 / hi), f_hi = (float) (1.0 / lo); - float inv; - if (!FORCE_SERIAL && tot >= 1.0 && hi < 1e300 && f_lo == f_hi) { - inv = f_lo; - } else { // block-uniform (every thread computed the same tot): the serial sum, exactly as router_top10_kernel - if (tid == 0) { - double sum = 0.0; - for (int e = 0; e < n_expert; ++e) sum += s_ex[e]; - s_inv = (float) (1.0 / sum); - } - __syncthreads(); - inv = s_inv; - } - if (warp != 0) return; - // wave 0: lane holds experts lane + 32 j; p is router_top10_kernel's expression - constexpr int PER = 16; - float pv[PER]; - unsigned live = 0; -#pragma unroll - for (int j = 0; j < PER; ++j) { - const int e = lane + 32 * j; - pv[j] = -INFINITY; - if (e < n_expert) { pv[j] = (float) (s_ex[e] * inv); live |= 1u << j; } - } - float my_w = 0.0f; - int my_id = 0, nsel = 0; - for (int i = 0; i < k; ++i) { - float bv = -INFINITY; - int bi = n_expert; // a sentinel that loses to every real index -#pragma unroll - for (int j = 0; j < PER; ++j) - if (((live >> j) & 1u) && pv[j] > bv) { bv = pv[j]; bi = lane + 32 * j; } - for (int off = 16; off > 0; off >>= 1) { - const float ov = __shfl_xor_sync(0xffffffffu, bv, off); - const int oi = __shfl_xor_sync(0xffffffffu, bi, off); - if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; } - } - if (bi >= n_expert) break; // as router_top10_kernel: no rank i or later is written (every p left is NaN) - if ((bi & 31) == lane) live &= ~(1u << (bi >> 5)); - if (lane == i) { my_w = bv; my_id = bi; } - nsel = i + 1; - } - if (nsel == k) { - double s = 0.0; - for (int i = 0; i < k; ++i) s += (double) __shfl_sync(0xffffffffu, my_w, i); - const double sc = fmax(s, 6.103515625e-05); // 2**-14 - if (lane < k) { - ids[(size_t) t * k + lane] = my_id; - weights[(size_t) t * k + lane] = (float) ((double) my_w / sc); - } - } else { // router_top10_kernel's tail exactly: unwritten ranks keep what the buffer held and are renormalised too - if (lane < nsel) { ids[(size_t) t * k + lane] = my_id; weights[(size_t) t * k + lane] = my_w; } - __threadfence(); - if (lane == 0) { - double s = 0.0; - for (int i = 0; i < k; ++i) s += (double) weights[(size_t) t * k + i]; - const double sc = fmax(s, 6.103515625e-05); - for (int i = 0; i < k; ++i) - weights[(size_t) t * k + i] = (float) ((double) weights[(size_t) t * k + i] / sc); - } - } -} - -void launch_generic(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights, void* stream, - int mode) { // mode 0: router_top10_kernel, 1: the HIP fast kernel, 2: the fast kernel's serial path - int threads = n_expert < RT_MAX_THREADS ? n_expert : RT_MAX_THREADS; - threads = (threads + 31) & ~31; - const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u; - const size_t smem = taken_bytes + (size_t) n_expert * sizeof(double) + (size_t) n_expert * sizeof(float); - if (mode == 1) { - router_top10_fast_kernel<<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>( - logits, n_tokens, n_expert, k, ids, weights); - return; - } - if (mode == 2) { - router_top10_fast_kernel<<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>( - logits, n_tokens, n_expert, k, ids, weights); - return; - } - router_top10_kernel<<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>( - logits, n_tokens, n_expert, k, ids, weights); -} -#endif - -} // namespace - -bool router_top10_variant(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights, - void* stream, int variant) { -#if defined(__HIPCC__) - if (n_tokens <= 0 || n_expert <= 64 || n_expert > 512 || k <= 0 || k > 32) return false; - if (variant < 0 || variant > 2) return false; - launch_generic(logits, n_tokens, n_expert, k, ids, weights, stream, variant); - return cudaGetLastError() == cudaSuccess; -#else - (void) logits; (void) n_tokens; (void) n_expert; (void) k; (void) ids; (void) weights; (void) stream; - (void) variant; - return false; -#endif -} - -void router_top10(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights, - void* stream) { -#if defined(__HIPCC__) - { -#if defined(STRATA_HIP_GFX906) - // gfx906 (wave64): the one-wavefront kernel below stays the default; the S6 kernel is wave32-shaped and only - // runs here on request (STRATA_HIP_ROUTER_FAST=1) until it is measured on this card - static const bool old = std::getenv("STRATA_HIP_ROUTER_FAST") == nullptr; -#else - static const bool old = std::getenv("STRATA_HIP_ROUTER_OLD") != nullptr; -#endif - if (!old && n_tokens > 0 && n_expert > 64 && n_expert <= 512 && k > 0 && k <= 32) { - launch_generic(logits, n_tokens, n_expert, k, ids, weights, stream, 1); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "router_top10 launch: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - if (stream == nullptr) { - const cudaError_t s = cudaDeviceSynchronize(); - if (s != cudaSuccess) { - std::fprintf(stderr, "router_top10: %s\n", cudaGetErrorString(s)); - std::exit(1); - } - } - return; - } - } -#endif - if (n_tokens <= 0 || n_expert <= 0 || k <= 0) return; - if (k > 64) { - std::fprintf(stderr, "router_top10: k %d exceeds the kernel's 64\n", k); - std::exit(1); - } - if (n_expert > RT_MAX_THREADS * 64) { - std::fprintf(stderr, "router_top10: n_expert %d is past the kernel's %d\n", n_expert, - RT_MAX_THREADS * 64); - std::exit(1); - } -#if defined(STRATA_HIP_GFX906) - if (n_expert <= 64 * RW_PER && !std::getenv("STRATA_ROUTER_BLOCK")) { - router_top10_wave_kernel<<<(unsigned) n_tokens, 64, 0, (cudaStream_t) stream>>>(logits, n_tokens, n_expert, k, - ids, weights); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "router_top10 launch: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - if (stream == nullptr && cudaDeviceSynchronize() != cudaSuccess) std::exit(1); - return; - } -#endif - int threads = n_expert < RT_MAX_THREADS ? n_expert : RT_MAX_THREADS; - threads = (threads + 31) & ~31; // at least one full warp, for the reductions - // the selection's taken-mask, then n_expert doubles for the exponentials, then n_expert floats for the - // probabilities. The mask is first so the two aligned arrays need no offset parameter. - const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u; - const size_t smem = - taken_bytes + (size_t) n_expert * sizeof(double) + (size_t) n_expert * sizeof(float); - router_top10_kernel<<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>( - logits, n_tokens, n_expert, k, ids, weights); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "router_top10 launch: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - if (stream == nullptr) { - const cudaError_t s = cudaDeviceSynchronize(); - if (s != cudaSuccess) { - std::fprintf(stderr, "router_top10: %s\n", cudaGetErrorString(s)); - std::exit(1); - } - } -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/s2_expert_grouped.cu b/src/kernels/cuda/s2_expert_grouped.cu deleted file mode 100644 index 925ac3a..0000000 --- a/src/kernels/cuda/s2_expert_grouped.cu +++ /dev/null @@ -1,1190 +0,0 @@ -// src/kernels/cuda/s2_expert_grouped.cu - R4's grouped GPU expert. Read the header first. -// -// THE ARITHMETIC IS `src/kernels/cpu/expert.cpp`'s, over the same bytes, one warp per output row. -// -// sum_j (c_j - 1) * d_w * xhat_j * d_x == d_w * d_x * ( sum_j c_j*xhat_j - sum_j xhat_j ) -// -// Both sums are INT8 x INT8, so both are `__dp4a` - four multiply-accumulates per instruction, exact in -// integer and with no dequantization inside the loop. The weight scale `d_w` is fp16 (one per 64 elements) -// and the activation scale `d_x` is fp16 (one per 32 elements), so the float work is one multiply-add per -// 32-element chunk rather than one per element. -// -// **THE SUMMATION ORDER IS NOT THE CPU's AND CANNOT BE.** Lane `L` takes chunks `L, L+32, ...` and the -// partials are reduced through shuffle; the CPU walks every chunk in order with its own accumulator shape. -// The two agree to float rounding and not to the bit, which is the same contract `s_gemv_parity` carries for -// the same reason. `bench/micro/moe_hit_parity.cu` is the check. -#include "strata/kernels/s2_expert_grouped.hpp" -#include "strata/kernels/dp4a.hpp" - -#include "strata/kernels/quantize_act.hpp" -#include "strata/kernels/verify_kernels.hpp" - -#include -#include - -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { - -// THE BLOB'S OWN GEOMETRY, from `include/strata/kernels/cpu/expert.hpp`. Restated as literals because that -// header is the CPU path's and this file must not silently follow it if the two ever disagree: the sizes below -// are what the CPU kernel's indexing computes, and `moe_hit_parity` compares the two end to end. -constexpr int H = 2560; -constexpr int FF = 640; -constexpr int QK = 64; // Q2_0's group: one fp16 scale per 64 weights -constexpr int ROW_GU = H / 4; // 640 B of codes per gate/up row (2 bits per element) -constexpr int ROW_D = FF / 4; // 160 B per down row -constexpr int SC_GU = H / QK; // 40 fp16 scales per gate/up row -constexpr int SC_D = FF / QK; // 10 per down row -constexpr size_t O_D_CODES = (size_t) 2 * FF * ROW_GU; -constexpr size_t O_GU_SCALES = O_D_CODES + (size_t) H * ROW_D; -constexpr size_t O_D_SCALES = O_GU_SCALES + (size_t) 2 * FF * SC_GU * 2; - -__device__ __forceinline__ float f16_at(const uint8_t* p) { - return __half2float(__ushort_as_half((uint16_t) (p[0] | (p[1] << 8)))); -} - -/// **ONE S2 ROW AGAINST A Q8_0 ACTIVATION, WARP-WIDE.** Every lane accumulates its own float partial over a -/// strided set of 32-element chunks and the caller reduces; `chunk` indices are absolute so the caller can -/// start the lane at any offset. -/// -/// Returns the lane's partial. `codes` is `n_in/4` bytes and `scales` `n_in/QK` fp16, both for THIS row. -/// -/// **`x_scales` IS R4.2h AND IT IS OPTIONAL ON PURPOSE.** When it is non-null the activation's multiplier -/// comes from an fp32 array instead of the block's fp16 `d`. The CPU pool multiplies by the fp32 -/// `ActQ::scale` (`cpu/expert.cpp:92`), and the two disagreed by **4.761e-04 relative on 80 of 80 chunks** -/// (`bench/micro/act_quant_parity.cu`), which is what made a cache hit compute a different expert from a -/// cache miss. Null keeps the previous fp16 behaviour **exactly**, so `moe_hit_parity` - which passes no -/// scales - still measures the kernel it always measured. -__device__ __forceinline__ float row_dot_s2_q8(const uint8_t* __restrict__ codes, - const uint8_t* __restrict__ scales, - const uint8_t* __restrict__ x_q8_0, int n_chunks, int lane, - const float* __restrict__ x_scales = nullptr) { - float acc = 0.0f; - for (int c = lane; c < n_chunks; c += 32) { - const uint8_t* cb = codes + (size_t) c * 8; // 8 code bytes = 32 elements - const uint8_t* xb = x_q8_0 + (size_t) c * 34; // one block_q8_0 - const float dx = x_scales ? x_scales[c] : f16_at(xb); - const int8_t* xq = (const int8_t*) (xb + 2); - - // ---- THE CODES, EXPANDED TO ONE BYTE PER ELEMENT, THEN FOUR AT A TIME INTO `dp4a`. - // - // The packed form is LSB-first: element 4j+k is bits [2k, 2k+2) of code byte j. `dp4a` needs both - // operands as packed int8, so each code byte becomes a word whose four bytes are its four 2-bit - // fields - which is exactly `(c & 3) | ((c>>2)&3)<<8 | ((c>>4)&3)<<16 | ((c>>6)&3)<<24`. - int s = 0; // sum of code * x - int hx = 0; // sum of x - the weight-independent term, as ones * x - const int ones = 0x01010101; -#pragma unroll - for (int j = 0; j < 8; ++j) { - const unsigned cbyte = cb[j]; - const int cw = (int) ((cbyte & 3u) | (((cbyte >> 2) & 3u) << 8) | (((cbyte >> 4) & 3u) << 16) | - (((cbyte >> 6) & 3u) << 24)); - // **`memcpy`, NOT A CAST.** A `block_q8_0` is 34 BYTES - two of header then 32 of int8 - so the - // activation data at offset 2 is never 4-byte aligned, and `*(const int*)(xq + 4*j)` faults with - // "misaligned address". It faulted exactly that way on this kernel's first run. `memcpy` of a - // known 4 bytes compiles to whatever load is legal for the alignment, which is the point of using - // it rather than reasoning about which cast happens to work. - int xw; - memcpy(&xw, xq + 4 * j, 4); - s = STRATA_DP4A(cw, xw, s); - hx = STRATA_DP4A(ones, xw, hx); - } - // One weight scale per 64 elements, so per TWO 32-element chunks. - const float dw = f16_at(scales + (size_t) (c >> 1) * 2); - acc += dw * dx * (float) (s - hx); - } - return acc; -} - -__device__ __forceinline__ float warp_sum(float v) { -#pragma unroll - for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off); - return v; -} - -/// GATE AND UP, ONE WARP PER ROW. -/// -/// **THE ROWS ARE INTERLEAVED AND THE FIRST VERSION OF THIS GOT IT WRONG.** In the blob, row-SLOT `i` of the -/// `2*FF` gate/up rows is gate row `i/2` when `i` is even and up row `(i-1)/2` when it is odd - that is what -/// `O_GU_CODES + (2r)*ROW_GU` and `+ (2r+1)*ROW_GU` mean in `expert.cpp`. This kernel decoded the correct -/// code row for slot `i` and then wrote it to output slot `i` of a layout whose first `FF` entries are gate and -/// whose last `FF` are up, which pairs `silu(gate[r]) * up[r]` with the WRONG `up` for every `r`. It produced -/// finite, plausible numbers. `moe_hit_parity` caught it on the first run, at worst relative error 2.2e+03. -/// -/// So slot `i` is DECODED from row-slot `i` and WRITTEN to the output slot its parity says it belongs to. -__global__ void gu_kernel(const uint8_t* __restrict__ blob_base, const int32_t* __restrict__ slot_index, - long long blob_bytes, const uint8_t* __restrict__ x_q8_0, - const float* __restrict__ x_scales, float* __restrict__ gate_up, int n_hits, - const int32_t* __restrict__ d_count = nullptr, - const int32_t* __restrict__ dst_index = nullptr, int tok_div = 0) { - const int warps_per_block = (int) (blockDim.x >> 5); - const long long slot = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5); - const long long rows_per_hit = 2LL * FF; - const long long total = (long long) n_hits * rows_per_hit; - if (slot >= total) return; - const int h = (int) (slot / rows_per_hit); - if (d_count != nullptr && h >= *d_count) return; // token graph: capacity layout, device count - const int i = (int) (slot % rows_per_hit); - const int lane = threadIdx.x & 31; - - const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes; - if (tok_div > 0) { // plan v0.3 P6 verify window: each hit reads its own token's activation - const int tok = dst_index[h] / tok_div; - x_q8_0 += (size_t) tok * (size_t) (H / 32) * 34; - if (x_scales != nullptr) x_scales += (size_t) tok * (size_t) (H / 32); - } - const float acc = row_dot_s2_q8(blob + (size_t) i * ROW_GU, - blob + O_GU_SCALES + (size_t) i * SC_GU * 2, x_q8_0, H / 32, lane, x_scales); - const float s = warp_sum(acc); - if (lane != 0) return; - // ---- THE OUTPUT LAYOUT IS GATE-MAJOR, AND THAT IS NOT COSMETIC. - // - // The first version wrote `gate_up[h*2FF + {0..FF-1}] = gate` and `[h*2FF + FF..] = up`, i.e. a per-hit - // [gate | up] pair, and then called the shared `swiglu_kernel` and `quantize_q8_0` over the whole buffer. - // Both of those walk a CONTIGUOUS range, so with more than one hit they read hit 0's UP rows where they - // wanted hit 1's GATE rows - finite numbers, wrong expert. With one hit it would have passed. - // - // Gate-major removes the mismatch instead of adding a stride to two other kernels: every hit's gate rows - // are contiguous from 0, every hit's up rows are contiguous from `n_hits * FF`, and the swiglu's output - // lands in the first `n_hits * FF` floats exactly where `quantize_q8_0` reads it. - const int r = i >> 1; - const size_t base = (i & 1) ? ((size_t) n_hits * FF + (size_t) h * FF) : ((size_t) h * FF); - gate_up[base + (size_t) r] = s; -} - -/// `silu(gate) * up`, in place, over a GATE-MAJOR buffer: `[0, n_pairs)` is every hit's gate and -/// `[n_pairs, 2*n_pairs)` is every hit's up, so hit `h`'s row `r` meets itself at `h*FF + r`. -/// -/// SiLU on the GATE and multiplied by up - the reading `docs/semantics.md` records, and the one that is wrong -/// the other way round in a way that still produces a finite number. -__global__ void swiglu_kernel(float* __restrict__ gate_up, long long n_pairs) { - const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n_pairs) return; - const float g = gate_up[i]; - const float u = gate_up[n_pairs + i]; - gate_up[i] = (g / (1.0f + __expf(-g))) * u; -} - -/// DOWN, ONE WARP PER ROW, reading the quantized intermediate the caller produced. -/// -/// `dst_index[h]` is which row of the shared output buffer hit `h` fills - see the header. It is the router's -/// slot, not `h`, and the two differ on every layer where some experts are resident and some are not. -__global__ void down_kernel(const uint8_t* __restrict__ blob_base, const int32_t* __restrict__ slot_index, - const int32_t* __restrict__ dst_index, long long blob_bytes, - const uint8_t* __restrict__ h_q8_0, const float* __restrict__ h_scales, - float* __restrict__ out, int n_hits, const int32_t* __restrict__ d_count = nullptr) { - const int warps_per_block = (int) (blockDim.x >> 5); - const long long row = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5); - const long long total = (long long) n_hits * H; - if (row >= total) return; - const int h = (int) (row / H); - if (d_count != nullptr && h >= *d_count) return; - const int r = (int) (row % H); - const int lane = threadIdx.x & 31; - - const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes; - const uint8_t* xb = h_q8_0 + (size_t) h * (size_t) (FF / 32) * 34; - const float acc = row_dot_s2_q8(blob + O_D_CODES + (size_t) r * ROW_D, - blob + O_D_SCALES + (size_t) r * SC_D * 2, xb, FF / 32, lane, - h_scales ? h_scales + (size_t) h * (size_t) (FF / 32) : nullptr); - const float s = warp_sum(acc); - if (lane == 0) out[(size_t) dst_index[h] * H + r] = s; -} - -// ---- THE SAME INTEGERS FROM FEWER INSTRUCTIONS. `STRATA_OLD_GROUPED=1` keeps the kernels above. -// -// **INSIDE A CHUNK, WHICH CODE MEETS WHICH ACTIVATION IN A `dp4a` WORD IS FREE.** `s = sum_e code_e * x_e` and -// `hx = sum_e x_e` are exact integer sums (|s| <= 32 * 3 * 128), so any grouping of the 32 products into words -// gives the same two integers. The grouping used here costs no transposition of the codes: `(w >> 2f) & 0x03030303` -// holds field `f` of each of a code word's four bytes - elements `4b + f`, plus 16 for the second word - so it is -// the ACTIVATIONS that are regrouped, once per chunk, into -// -// X[4h + f] = { x[16h + f], x[16h + 4 + f], x[16h + 8 + f], x[16h + 12 + f] } -// -// a 4x4 byte transpose of each half of the chunk, eight `__byte_perm`. The kernels above spend seven integer -// operations per code BYTE and a second `dp4a` chain for `hx` on every row; here a code word costs seven for 16 -// elements and `hx` is summed once per chunk. `s`, `hx` and the float expression `dw * dx * (float) (s - hx)` are -// unchanged, so every output is bitwise the previous kernels' - `s2_expert_grouped_parity` checks exactly that. - -// fp16 at an even address, one 16-bit load (`f16_at` reads it as two bytes); same value. -__device__ __forceinline__ float f16_ld(const uint8_t* p) { - return __half2float(__ushort_as_half(*(const unsigned short*) p)); -} - -// A chunk's two code words as the eight `dp4a` operands that pair with `X[0..7]`: `m[4h + f]` byte `b` is the -// code of element `16h + 4b + f`. -__device__ __forceinline__ void expand_codes(uint2 cb, int m[8]) { - const unsigned M = 0x03030303u; - m[0] = (int) (cb.x & M); - m[1] = (int) ((cb.x >> 2) & M); - m[2] = (int) ((cb.x >> 4) & M); - m[3] = (int) ((cb.x >> 6) & M); - m[4] = (int) (cb.y & M); - m[5] = (int) ((cb.y >> 2) & M); - m[6] = (int) ((cb.y >> 4) & M); - m[7] = (int) ((cb.y >> 6) & M); -} - -// The 32 int8 of the `block_q8_0` at `xb` regrouped into `X[0..7]` (see above), and their sum `hx`. -// -// **NINE ALIGNED WORD LOADS INSTEAD OF 32 BYTE LOADS.** The caller guarantees a 4-byte aligned activation row, so -// chunk `c`'s int8 start at `34c + 2`, i.e. 0 bytes (odd `c`) or 2 bytes (even `c`) into an aligned word; the -// words are read aligned and funnel-shifted into place. The ninth word is read only in the 2-byte case, and then -// it lies inside block `c + 1` of the same row: both row lengths (80 and 20 chunks) are even, so an even chunk is -// never a row's last. -__device__ __forceinline__ int load_x_chunk(const uint8_t* __restrict__ xb, int X[8]) { - const uint8_t* q = xb + 2; - const int off = (int) ((uintptr_t) q & 3); - const unsigned* p = (const unsigned*) (q - off); - const unsigned sh = (unsigned) off * 8; - unsigned v[9]; -#pragma unroll - for (int j = 0; j < 8; ++j) v[j] = __ldg(p + j); - v[8] = off != 0 ? __ldg(p + 8) : 0u; - unsigned n[8]; - int hx = 0; -#pragma unroll - for (int j = 0; j < 8; ++j) { - // natural word j: x[4j .. 4j+3]; a 64-bit shift (sh is 0, 8, 16 or 24) rather than __funnelshift_r, so the same - // source needs no CUDA-only intrinsic. - n[j] = (unsigned) ((((unsigned long long) v[j + 1] << 32) | v[j]) >> sh); - hx = STRATA_DP4A(0x01010101, (int) n[j], hx); - } -#pragma unroll - for (int h = 0; h < 2; ++h) { - const unsigned t0 = __byte_perm(n[4 * h], n[4 * h + 1], 0x5140); // a0 b0 a1 b1 - const unsigned t1 = __byte_perm(n[4 * h], n[4 * h + 1], 0x7362); // a2 b2 a3 b3 - const unsigned t2 = __byte_perm(n[4 * h + 2], n[4 * h + 3], 0x5140); // c0 d0 c1 d1 - const unsigned t3 = __byte_perm(n[4 * h + 2], n[4 * h + 3], 0x7362); // c2 d2 c3 d3 - X[4 * h + 0] = (int) __byte_perm(t0, t2, 0x5410); // a0 b0 c0 d0 - X[4 * h + 1] = (int) __byte_perm(t0, t2, 0x7632); // a1 b1 c1 d1 - X[4 * h + 2] = (int) __byte_perm(t1, t3, 0x5410); // a2 b2 c2 d2 - X[4 * h + 3] = (int) __byte_perm(t1, t3, 0x7632); // a3 b3 c3 d3 - } - return hx; -} - -// `s` for one chunk: the eight expanded code words against the eight regrouped activation words. -__device__ __forceinline__ int chunk_s(const int m[8], const int X[8]) { - int s = 0; -#pragma unroll - for (int j = 0; j < 8; ++j) s = STRATA_DP4A(m[j], X[j], s); - return s; -} - -/// `gu_kernel`, new: ONE WARP PER (gate, up) PAIR - row-slots `2r` and `2r + 1`, adjacent in the blob - so each -/// activation chunk is loaded and regrouped once for both rows. Per row, the lane's chunks, their order, the float -/// expression and the shuffle reduction are `row_dot_s2_q8`'s; the outputs land where `gu_kernel` puts them. -__global__ void gu_pair_kernel(const uint8_t* __restrict__ blob_base, const int32_t* __restrict__ slot_index, - long long blob_bytes, const uint8_t* __restrict__ x_q8_0, - const float* __restrict__ x_scales, float* __restrict__ gate_up, int n_hits, - const int32_t* __restrict__ d_count, const int32_t* __restrict__ dst_index, - int tok_div) { - const int warps_per_block = (int) (blockDim.x >> 5); - const long long pair = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5); - const long long total = (long long) n_hits * FF; - if (pair >= total) return; - const int h = (int) (pair / FF); - if (d_count != nullptr && h >= *d_count) return; - const int r = (int) (pair % FF); - const int lane = threadIdx.x & 31; - - const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes; - if (tok_div > 0) { - const int tok = dst_index[h] / tok_div; - x_q8_0 += (size_t) tok * (size_t) (H / 32) * 34; - if (x_scales != nullptr) x_scales += (size_t) tok * (size_t) (H / 32); - } - const uint8_t* codes = blob + (size_t) (2 * r) * ROW_GU; // gate row; the up row follows it - const uint8_t* scales = blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2; - float acc_g = 0.0f, acc_u = 0.0f; - for (int c = lane; c < H / 32; c += 32) { - const uint8_t* xb = x_q8_0 + (size_t) c * 34; - const float dx = x_scales ? x_scales[c] : f16_ld(xb); - int X[8], m[8]; - const int hx = load_x_chunk(xb, X); - expand_codes(*(const uint2*) (codes + (size_t) c * 8), m); - const float dw_g = f16_ld(scales + (size_t) (c >> 1) * 2); - acc_g += dw_g * dx * (float) (chunk_s(m, X) - hx); - expand_codes(*(const uint2*) (codes + ROW_GU + (size_t) c * 8), m); - const float dw_u = f16_ld(scales + SC_GU * 2 + (size_t) (c >> 1) * 2); - acc_u += dw_u * dx * (float) (chunk_s(m, X) - hx); - } - const float sg = warp_sum(acc_g); - const float su = warp_sum(acc_u); - if (lane != 0) return; - gate_up[(size_t) h * FF + (size_t) r] = sg; // gate-major, as in `gu_kernel` - gate_up[(size_t) n_hits * FF + (size_t) h * FF + (size_t) r] = su; -} - -/// `down_kernel`, new: ONE WARP PER PAIR OF ROWS `r, r + 1` of one hit, the intermediate's chunk loaded once for both. -__global__ void down_pair_kernel(const uint8_t* __restrict__ blob_base, const int32_t* __restrict__ slot_index, - const int32_t* __restrict__ dst_index, long long blob_bytes, - const uint8_t* __restrict__ h_q8_0, const float* __restrict__ h_scales, - float* __restrict__ out, int n_hits, const int32_t* __restrict__ d_count) { - const int warps_per_block = (int) (blockDim.x >> 5); - const long long pair = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5); - const long long total = (long long) n_hits * (H / 2); - if (pair >= total) return; - const int h = (int) (pair / (H / 2)); - if (d_count != nullptr && h >= *d_count) return; - const int r = 2 * (int) (pair % (H / 2)); - const int lane = threadIdx.x & 31; - - const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes; - const uint8_t* xrow = h_q8_0 + (size_t) h * (size_t) (FF / 32) * 34; - const float* xs = h_scales ? h_scales + (size_t) h * (size_t) (FF / 32) : nullptr; - const uint8_t* codes = blob + O_D_CODES + (size_t) r * ROW_D; - const uint8_t* scales = blob + O_D_SCALES + (size_t) r * SC_D * 2; - float acc0 = 0.0f, acc1 = 0.0f; - for (int c = lane; c < FF / 32; c += 32) { - const uint8_t* xb = xrow + (size_t) c * 34; - const float dx = xs ? xs[c] : f16_ld(xb); - int X[8], m[8]; - const int hx = load_x_chunk(xb, X); - expand_codes(*(const uint2*) (codes + (size_t) c * 8), m); - const float dw0 = f16_ld(scales + (size_t) (c >> 1) * 2); - acc0 += dw0 * dx * (float) (chunk_s(m, X) - hx); - expand_codes(*(const uint2*) (codes + ROW_D + (size_t) c * 8), m); - const float dw1 = f16_ld(scales + SC_D * 2 + (size_t) (c >> 1) * 2); - acc1 += dw1 * dx * (float) (chunk_s(m, X) - hx); - } - const float s0 = warp_sum(acc0); - const float s1 = warp_sum(acc1); - if (lane != 0) return; - const size_t o = (size_t) dst_index[h] * H + (size_t) r; - out[o] = s0; - out[o + 1] = s1; -} - -// The CPU subtracts the weight bias after its eight FMA accumulators have been reduced. Moving the -// subtraction into each integer dot, as the legacy kernel does, changes rounding even with equal scales. -__global__ void activation_correction_kernel(const uint8_t* q8, const float* scales, float* hx, int chunks) { - const int c = blockIdx.x * blockDim.x + threadIdx.x; - if (c >= chunks) return; - const int8_t* q = (const int8_t*) (q8 + (size_t) c * 34 + 2); - int sum = 0; - for (int j = 0; j < 32; ++j) sum += q[j]; - hx[c] = __fmul_rn(scales[c], (float) sum); -} - -__device__ __forceinline__ int dot4(const uint8_t* codes, const int8_t* q) { - const unsigned c = *codes; - const int cw = (int) ((c & 3u) | (((c >> 2) & 3u) << 8) | - (((c >> 4) & 3u) << 16) | (((c >> 6) & 3u) << 24)); - int xw; - memcpy(&xw, q, sizeof xw); - return STRATA_DP4A(cw, xw, 0); -} - -__device__ __forceinline__ float row_dot_cpu_order(const uint8_t* codes, const uint8_t* scales, - const uint8_t* xq, const float* xs, - const float* hx, int blocks, int lane) { - float acc = 0.0f; - float corr = 0.0f; - for (int b = 0; b < blocks; ++b) { - const float d = f16_at(scales + 2 * b); - const int lo = dot4(codes + b * 16 + lane, - (const int8_t*) (xq + (size_t) (2 * b) * 34 + 2) + lane * 4); - const int hi = dot4(codes + b * 16 + 8 + lane, - (const int8_t*) (xq + (size_t) (2 * b + 1) * 34 + 2) + lane * 4); - acc = __fmaf_rn(__fmul_rn(d, xs[2 * b]), (float) lo, acc); - acc = __fmaf_rn(__fmul_rn(d, xs[2 * b + 1]), (float) hi, acc); - if (lane == 0) - corr = __fadd_rn(corr, __fmul_rn(d, __fadd_rn(hx[2 * b], hx[2 * b + 1]))); - } - // _mm_add_ps(low128, high128), then two _mm_hadd_ps. The pair order is 4, 1, 2; - // a standard shuffle tree in the order 4, 2, 1 is a different floating-point expression. - constexpr unsigned mask = 0xffffffffu; - acc = __fadd_rn(acc, __shfl_down_sync(mask, acc, 4, 8)); - acc = __fadd_rn(acc, __shfl_down_sync(mask, acc, 1, 8)); - acc = __fadd_rn(acc, __shfl_down_sync(mask, acc, 2, 8)); - return __fsub_rn(acc, corr); // Only lane zero is consumed. -} - -template -__global__ void cpu_order_projection_kernel(const uint8_t* blob_base, const int32_t* slots, - const int32_t* destinations, long long blob_bytes, - const uint8_t* xq, const float* xs, const float* hx, - float* out, int n_hits) { - constexpr int rows_per_hit = DOWN ? H : 2 * FF; - const int row = blockIdx.x * (blockDim.x / 8) + threadIdx.x / 8; - if (row >= n_hits * rows_per_hit) return; - const int h = row / rows_per_hit; - const int r = row % rows_per_hit; - const int lane = threadIdx.x & 7; - const uint8_t* blob = blob_base + (size_t) slots[h] * (size_t) blob_bytes; - const int chunks_offset = DOWN ? h * (FF / 32) : 0; - const uint8_t* codes = DOWN ? blob + O_D_CODES + (size_t) r * ROW_D : blob + (size_t) r * ROW_GU; - const uint8_t* scales = DOWN ? blob + O_D_SCALES + (size_t) r * SC_D * 2 - : blob + O_GU_SCALES + (size_t) r * SC_GU * 2; - const float value = row_dot_cpu_order(codes, scales, xq + (size_t) chunks_offset * 34, - xs + chunks_offset, hx + chunks_offset, - DOWN ? SC_D : SC_GU, lane); - if (lane != 0) return; - if (DOWN) out[(size_t) destinations[h] * H + r] = value; - else out[((r & 1) ? (size_t) n_hits * FF : 0) + (size_t) h * FF + (r >> 1)] = value; -} - -__global__ void cpu_order_swiglu_kernel(float* gu, int pairs) { - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i >= pairs) return; - const float g = gu[i]; - // Accurate fp32 exponential; __expf's approximation would introduce an additional source of error. - // CPU/GPU libc last-bit differences are diagnosed separately by the micro, not hidden with FP64 here. - const float eg = expf(-g); - gu[i] = __fmul_rn(__fdiv_rn(g, __fadd_rn(1.0f, eg)), gu[pairs + i]); -} - -__global__ void cpu_order_quantize_kernel(const float* x, uint8_t* blocks, float* scales, - float* hx, int chunks) { - const int c = blockIdx.x * blockDim.x + threadIdx.x; - if (c >= chunks) return; - const float* xb = x + c * 32; - uint8_t* out = blocks + (size_t) c * 34; - float amax = 0.0f; - for (int j = 0; j < 32; ++j) amax = fmaxf(amax, fabsf(xb[j])); - const float s = amax > 0.0f ? __fdiv_rn(amax, 127.0f) : 0.0f; - const float inv = s > 0.0f ? __fdiv_rn(1.0f, s) : 0.0f; - scales[c] = s; - const uint16_t bits = __half_as_ushort(__float2half_rn(s)); - out[0] = (uint8_t) bits; - out[1] = (uint8_t) (bits >> 8); - int sum = 0; - for (int j = 0; j < 32; ++j) { - const float t = __fmul_rn(xb[j], inv); - int v = (int) __fadd_rn(t, t >= 0.0f ? 0.5f : -0.5f); - v = v < -127 ? -127 : (v > 127 ? 127 : v); - out[2 + j] = (uint8_t) (int8_t) v; - sum += v; - } - hx[c] = __fmul_rn(s, (float) sum); -} - -constexpr int THREADS = 256; - -void check(const char* who, void* stream) { - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "%s launch: %s\n", who, cudaGetErrorString(e)); - std::exit(1); - } - // Deliberately NOT synchronising for a non-null stream: this is called once per layer from a captured - // graph's worth of work, and `finish()`'s null-stream sync in `s_gemv.cu` is the pattern that made a whole - // round of measurements the driver's cost instead of the kernel's (Memory/ERRORS.md RC-7). - (void) stream; -} - -// The previous kernels stay selectable for A/B - `STRATA_OLD_GROUPED=1` in the environment, or -// `moe_grouped_select_old` (the parity test runs both in one process). The environment is read once, on first use; -// the choice is made at each launch, so a captured graph keeps the kernels it was captured with. -std::atomic g_select_old{-1}; -// Which kernels the last launch of an entry point used: 1 = new, 0 = previous, -1 = none since the last query. -std::atomic g_last_path{-1}; - -bool old_kernels() { - const int s = g_select_old.load(std::memory_order_relaxed); - if (s >= 0) return s != 0; - static const bool env = [] { - const char* e = std::getenv("STRATA_OLD_GROUPED"); - return e != nullptr && e[0] == '1'; - }(); - return env; -} - -// `STRATA_GROUPED_PAIR_MIN_HITS=N`: the per-hit path keeps the previous one-warp-per-row kernels below N hits of -// capacity. The new per-hit kernels launch half the warps (two rows each), so one hit's gate/up is 80 blocks - fewer -// than an RTX 5090's SMs - and whether that costs time at one to three hits is what `--bench` measures. Bitwise -// the same either way; default 0 (always the new kernels). Ignored while `moe_grouped_select_old` forces a choice. -long long pair_min_hits() { - if (g_select_old.load(std::memory_order_relaxed) >= 0) return 0; - static const long long n = [] { - const char* e = std::getenv("STRATA_GROUPED_PAIR_MIN_HITS"); - return e != nullptr ? std::atoll(e) : 0LL; - }(); - return n; -} - -// The new kernels read the activations as aligned words (`load_x_chunk`), so they need 4-byte aligned activation -// rows - the input's and the intermediate's in `scratch`; the per-hit ones also read a blob's codes as uint2, which -// needs an 8-byte aligned arena and slot size (the grouped kernels above already did). Anything else keeps the -// previous kernels rather than issuing a misaligned load. -bool new_grouped(const void* x_q8_0, const void* scratch) { - const bool fast = !old_kernels() && ((uintptr_t) x_q8_0 & 3) == 0 && ((uintptr_t) scratch & 3) == 0; - g_last_path.store(fast ? 1 : 0, std::memory_order_relaxed); - return fast; -} - -bool new_hit(const void* blob_base, long long blob_bytes, const void* x_q8_0, const void* scratch, long long cap) { - const bool fast = new_grouped(x_q8_0, scratch) && ((uintptr_t) blob_base & 7) == 0 && (blob_bytes & 7) == 0 && - cap >= pair_min_hits(); - g_last_path.store(fast ? 1 : 0, std::memory_order_relaxed); - return fast; -} - -// The per-hit path's two projections, previous or new kernels (one warp per row, or per pair of rows). -void launch_hit_gu(bool fast, const uint8_t* blob_base, const int32_t* slot_index, long long blob_bytes, - const uint8_t* x_q8_0, const float* x_scales, float* gate_up, long long cap, - const int32_t* d_count, const int32_t* dst_index, int tok_div, cudaStream_t cs) { - const int warps = THREADS / 32; - if (fast) { - const long long pairs = cap * (long long) FF; - gu_pair_kernel<<<(unsigned) ((pairs + warps - 1) / warps), THREADS, 0, cs>>>( - blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, (int) cap, d_count, dst_index, tok_div); - } else { - const long long rows = cap * 2LL * FF; - gu_kernel<<<(unsigned) ((rows + warps - 1) / warps), THREADS, 0, cs>>>( - blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, (int) cap, d_count, dst_index, tok_div); - } -} - -void launch_hit_down(bool fast, const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index, - long long blob_bytes, const uint8_t* h_q8_0, const float* h_scales, float* out, long long cap, - const int32_t* d_count, cudaStream_t cs) { - const int warps = THREADS / 32; - if (fast) { - const long long pairs = cap * (long long) (H / 2); - down_pair_kernel<<<(unsigned) ((pairs + warps - 1) / warps), THREADS, 0, cs>>>( - blob_base, slot_index, dst_index, blob_bytes, h_q8_0, h_scales, out, (int) cap, d_count); - } else { - const long long rows = cap * (long long) H; - down_kernel<<<(unsigned) ((rows + warps - 1) / warps), THREADS, 0, cs>>>( - blob_base, slot_index, dst_index, blob_bytes, h_q8_0, h_scales, out, (int) cap, d_count); - } -} - -} // namespace - -void moe_grouped_select_old(int old) { g_select_old.store(old < 0 ? -1 : (old != 0 ? 1 : 0)); } - -int moe_grouped_last_path() { return g_last_path.exchange(-1, std::memory_order_relaxed); } - -uint64_t moe_hit_grouped_scratch_bytes(int64_t n_hits, int64_t n_embd, int64_t n_ff) { - if (n_hits <= 0) return 0; - const uint64_t gu = (uint64_t) n_hits * (uint64_t) (2 * n_ff) * 4; - const uint64_t q8 = (uint64_t) n_hits * (uint64_t) (n_ff / 32) * 34; - // R4.2h: the fp32 scales for the INTERMEDIATE's own quantization, one per 32-element chunk per hit. - const uint64_t hs = (uint64_t) n_hits * (uint64_t) (n_ff / 32) * 4; - const uint64_t xh = (uint64_t) (n_embd / 32) * 4; - return ((gu + 15) & ~15ull) + ((q8 + 15) & ~15ull) + 2 * ((hs + 15) & ~15ull) + - ((xh + 15) & ~15ull); -} - -void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index, - int64_t n_hits, int64_t blob_bytes, const uint8_t* x_q8_0, void* scratch, float* out, - void* stream, const float* x_scales) { - if (n_hits <= 0) return; - cudaStream_t cs = (cudaStream_t) stream; - const bool fast = new_hit(blob_base, blob_bytes, x_q8_0, scratch, n_hits); - - const uint64_t gu_bytes = ((uint64_t) n_hits * (uint64_t) (2 * FF) * 4 + 15) & ~15ull; - const uint64_t q8_bytes = ((uint64_t) n_hits * (uint64_t) (FF / 32) * 34 + 15) & ~15ull; - float* gate_up = (float*) scratch; - uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes; - float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes); - - // 1. gate + up, one launch for every row of every hit. - { - launch_hit_gu(fast, blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, n_hits, nullptr, nullptr, - 0, cs); - check("moe_hit_grouped_s2/gu", stream); - } - // 2. silu(gate) * up. - { - const long long pairs = n_hits * (long long) FF; - const unsigned blocks = (unsigned) ((pairs + THREADS - 1) / THREADS); - swiglu_kernel<<>>(gate_up, pairs); - check("moe_hit_grouped_s2/swiglu", stream); - } - // 3. the intermediate's own contract, which is `ggml_mul_mat`'s rule and NOT a choice: the down weight is - // Q2_0, whose `vec_dot_type` is Q8_0. `gate_up` holds the pairs; the product went into the first half. - // **R4.2h: the CPU quantizes this intermediate into `a2` with fp32 scales too** (`expert.cpp:232`), so - // when the caller supplies `x_scales` the intermediate gets the CPU's contract as well - otherwise the - // down projection would keep the very disagreement the gate/up projection just had removed. - if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, n_hits * (int64_t) FF, stream); - else quantize_q8_0(gate_up, h_q8_0, n_hits * (int64_t) FF, stream); - // 4. down. - { - launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0, - x_scales != nullptr ? h_scales : nullptr, out, n_hits, nullptr, cs); - check("moe_hit_grouped_s2/down", stream); - } -} - -namespace { -// Plan v0.3 P4 token graph: which of this layer's routed experts are resident, decided ON THE DEVICE from the -// static residency row, so no host step sits between the ring and the hit kernels. One warp; k <= 32. -__global__ void hit_select_kernel(const int32_t* __restrict__ ids, const int32_t* __restrict__ res_row, int k, - int n_expert, int32_t* __restrict__ slot, int32_t* __restrict__ dst, - int32_t* __restrict__ count) { - const int lane = threadIdx.x; - int s = -1; - if (lane < k) { - const int e = ids[lane]; - if (e >= 0 && e < n_expert) s = res_row[e]; - } - const unsigned hit = __ballot_sync(0xffffffffu, s >= 0); - if (s >= 0) { - const int at = __popc(hit & ((1u << lane) - 1u)); - slot[at] = s; - dst[at] = lane; - } - if (lane == 0) *count = __popc(hit); -} - -// Plan v0.3 P6: the same for up to 128 routed entries (a verify window of T tokens x k): four warps, ballots -// compacted in entry order. -__global__ void hit_select_multi_kernel(const int32_t* __restrict__ ids, const int32_t* __restrict__ res_row, int n, - int n_expert, int32_t* __restrict__ slot, int32_t* __restrict__ dst, - int32_t* __restrict__ count) { - __shared__ int warp_count[4]; - const int i = threadIdx.x, lane = i & 31, warp = i >> 5; - int s = -1; - if (i < n) { - const int e = ids[i]; - if (e >= 0 && e < n_expert) s = res_row[e]; - } - const unsigned hit = __ballot_sync(0xffffffffu, s >= 0); - if (lane == 0) warp_count[warp] = __popc(hit); - __syncthreads(); - int before = 0; - for (int w = 0; w < warp; ++w) before += warp_count[w]; - if (s >= 0) { - const int at = before + __popc(hit & ((1u << lane) - 1u)); - slot[at] = s; - dst[at] = i; - } - if (i == 0) *count = warp_count[0] + warp_count[1] + warp_count[2] + warp_count[3]; -} - -__global__ void add_hits_kernel(float* __restrict__ parts, const float* __restrict__ hit_out, - const int32_t* __restrict__ dst, const int32_t* __restrict__ count, int n_embd) { - const int h = blockIdx.y; - if (h >= *count) return; - const size_t row = (size_t) dst[h] * (size_t) n_embd; - for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n_embd; i += gridDim.x * blockDim.x) - parts[row + i] += hit_out[row + i]; -} -} // namespace - -void moe_hit_select(const int32_t* ids, const int32_t* res_row, int k, int n_expert, int32_t* slot, int32_t* dst, - int32_t* count, void* stream) { - if (k < 1 || k > 32) { std::fprintf(stderr, "moe_hit_select: k must be 1..32\n"); std::exit(1); } - hit_select_kernel<<<1, 32, 0, (cudaStream_t) stream>>>(ids, res_row, k, n_expert, slot, dst, count); - check("moe_hit_select", stream); -} - -void moe_hit_grouped_s2_dev(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index, - const int32_t* d_count, int64_t cap, int64_t blob_bytes, const uint8_t* x_q8_0, - void* scratch, float* out, void* stream, const float* x_scales) { - if (cap <= 0) return; - cudaStream_t cs = (cudaStream_t) stream; - const bool fast = new_hit(blob_base, blob_bytes, x_q8_0, scratch, cap); - const uint64_t gu_bytes = ((uint64_t) cap * (uint64_t) (2 * FF) * 4 + 15) & ~15ull; - const uint64_t q8_bytes = ((uint64_t) cap * (uint64_t) (FF / 32) * 34 + 15) & ~15ull; - float* gate_up = (float*) scratch; - uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes; - float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes); - { - launch_hit_gu(fast, blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, cap, d_count, nullptr, 0, - cs); - check("moe_hit_grouped_s2_dev/gu", stream); - } - { - const long long pairs = cap * (long long) FF; - swiglu_kernel<<<(unsigned) ((pairs + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate_up, pairs); - check("moe_hit_grouped_s2_dev/swiglu", stream); - } - if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream); - else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream); - { - launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0, - x_scales != nullptr ? h_scales : nullptr, out, cap, d_count, cs); - check("moe_hit_grouped_s2_dev/down", stream); - } -} - -void moe_hit_select_multi(const int32_t* ids, const int32_t* res_row, int n, int n_expert, int32_t* slot, int32_t* dst, - int32_t* count, void* stream) { - if (n < 1 || n > 128) { std::fprintf(stderr, "moe_hit_select_multi: n must be 1..128\n"); std::exit(1); } - hit_select_multi_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(ids, res_row, n, n_expert, slot, dst, count); - check("moe_hit_select_multi", stream); -} - -void moe_hit_grouped_s2_multi(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index, - const int32_t* d_count, int64_t cap, int64_t blob_bytes, const uint8_t* x_q8_0, - const float* x_scales, int k_per_token, void* scratch, float* out, void* stream) { - if (cap <= 0) return; - cudaStream_t cs = (cudaStream_t) stream; - const bool fast = new_hit(blob_base, blob_bytes, x_q8_0, scratch, cap); - const uint64_t gu_bytes = ((uint64_t) cap * (uint64_t) (2 * FF) * 4 + 15) & ~15ull; - const uint64_t q8_bytes = ((uint64_t) cap * (uint64_t) (FF / 32) * 34 + 15) & ~15ull; - float* gate_up = (float*) scratch; - uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes; - float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes); - { - launch_hit_gu(fast, blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, cap, d_count, dst_index, - k_per_token, cs); - check("moe_hit_grouped_s2_multi/gu", stream); - } - { - const long long pairs = cap * (long long) FF; - swiglu_kernel<<<(unsigned) ((pairs + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate_up, pairs); - check("moe_hit_grouped_s2_multi/swiglu", stream); - } - if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream); - else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream); - { - launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0, - x_scales != nullptr ? h_scales : nullptr, out, cap, d_count, cs); - check("moe_hit_grouped_s2_multi/down", stream); - } -} - -namespace { -// Plan v0.3 P6: experts GROUPED - one blob pointer per group (a VRAM slot or a mapped host blob read over PCIe), -// every entry of the group (a token routed to that expert) computed from ONE read of each row. Per entry the -// arithmetic is `row_dot_s2_q8`'s, chunk by chunk in the same lane order, so every entry is bitwise the per-entry -// hit kernel's. -constexpr int GU_CHUNKS = (H / 32 + 31) / 32; // 3: chunks of a gate/up row per lane (80 chunks / 32 lanes) -constexpr int GMAX = 8; // entries per group (tokens routed to one expert in a window) -// a group holds one entry per token of the window routed to its expert, and the kernels below keep at -// most GMAX of them (`min(..., GMAX)`): a longer window would drop entries without a word. -static_assert(GMAX >= kVerifyMaxT, "a verify window's group can exceed GMAX entries"); -constexpr int GU_ROWS = 32; // gate/up rows per block: 4 per warp -constexpr int D_ROWS = 64; // down rows per block: 8 per warp - -// One activation chunk's contribution, `row_dot_s2_q8`'s inner body with the 32 int8 of the chunk already in -// aligned words: same dp4a sequence, same float expression, so the result is bitwise the per-entry kernel's. -__device__ __forceinline__ float chunk_dot(uint2 cb, const int* xw, float dw, float dx) { - const uint8_t* cbytes = (const uint8_t*) &cb; - int s = 0, hx = 0; - const int ones = 0x01010101; -#pragma unroll - for (int j = 0; j < 8; ++j) { - const unsigned cbyte = cbytes[j]; - const int cw = (int) ((cbyte & 3u) | (((cbyte >> 2) & 3u) << 8) | (((cbyte >> 4) & 3u) << 16) | - (((cbyte >> 6) & 3u) << 24)); - s = STRATA_DP4A(cw, xw[j], s); - hx = STRATA_DP4A(ones, xw[j], hx); - } - return dw * dx * (float) (s - hx); -} - -// Gate/up: a block = GU_ROWS rows of ONE group. The group's activations (each entry's token row of x_q8_0 and -// its fp32 scales) are staged once into shared memory as aligned words; each warp then walks its rows, loading -// each lane's code chunks once and dotting them with every entry. -__global__ void __launch_bounds__(256) gu_grouped_kernel(const unsigned long long* __restrict__ grp_ptr, - const int32_t* __restrict__ grp_start, - const int32_t* __restrict__ n_groups, - const int32_t* __restrict__ ent_tok, - const uint8_t* __restrict__ x_q8_0, - const float* __restrict__ x_scales, - float* __restrict__ gate_up, int cap_entries) { - __shared__ int xs_q[GMAX][H / 4]; // the entries' int8 activations as words (2560 B each) - __shared__ float xs_d[GMAX][H / 32]; - const int g = blockIdx.y; - if (g >= *n_groups) return; - const int e0 = grp_start[g], ne = min(grp_start[g + 1] - e0, GMAX); - const int t = threadIdx.x, lane = t & 31, warp = t >> 5; - for (int i = t; i < ne * (H / 32); i += blockDim.x) { - const int k = i / (H / 32), c = i - k * (H / 32); - const uint8_t* xb = x_q8_0 + (size_t) ent_tok[e0 + k] * (size_t) (H / 32) * 34 + (size_t) c * 34; - xs_d[k][c] = x_scales ? x_scales[(size_t) ent_tok[e0 + k] * (H / 32) + c] : f16_at(xb); - const int8_t* q = (const int8_t*) (xb + 2); -#pragma unroll - for (int w = 0; w < 8; ++w) { - int v; - memcpy(&v, q + 4 * w, 4); - xs_q[k][c * 8 + w] = v; - } - } - __syncthreads(); - const uint8_t* blob = (const uint8_t*) grp_ptr[g]; - const int row0 = blockIdx.x * GU_ROWS; - for (int rr = warp; rr < GU_ROWS; rr += 8) { - const int i = row0 + rr; - const uint8_t* codes = blob + (size_t) i * ROW_GU; - const uint8_t* scales = blob + O_GU_SCALES + (size_t) i * SC_GU * 2; - uint2 cb[GU_CHUNKS]; - float dw[GU_CHUNKS]; -#pragma unroll - for (int q = 0; q < GU_CHUNKS; ++q) { - const int c = lane + 32 * q; - if (c < H / 32) { - cb[q] = *(const uint2*) (codes + (size_t) c * 8); - dw[q] = f16_at(scales + (size_t) (c >> 1) * 2); - } - } - for (int k = 0; k < ne; ++k) { - float acc = 0.0f; -#pragma unroll - for (int q = 0; q < GU_CHUNKS; ++q) { - const int c = lane + 32 * q; - if (c >= H / 32) break; - acc += chunk_dot(cb[q], &xs_q[k][c * 8], dw[q], xs_d[k][c]); - } - const float sum = warp_sum(acc); - if (lane == 0) { - const int e = e0 + k, r = i >> 1; - const size_t base = (i & 1) ? ((size_t) cap_entries * FF + (size_t) e * FF) : ((size_t) e * FF); - gate_up[base + (size_t) r] = sum; - } - } - } -} - -// Down: a block = D_ROWS rows of ONE group; the entries' quantized intermediates staged once. A down row is 20 -// chunks, so lanes 0..19 each hold one chunk, as in the per-entry kernel. -__global__ void __launch_bounds__(256) down_grouped_kernel(const unsigned long long* __restrict__ grp_ptr, - const int32_t* __restrict__ grp_start, - const int32_t* __restrict__ n_groups, - const int32_t* __restrict__ ent_dst, - const uint8_t* __restrict__ h_q8_0, - const float* __restrict__ h_scales, - float* __restrict__ out) { - __shared__ int hs_q[GMAX][FF / 4]; - __shared__ float hs_d[GMAX][FF / 32]; - const int g = blockIdx.y; - if (g >= *n_groups) return; - const int e0 = grp_start[g], ne = min(grp_start[g + 1] - e0, GMAX); - const int t = threadIdx.x, lane = t & 31, warp = t >> 5; - for (int i = t; i < ne * (FF / 32); i += blockDim.x) { - const int k = i / (FF / 32), c = i - k * (FF / 32); - const uint8_t* xb = h_q8_0 + (size_t) (e0 + k) * (size_t) (FF / 32) * 34 + (size_t) c * 34; - hs_d[k][c] = h_scales ? h_scales[(size_t) (e0 + k) * (FF / 32) + c] : f16_at(xb); - const int8_t* q = (const int8_t*) (xb + 2); -#pragma unroll - for (int w = 0; w < 8; ++w) { - int v; - memcpy(&v, q + 4 * w, 4); - hs_q[k][c * 8 + w] = v; - } - } - __syncthreads(); - const uint8_t* blob = (const uint8_t*) grp_ptr[g]; - const int row0 = blockIdx.x * D_ROWS; - for (int rr = warp; rr < D_ROWS; rr += 8) { - const int r = row0 + rr; - const uint8_t* codes = blob + O_D_CODES + (size_t) r * ROW_D; - const uint8_t* scales = blob + O_D_SCALES + (size_t) r * SC_D * 2; - const int c = lane; - uint2 cb = make_uint2(0, 0); - float dw = 0.0f; - if (c < FF / 32) { - cb = *(const uint2*) (codes + (size_t) c * 8); - dw = f16_at(scales + (size_t) (c >> 1) * 2); - } - for (int k = 0; k < ne; ++k) { - float acc = 0.0f; - if (c < FF / 32) acc += chunk_dot(cb, &hs_q[k][c * 8], dw, hs_d[k][c]); - const float sum = warp_sum(acc); - if (lane == 0) out[(size_t) ent_dst[e0 + k] * H + r] = sum; - } - } -} - -// ---- The grouped kernels with the staged activations laid out for the reads. -// -// **THE LAYOUT ABOVE IS AN 8-WAY BANK CONFLICT.** `xs_q[k][c * 8 + j]` puts lane `L`'s word `j` at `8L + j`, so -// lanes `L, L + 4, L + 8, ...` share a bank on every one of the chunk's eight reads; and `chunk_dot` recomputes -// `hx`, which depends on the entry alone, for every row. Here the staging writes, once per (entry, chunk): -// -// xs_w[j][k * NC + c] word j of the regrouped chunk (`load_x_chunk`), so lanes read consecutive words -// xs_dh[k * NC + c] (dx, hx) - one 64-bit read per chunk instead of a float and eight `dp4a` -// -// Word-major, the staging writes are consecutive as well (the flat index `i` IS `k * NC + c`), so neither side -// conflicts and no padding is needed. Each warp takes its rows TWO at a time (adjacent rows: gate `r` and up `r`, -// or down rows `r, r + 1`), so every shared read serves both; the codes of both are expanded once per row, not -// once per entry. Per (row, entry) the lane's chunks, their order, the float expression and the shuffle -// reduction are the kernels' above, so every output is bitwise theirs. - -// Stages chunk `i = k * NC + c` of a group: its regrouped words at `xs_w[j * STRIDE + i]` and (dx, hx) at `xs_dh[i]`. -template -__device__ __forceinline__ void stage_chunk(const uint8_t* __restrict__ xb, float dx, int* xs_w, int2* xs_dh, int i) { - int X[8]; - const int hx = load_x_chunk(xb, X); -#pragma unroll - for (int j = 0; j < 8; ++j) xs_w[j * STRIDE + i] = X[j]; - xs_dh[i] = make_int2(__float_as_int(dx), hx); -} - -__global__ void __launch_bounds__(256) gu_grouped_t_kernel(const unsigned long long* __restrict__ grp_ptr, - const int32_t* __restrict__ grp_start, - const int32_t* __restrict__ n_groups, - const int32_t* __restrict__ ent_tok, - const uint8_t* __restrict__ x_q8_0, - const float* __restrict__ x_scales, - float* __restrict__ gate_up, int cap_entries) { - constexpr int NC = H / 32; - __shared__ int xs_w[8 * GMAX * NC]; // 20 KB: word j of entry k's chunk c at [j][k * NC + c] - __shared__ int2 xs_dh[GMAX * NC]; // 5 KB: (dx as bits, hx) - const int g = blockIdx.y; - if (g >= *n_groups) return; - const int e0 = grp_start[g], ne = min(grp_start[g + 1] - e0, GMAX); - const int t = threadIdx.x, lane = t & 31, warp = t >> 5; - for (int i = t; i < ne * NC; i += blockDim.x) { - const int k = i / NC, c = i - k * NC; - const int tok = ent_tok[e0 + k]; - const uint8_t* xb = x_q8_0 + (size_t) tok * (size_t) NC * 34 + (size_t) c * 34; - const float dx = x_scales ? x_scales[(size_t) tok * NC + c] : f16_ld(xb); - stage_chunk(xb, dx, xs_w, xs_dh, i); - } - __syncthreads(); - const uint8_t* blob = (const uint8_t*) grp_ptr[g]; - const int row0 = blockIdx.x * GU_ROWS; // even: a pair is always (gate r, up r) - for (int pp = warp; pp < GU_ROWS / 2; pp += 8) { - const int i = row0 + 2 * pp; - const uint8_t* codes = blob + (size_t) i * ROW_GU; - const uint8_t* scales = blob + O_GU_SCALES + (size_t) i * SC_GU * 2; - int m0[GU_CHUNKS][8], m1[GU_CHUNKS][8]; - float dw0[GU_CHUNKS], dw1[GU_CHUNKS]; -#pragma unroll - for (int q = 0; q < GU_CHUNKS; ++q) { - const int c = lane + 32 * q; - if (c < NC) { - expand_codes(*(const uint2*) (codes + (size_t) c * 8), m0[q]); - expand_codes(*(const uint2*) (codes + ROW_GU + (size_t) c * 8), m1[q]); - dw0[q] = f16_ld(scales + (size_t) (c >> 1) * 2); - dw1[q] = f16_ld(scales + SC_GU * 2 + (size_t) (c >> 1) * 2); - } - } - for (int k = 0; k < ne; ++k) { - float acc0 = 0.0f, acc1 = 0.0f; -#pragma unroll - for (int q = 0; q < GU_CHUNKS; ++q) { - const int c = lane + 32 * q; - if (c >= NC) break; - const int at = k * NC + c; - int X[8]; -#pragma unroll - for (int j = 0; j < 8; ++j) X[j] = xs_w[j * (GMAX * NC) + at]; - const int2 dh = xs_dh[at]; - const float dx = __int_as_float(dh.x); - acc0 += dw0[q] * dx * (float) (chunk_s(m0[q], X) - dh.y); - acc1 += dw1[q] * dx * (float) (chunk_s(m1[q], X) - dh.y); - } - const float s0 = warp_sum(acc0); - const float s1 = warp_sum(acc1); - if (lane == 0) { - const int e = e0 + k, r = i >> 1; - gate_up[(size_t) e * FF + (size_t) r] = s0; - gate_up[(size_t) cap_entries * FF + (size_t) e * FF + (size_t) r] = s1; - } - } - } -} - -__global__ void __launch_bounds__(256) down_grouped_t_kernel(const unsigned long long* __restrict__ grp_ptr, - const int32_t* __restrict__ grp_start, - const int32_t* __restrict__ n_groups, - const int32_t* __restrict__ ent_dst, - const uint8_t* __restrict__ h_q8_0, - const float* __restrict__ h_scales, - float* __restrict__ out) { - constexpr int NC = FF / 32; - __shared__ int hs_w[8 * GMAX * NC]; - __shared__ int2 hs_dh[GMAX * NC]; - const int g = blockIdx.y; - if (g >= *n_groups) return; - const int e0 = grp_start[g], ne = min(grp_start[g + 1] - e0, GMAX); - const int t = threadIdx.x, lane = t & 31, warp = t >> 5; - for (int i = t; i < ne * NC; i += blockDim.x) { - const int k = i / NC, c = i - k * NC; - const uint8_t* xb = h_q8_0 + (size_t) (e0 + k) * (size_t) NC * 34 + (size_t) c * 34; - const float dx = h_scales ? h_scales[(size_t) (e0 + k) * NC + c] : f16_ld(xb); - stage_chunk(xb, dx, hs_w, hs_dh, i); - } - __syncthreads(); - const uint8_t* blob = (const uint8_t*) grp_ptr[g]; - const int row0 = blockIdx.x * D_ROWS; - for (int pp = warp; pp < D_ROWS / 2; pp += 8) { - const int r = row0 + 2 * pp; - const uint8_t* codes = blob + O_D_CODES + (size_t) r * ROW_D; - const uint8_t* scales = blob + O_D_SCALES + (size_t) r * SC_D * 2; - const int c = lane; // lanes 0..19 hold one chunk each, as above - int m0[8], m1[8]; - float dw0 = 0.0f, dw1 = 0.0f; - if (c < NC) { - expand_codes(*(const uint2*) (codes + (size_t) c * 8), m0); - expand_codes(*(const uint2*) (codes + ROW_D + (size_t) c * 8), m1); - dw0 = f16_ld(scales + (size_t) (c >> 1) * 2); - dw1 = f16_ld(scales + SC_D * 2 + (size_t) (c >> 1) * 2); - } - for (int k = 0; k < ne; ++k) { - float acc0 = 0.0f, acc1 = 0.0f; - if (c < NC) { - const int at = k * NC + c; - int X[8]; -#pragma unroll - for (int j = 0; j < 8; ++j) X[j] = hs_w[j * (GMAX * NC) + at]; - const int2 dh = hs_dh[at]; - const float dx = __int_as_float(dh.x); - acc0 += dw0 * dx * (float) (chunk_s(m0, X) - dh.y); - acc1 += dw1 * dx * (float) (chunk_s(m1, X) - dh.y); - } - const float s0 = warp_sum(acc0); - const float s1 = warp_sum(acc1); - if (lane == 0) { - const size_t o = (size_t) ent_dst[e0 + k] * H + (size_t) r; - out[o] = s0; - out[o + 1] = s1; - } - } - } -} -} // namespace - -namespace { -// Plan v0.3 P6: groups built on the device when every expert is resident at `base + id * blob` (the MTP layer): -// one block of 128 threads, groups in first-appearance order, entries of a group in routing order. -__global__ void group_resident_kernel(const int32_t* __restrict__ ids, int n, int k_per_tok, const uint8_t* base, - long long blob, unsigned long long* __restrict__ grp_ptr, - int32_t* __restrict__ grp_start, int32_t* __restrict__ counts, - int32_t* __restrict__ ent_dst, int32_t* __restrict__ ent_tok) { - __shared__ int e_s[128], first_s[128], size_s[128], gidx_s[128], gstart_s[129]; - const int i = threadIdx.x; - const int e = i < n ? ids[i] : -1; - e_s[i] = e; - __syncthreads(); - int first = i, rank = 0, size = 0; - if (i < n) { - for (int j = 0; j < i; ++j) - if (e_s[j] == e) { if (first == i) first = j; ++rank; } - if (first == i) - for (int j = i; j < n; ++j) size += e_s[j] == e; - } - first_s[i] = first; - size_s[i] = (i < n && first == i) ? size : 0; - __syncthreads(); - if (i == 0) { - int gi = 0, acc = 0; - for (int j = 0; j < n; ++j) - if (first_s[j] == j) { - gidx_s[j] = gi; - gstart_s[gi] = acc; - grp_ptr[gi] = (unsigned long long) (base + (size_t) e_s[j] * (size_t) blob); - grp_start[gi] = acc; - acc += size_s[j]; - ++gi; - } - grp_start[gi] = acc; - counts[0] = gi; - counts[1] = acc; - } - __syncthreads(); - if (i < n) { - const int at = gstart_s[gidx_s[first]] + rank; - ent_dst[at] = i; - ent_tok[at] = i / k_per_tok; - } -} -} // namespace - -void moe_group_resident(const int32_t* ids, int n, int k_per_tok, const uint8_t* base, int64_t blob, - unsigned long long* grp_ptr, int32_t* grp_start, int32_t* counts, int32_t* ent_dst, - int32_t* ent_tok, void* stream) { - if (n < 1 || n > 128) { std::fprintf(stderr, "moe_group_resident: n must be 1..128\n"); std::exit(1); } - group_resident_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(ids, n, k_per_tok, base, (long long) blob, grp_ptr, - grp_start, counts, ent_dst, ent_tok); - check("moe_group_resident", stream); -} - -void moe_grouped_s2(const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups, - const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups, int64_t cap_entries, - const uint8_t* x_q8_0, const float* x_scales, void* scratch, float* out, void* stream) { - if (cap_groups <= 0 || cap_entries <= 0) return; - cudaStream_t cs = (cudaStream_t) stream; - const uint64_t gu_bytes = ((uint64_t) cap_entries * (uint64_t) (2 * FF) * 4 + 15) & ~15ull; - const uint64_t q8_bytes = ((uint64_t) cap_entries * (uint64_t) (FF / 32) * 34 + 15) & ~15ull; - float* gate_up = (float*) scratch; - uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes; - float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes); - const bool fast = new_grouped(x_q8_0, scratch); - { - const dim3 grid((unsigned) (2 * FF / GU_ROWS), (unsigned) cap_groups); - if (fast) - gu_grouped_t_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, x_q8_0, x_scales, - gate_up, (int) cap_entries); - else - gu_grouped_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, x_q8_0, x_scales, gate_up, - (int) cap_entries); - check("moe_grouped_s2/gu", stream); - } - { - const long long pairs = cap_entries * (long long) FF; - swiglu_kernel<<<(unsigned) ((pairs + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate_up, pairs); - check("moe_grouped_s2/swiglu", stream); - } - if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap_entries * (int64_t) FF, stream); - else quantize_q8_0(gate_up, h_q8_0, cap_entries * (int64_t) FF, stream); - { - const dim3 grid((unsigned) (H / D_ROWS), (unsigned) cap_groups); - const float* hs = x_scales != nullptr ? h_scales : nullptr; - if (fast) - down_grouped_t_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, h_q8_0, hs, out); - else - down_grouped_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, h_q8_0, hs, out); - check("moe_grouped_s2/down", stream); - } -} - -void moe_hit_add(float* parts, const float* hit_out, const int32_t* dst, const int32_t* count, int64_t cap, - int64_t n_embd, void* stream) { - if (cap <= 0) return; - const dim3 grid((unsigned) ((n_embd + 255) / 256 < 8 ? (n_embd + 255) / 256 : 8), (unsigned) cap); - add_hits_kernel<<>>(parts, hit_out, dst, count, (int) n_embd); - check("moe_hit_add", stream); -} - -void moe_hit_grouped_s2_cpu_order(const uint8_t* blob_base, const int32_t* slot_index, - const int32_t* dst_index, int64_t n_hits, int64_t blob_bytes, - const uint8_t* x_q8_0, void* scratch, float* out, void* stream, - const float* x_scales, float* gate_up_trace) { - if (n_hits <= 0) return; - if (x_scales == nullptr) { - std::fprintf(stderr, "moe_hit_grouped_s2_cpu_order requires fp32 activation scales\n"); - std::exit(1); - } - cudaStream_t cs = (cudaStream_t) stream; - const uint64_t gu_bytes = ((uint64_t) n_hits * 2 * FF * 4 + 15) & ~15ull; - const uint64_t q8_bytes = ((uint64_t) n_hits * (FF / 32) * 34 + 15) & ~15ull; - const uint64_t scale_bytes = ((uint64_t) n_hits * (FF / 32) * 4 + 15) & ~15ull; - float* gu = (float*) scratch; - uint8_t* hq = (uint8_t*) scratch + gu_bytes; - float* hs = (float*) (hq + q8_bytes); - float* hh = (float*) ((uint8_t*) hs + scale_bytes); - float* xh = (float*) ((uint8_t*) hh + scale_bytes); - activation_correction_kernel<<<(H / 32 + THREADS - 1) / THREADS, THREADS, 0, cs>>>( - x_q8_0, x_scales, xh, H / 32); - check("cpu_order/input_correction", stream); - const int rows_per_block = THREADS / 8; - cpu_order_projection_kernel<<<(unsigned) ((n_hits * 2 * FF + rows_per_block - 1) / rows_per_block), - THREADS, 0, cs>>>( - blob_base, slot_index, dst_index, blob_bytes, x_q8_0, x_scales, xh, gu, (int) n_hits); - check("cpu_order/gate_up", stream); - if (gate_up_trace != nullptr && - cudaMemcpyAsync(gate_up_trace, gu, (size_t) n_hits * 2 * FF * sizeof(float), - cudaMemcpyDeviceToDevice, cs) != cudaSuccess) { - std::fprintf(stderr, "cpu_order/gate_up_trace copy failed\n"); - std::exit(1); - } - cpu_order_swiglu_kernel<<<(unsigned) ((n_hits * FF + THREADS - 1) / THREADS), THREADS, 0, cs>>>( - gu, (int) n_hits * FF); - check("cpu_order/swiglu", stream); - cpu_order_quantize_kernel<<<(unsigned) ((n_hits * (FF / 32) + THREADS - 1) / THREADS), THREADS, 0, cs>>>( - gu, hq, hs, hh, (int) n_hits * (FF / 32)); - check("cpu_order/intermediate_quantize", stream); - cpu_order_projection_kernel<<<(unsigned) ((n_hits * H + rows_per_block - 1) / rows_per_block), - THREADS, 0, cs>>>( - blob_base, slot_index, dst_index, blob_bytes, hq, hs, hh, out, (int) n_hits); - check("cpu_order/down", stream); -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/s2_gemv.cu b/src/kernels/cuda/s2_gemv.cu deleted file mode 100644 index c1ff5cf..0000000 --- a/src/kernels/cuda/s2_gemv.cu +++ /dev/null @@ -1,63 +0,0 @@ -// src/kernels/cuda/s2_gemv.cu - P2.S2: the S2 GEMV, one thread per output row. -// -// Naive per the phase rule: dequantize on the fly, FP32 accumulation inside the row, no shared memory, no -// vector loads, no __ldg hints. Phase 3 changes this file; the parity test is what says whether a change is -// still right. -#include "strata/kernels/s2_gemv.hpp" - -#include -#include - -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int QK = 64; - -__global__ void s2_gemv_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes, - const float* __restrict__ scales, float* __restrict__ y, long long n_in, - long long n_out) { - const long long o = (long long) blockIdx.x * blockDim.x + threadIdx.x; - if (o >= n_out) return; - - const long long nb = n_in / QK; - const uint8_t* c = codes + o * nb * (QK / 4); - const float* s = scales + o * nb; - - float acc = 0.0f; - for (long long b = 0; b < nb; ++b) { - const float d = s[b]; - const uint8_t* cb = c + b * (QK / 4); - const uint16_t* xb = x + b * QK; - for (int j = 0; j < QK; ++j) { - // (code - 1) in the INTEGER domain, then the group scale, then the activation; the CPU reference - // below is written in the same order so the two differ only by floating-point contraction. - const int code = (cb[j >> 2] >> ((j & 3) * 2)) & 0x03; - acc += (float) (code - 1) * d * __half2float(__ushort_as_half(xb[j])); - } - } - y[o] = acc; -} - -} // namespace - -void s2_gemv(const uint16_t* x, const uint8_t* codes, const float* scales, float* y, int64_t n_in, - int64_t n_out) { - if (n_in <= 0 || n_out <= 0) return; - if (n_in % QK != 0) { - std::fprintf(stderr, "s2_gemv: n_in %lld is not a multiple of %d\n", (long long) n_in, QK); - std::exit(1); - } - const int threads = 128; - const long long blocks = (n_out + threads - 1) / threads; - s2_gemv_kernel<<<(unsigned) blocks, threads>>>(x, codes, scales, y, n_in, n_out); - const cudaError_t e = cudaDeviceSynchronize(); - if (e != cudaSuccess) { - std::fprintf(stderr, "s2_gemv: %s\n", cudaGetErrorString(e)); - std::exit(1); - } -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/s2_gemv_fast.cu b/src/kernels/cuda/s2_gemv_fast.cu deleted file mode 100644 index c83bd17..0000000 --- a/src/kernels/cuda/s2_gemv_fast.cu +++ /dev/null @@ -1,153 +0,0 @@ -// src/kernels/cuda/s2_gemv_fast.cu - two levers on the hottest kernel, BOTH MEASURED NEGATIVE OR NEUTRAL. -// -// *** THIS FILE IS NAMED "fast" AND IS NOT FASTER. DO NOT ADOPT IT AS THE FAST PATH. *** -// It is kept because the negative result is worth more than the file costs: it closes two plausible -// optimisations and it is the experiment that established the measurement floor. -// -// L5 got the S2 GEMV from 10.5 to 86.2 G weights/s by amortising the loads, and left the instruction-count -// argument confirmed but unfinished. Two further reductions were obvious, so both were built and measured: -// -// LEVER 1 - STAGE `x` IN SHARED MEMORY. `x` is n_in halves (5 KB at n_embd 2560) and every output row reads -// all of it, so the generic kernel issues n_out * n_in activation loads per GEMV. Staging it once per block -// measured WORSE in every single paired comparison (59-76 G w/s staged against 64-87 G w/s unstaged, across -// four sweep passes and three thread counts). The __syncthreads and the copy cost more than the L1/L2 hits -// they replace - the same 5 KB is already resident and already broadcast. -// -// LEVER 2 - A CONSTANT-MEMORY CODE TABLE. Turn the per-element shifts, masks and int-to-float convert into -// one broadcast `float4` load per four elements. Measured NEUTRAL: the two orderings swap between passes -// with no consistent winner. -// -// WHY THE NEGATIVE RESULT IS THE REAL FINDING: run-to-run variance on this machine is now ~20% within a -// single configuration (quads tpr=32 measured 64.3 to 79.5 G w/s across four passes), because `verify` holds -// ~97% of six CPU cores. **The noise floor now EXCEEDS the effect sizes being chased**, so further -// micro-optimisation of this kernel cannot be evaluated here and should wait for a quiet machine rather than -// produce more numbers that cannot be distinguished from noise. -// -// Both changes alter the summation order or the expression, so this kernel is checked against the naive -// reference like every other one - being faster is never a reason to be trusted, and being neutral is not -// either. -#include "strata/kernels/s_gemv.hpp" - -#include -#include - -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int QK_S2 = 64; -constexpr int MAX_SHARED_HALVES = 4096; // 8 KB of shared for x; n_embd 2560 fits with room - -// byte -> the four code values with the -1 bias already applied, in element order (bits 0,2,4,6). -__constant__ float c_codes[256][4]; - -bool g_lut_ready[64] = {}; // per device: __constant__ memory is per device (a layer split runs on two) - -void ensure_lut() { - int dev = 0; - cudaGetDevice(&dev); - if (dev < 0 || dev >= 64) dev = 0; - if (g_lut_ready[dev]) return; - float host[256][4]; - for (int b = 0; b < 256; ++b) { - for (int k = 0; k < 4; ++k) { - host[b][k] = (float) (((b >> (2 * k)) & 3) - 1); - } - } - const cudaError_t e = cudaMemcpyToSymbol(c_codes, host, sizeof(host)); - if (e != cudaSuccess) { - std::fprintf(stderr, "s2_gemv_fast: cudaMemcpyToSymbol failed: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - g_lut_ready[dev] = true; -} - -// One block per output row. `staged` says whether x was copied to shared, so the SAME kernel covers both -// configurations and the bench can measure them against each other with nothing else changed. -template -__global__ void s2_gemv_fast_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes, - const float* __restrict__ scales, float* __restrict__ y, long long n_in, - long long n_out, int threads_per_row) { - extern __shared__ float smem[]; - __half* sx = reinterpret_cast<__half*>(smem); // [threads_per_row, ...] partials live after - float* partial = smem + (STAGE_X ? (MAX_SHARED_HALVES / 2) : 0); - - const long long o = blockIdx.x; - if (o >= n_out) return; - const int tid = threadIdx.x; - - if (STAGE_X) { - const __half* xh = reinterpret_cast(x); - for (long long i = tid; i < n_in; i += threads_per_row) sx[i] = xh[i]; - __syncthreads(); - } - - const long long n_quads = n_in / 4; - const uint8_t* c = codes + o * n_quads; - const float* s = scales + o * (n_in / QK_S2); - - float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f; - for (long long q = tid; q < n_quads; q += threads_per_row) { - const uint8_t byte = c[q]; // ONE load for four codes - const float d = s[q >> 4]; // (q*4) >> 6 - const float4 cv = *reinterpret_cast(&c_codes[byte][0]); // one broadcast load - if (STAGE_X) { - const __half2 h01 = *reinterpret_cast(&sx[q * 4]); - const __half2 h23 = *reinterpret_cast(&sx[q * 4 + 2]); - a0 += cv.x * d * __low2float(h01); - a1 += cv.y * d * __high2float(h01); - a2 += cv.z * d * __low2float(h23); - a3 += cv.w * d * __high2float(h23); - } else { - const uint2 xw2 = *reinterpret_cast(x + q * 4); - const __half2 h01 = *reinterpret_cast(&xw2.x); - const __half2 h23 = *reinterpret_cast(&xw2.y); - a0 += cv.x * d * __low2float(h01); - a1 += cv.y * d * __high2float(h01); - a2 += cv.z * d * __low2float(h23); - a3 += cv.w * d * __high2float(h23); - } - } - partial[tid] = (a0 + a1) + (a2 + a3); - __syncthreads(); - for (int step = threads_per_row / 2; step > 0; step >>= 1) { - if (tid < step) partial[tid] += partial[tid + step]; - __syncthreads(); - } - if (tid == 0) y[o] = partial[0]; -} - -} // namespace - -void s2_gemv_fast(const uint16_t* x, const uint8_t* codes, const float* scales, float* y, int64_t n_in, - int64_t n_out, int threads_per_row, bool stage_x) { - if (n_in <= 0 || n_out <= 0) return; - if (n_in % 4 != 0 || n_in % QK_S2 != 0) { - std::fprintf(stderr, "s2_gemv_fast: n_in %lld must be a multiple of %d\n", (long long) n_in, QK_S2); - std::exit(1); - } - ensure_lut(); - if (stage_x && n_in > MAX_SHARED_HALVES) { - std::fprintf(stderr, "s2_gemv_fast: n_in %lld exceeds the %d-half shared staging limit\n", - (long long) n_in, MAX_SHARED_HALVES); - std::exit(1); - } - const size_t smem = (stage_x ? MAX_SHARED_HALVES * sizeof(__half) : 0) + - (size_t) threads_per_row * sizeof(float); - if (stage_x) { - s2_gemv_fast_kernel<<<(unsigned) n_out, threads_per_row, smem>>>(x, codes, scales, y, n_in, n_out, - threads_per_row); - } else { - s2_gemv_fast_kernel<<<(unsigned) n_out, threads_per_row, smem>>>(x, codes, scales, y, n_in, n_out, - threads_per_row); - } - const cudaError_t e = cudaDeviceSynchronize(); - if (e != cudaSuccess) { - std::fprintf(stderr, "s2_gemv_fast: %s\n", cudaGetErrorString(e)); - std::exit(1); - } -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/s2_gemv_q8.cu b/src/kernels/cuda/s2_gemv_q8.cu deleted file mode 100644 index 386f882..0000000 --- a/src/kernels/cuda/s2_gemv_q8.cu +++ /dev/null @@ -1,96 +0,0 @@ -// src/kernels/cuda/s2_gemv_q8.cu - the S2 GEMV that consumes Q8_0 ACTIVATIONS, as ggml does. -// -// THE GAP THIS CLOSES (round 186). `ggml_mul_mat` converts src1 - the ACTIVATION - to the weight's -// `vec_dot_type` before the dot product, and for Q2_0 that is Q8_0. The CUDA kernels built in rounds 166-177 -// take FP16 activations instead, while the CPU expert path (`bench/micro/cpu_s2.cpp`) already quantizes to int8 -// and uses `vpdpbusd`. Left that way the two paths compute different numbers for different experts of the SAME -// token, and the measured size of the difference is the activation contract itself: 0.9498% relative, against -// P2.S2's 1e-3 tolerance for FP16 paths. -// -// This is the CORRECTNESS version, not the fast one. It dequantizes each activation (`xq * dx`) inside the -// loop and does the same float arithmetic as `s2_gemv_quads`; the speed win available here is `__dp4a`, which -// turns four int8 MACs into one instruction, and that belongs to Phase 3 once the numerics are settled. The -// phase's rule is the simplest correct kernel first, and a dp4a version whose numerics are wrong would be -// indistinguishable from a fast one. -// -// Layout: activations are (n_in/32) ggml Q8_0 blocks, 34 bytes each - `fp16 d` then `int8 qs[32]` - produced by -// `strata::kernels::quantize_q8_0`. A quad of four elements lies inside one 32-element block, so the block -// scale is constant across it and is loaded once. -#include "strata/kernels/s2_gemv_q8.hpp" - -#include -#include - -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int QK_S2 = 64; -constexpr int QK8_0 = 32; - -__global__ void s2_gemv_q8_kernel(const uint8_t* __restrict__ act, const uint8_t* __restrict__ codes, - const float* __restrict__ scales, float* __restrict__ y, long long n_in, - long long n_out, int threads_per_row) { - extern __shared__ float partial[]; - const long long o = blockIdx.x; - if (o >= n_out) return; - const int tid = threadIdx.x; - - const long long n_quads = n_in / 4; - const uint8_t* c = codes + o * n_quads; // one code byte per quad - const float* s = scales + o * (n_in / QK_S2); - - float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f; - for (long long q = tid; q < n_quads; q += threads_per_row) { - const uint8_t byte = c[q]; - const float d = s[q >> 4]; // (q*4) >> 6, the S2 group index as a shift - // the activation quad: four int8 in one 32-element block, so one block scale - const long long ablk = (q * 4) / QK8_0; - const uint8_t* blk = act + ablk * 34; - const uint16_t dbits = (uint16_t) (blk[0] | (blk[1] << 8)); - const float dx = __half2float(__ushort_as_half(dbits)); - const int8_t* xq = reinterpret_cast(blk + 2); - const int off = (int) ((q * 4) % QK8_0); - - const float w0 = (float) ((int) (byte & 3) - 1) * d; - const float w1 = (float) ((int) ((byte >> 2) & 3) - 1) * d; - const float w2 = (float) ((int) ((byte >> 4) & 3) - 1) * d; - const float w3 = (float) ((int) ((byte >> 6) & 3) - 1) * d; - a0 += w0 * ((float) xq[off + 0] * dx); - a1 += w1 * ((float) xq[off + 1] * dx); - a2 += w2 * ((float) xq[off + 2] * dx); - a3 += w3 * ((float) xq[off + 3] * dx); - } - partial[tid] = (a0 + a1) + (a2 + a3); - __syncthreads(); - for (int step = threads_per_row / 2; step > 0; step >>= 1) { - if (tid < step) partial[tid] += partial[tid + step]; - __syncthreads(); - } - if (tid == 0) y[o] = partial[0]; -} - -} // namespace - -void s2_gemv_q8(const uint8_t* act, const uint8_t* codes, const float* scales, float* y, int64_t n_in, - int64_t n_out, int threads_per_row, void* stream) { - if (n_in <= 0 || n_out <= 0) return; - if (n_in % QK8_0 != 0 || n_in % QK_S2 != 0) { - std::fprintf(stderr, "s2_gemv_q8: n_in %lld must be a multiple of %d\n", (long long) n_in, QK_S2); - std::exit(1); - } - const size_t smem = (size_t) threads_per_row * sizeof(float); - s2_gemv_q8_kernel<<<(unsigned) n_out, threads_per_row, smem, (cudaStream_t) stream>>>(act, codes, scales, y, - n_in, n_out, - threads_per_row); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "s2_gemv_q8 launch: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - if (stream == nullptr) cudaDeviceSynchronize(); -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/s2_gemv_quads.cu b/src/kernels/cuda/s2_gemv_quads.cu deleted file mode 100644 index 7cb7cb4..0000000 --- a/src/kernels/cuda/s2_gemv_quads.cu +++ /dev/null @@ -1,93 +0,0 @@ -// src/kernels/cuda/s2_gemv_quads.cu - S2 with the code load amortised over four elements. -// -// THE HYPOTHESIS THIS TESTS. L4 measured 66 G weights/s = 0.55 weights/cycle/SM, and at an estimated ~13 -// instructions per weight that is ~7.2 instructions/cycle/SM against an SM's 4/cycle issue ceiling. Compute -// (0.4% of FP32 peak) and bandwidth (2%) are excluded by measurement and the dependency chain was excluded by -// experiment in L4, so instruction ISSUE is what remains. If that is right, cutting instructions per weight -// must move the rate; if the rate does not move, the hypothesis is wrong and that is worth knowing too. -// -// WHERE THE INSTRUCTIONS GO. For S2 four consecutive elements share ONE byte (element i at byte i/4, bits -// (i%4)*2), and four halves of x are eight contiguous bytes. The generic kernel walks with a thread stride -// and loads one byte and one half PER ELEMENT; a thread that takes a contiguous quad instead loads one byte -// and one 64-bit word for all four. Memory instructions per element drop from 2 to 0.5, and the address -// arithmetic is computed once rather than four times. -// -// S2 IS SPECIALISED DELIBERATELY: it is 31.64 GiB of the 38 GiB pack, so it is the kernel that matters. The -// generic `s_gemv_split` still serves S4 and S8. -#include "strata/kernels/s_gemv.hpp" - -#include -#include - -#include -#include - -namespace strata::kernels { -namespace { - -// QK = 64 elements per group; a quad of 4 elements is 1/16 of a group, so -// group = (quad * 4) >> 6 = quad >> 4 -constexpr int QK_S2 = 64; -constexpr int CODES_PER_BYTE_S2 = 4; - -__global__ void s2_gemv_quads_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes, - const float* __restrict__ scales, float* __restrict__ y, long long n_in, - long long n_out, int threads_per_row) { - extern __shared__ float partial[]; - const long long o = blockIdx.x; - if (o >= n_out) return; - const int tid = threadIdx.x; - - const long long n_quads = n_in / 4; - const uint8_t* c = codes + o * n_quads; // exactly one code byte per quad - const float* s = scales + o * (n_in / QK_S2); - - float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f; - for (long long q = tid; q < n_quads; q += threads_per_row) { - const uint8_t byte = c[q]; // ONE load for four codes - const float d = s[q >> 4]; // (q*4) >> 6, the group index as a shift - // ONE 64-bit load for four halves. `x` is 256-byte aligned and four halves are eight bytes, so - // this is an aligned uint2 - if it were not, the misaligned access would fault rather than be slow. - const uint2 xw = *reinterpret_cast(x + q * 4); - const __half2 h01 = *reinterpret_cast(&xw.x); - const __half2 h23 = *reinterpret_cast(&xw.y); - // the four codes, each carrying the -1 bias in the INTEGER domain; the scale is applied once per - // element here rather than once per group, which is the same expression the generic kernel uses - const float w0 = (float) ((int) (byte & 3) - 1) * d; - const float w1 = (float) ((int) ((byte >> 2) & 3) - 1) * d; - const float w2 = (float) ((int) ((byte >> 4) & 3) - 1) * d; - const float w3 = (float) ((int) ((byte >> 6) & 3) - 1) * d; - a0 += w0 * __low2float(h01); - a1 += w1 * __high2float(h01); - a2 += w2 * __low2float(h23); - a3 += w3 * __high2float(h23); - } - partial[tid] = (a0 + a1) + (a2 + a3); - __syncthreads(); - for (int step = threads_per_row / 2; step > 0; step >>= 1) { - if (tid < step) partial[tid] += partial[tid + step]; - __syncthreads(); - } - if (tid == 0) y[o] = partial[0]; -} - -} // namespace - -void s2_gemv_quads(const uint16_t* x, const uint8_t* codes, const float* scales, float* y, int64_t n_in, - int64_t n_out, int threads_per_row) { - if (n_in <= 0 || n_out <= 0) return; - if (n_in % 4 != 0) { - std::fprintf(stderr, "s2_gemv_quads: n_in %lld is not a multiple of 4\n", (long long) n_in); - std::exit(1); - } - const size_t smem = (size_t) threads_per_row * sizeof(float); - s2_gemv_quads_kernel<<<(unsigned) n_out, threads_per_row, smem>>>(x, codes, scales, y, n_in, n_out, - threads_per_row); - const cudaError_t e = cudaDeviceSynchronize(); - if (e != cudaSuccess) { - std::fprintf(stderr, "s2_gemv_quads: %s\n", cudaGetErrorString(e)); - std::exit(1); - } -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/s_gemv.cu b/src/kernels/cuda/s_gemv.cu deleted file mode 100644 index d0db178..0000000 --- a/src/kernels/cuda/s_gemv.cu +++ /dev/null @@ -1,694 +0,0 @@ -// src/kernels/cuda/s_gemv.cu - P2.S2: the S-family GEMV, one thread per output row. -// -// Naive per the phase rule: dequantize on the fly, FP32 accumulation inside the row, no shared memory, no -// vector loads. The kernel is templated on the code WIDTH (a compile-time property of the unpacking loop) and -// takes the rest of the per-type attributes as run-time arguments, because the manifest supplies them per -// tensor and a 13-way switch inside the inner loop would be the naive-but-wrong kind of naive. -#include "strata/kernels/s_gemv.hpp" - -#include -#include - -#include -#include - -namespace strata::kernels { -namespace { - -// `kvalues_iq4nl`: the non-linear codebook, verbatim from ggml-common.h / ggml-quants.c. -// -// **IT WAS IN `__constant__` FOR THE WRONG REASON, AND IT COST 2.12x.** The old comment justified constant -// memory with "every thread reads it and it is the same 16 values for the whole launch". That reasoning is -// exactly backwards: constant memory is fast when the access is UNIFORM - every lane reading the SAME address - -// and a NON-LINEAR codebook means every lane reads a DIFFERENT index, which is the pattern it handles worst. -// -// Measured on `attn_qkv` (IQ4_XS, 10240 x 2560), forcing the Affine codebook so that the memory traffic and the -// instruction count stay identical and only the table read is removed: -// -// codebook probe: IQ4NL 0.2032 ms Affine 0.0960 ms ratio 2.12x -// -// `decode_tbl` below reads a SHARED copy instead: 16 bytes loaded once per block, then an index into shared -// memory that costs at most a four-way bank conflict. The `__constant__` array stays as the source of it. -__constant__ signed char kIq4Nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, - 1, 13, 25, 38, 53, 69, 89, 113}; - -template -__device__ __forceinline__ float decode(int code, int bias, int codebook) { - if (codebook == (int) Codebook::Iq4Nl) return (float) kIq4Nl[code & 0x0F]; - return (float) (code + bias); // the bias is applied to the CODE, in the integer domain -} - -/// The same decode with the codebook in SHARED memory, which is what the hot kernels use - see the measurement -/// above. A divergent read of a 16-entry table is the one access pattern constant memory is worst at. -template -__device__ __forceinline__ float decode_tbl(int code, int bias, int codebook, const signed char* tbl) { - if (codebook == (int) Codebook::Iq4Nl) return (float) tbl[code & 0x0F]; - return (float) (code + bias); -} - -// ---- Q8_K ACTIVATIONS ---------------------------------------------------------------------------------- -// -// 292 bytes per 256 elements: `{ f32 d ; int8_t qs[256] ; int16_t bsums[16] }`. `bsums` is not read - it -// exists for ggml's AVX2 dot product - but the STRIDE includes it, so a buffer from `quantize_q8_K` passes -// straight in. -// -// The block's `d` sits at a 4-byte-aligned offset from the buffer base as long as the base is aligned, which -// `cudaMalloc` guarantees. -constexpr int Q8K_BLOCK_BYTES = 292; -constexpr int Q8K_BLOCK_ELEMS = 256; - -__device__ __forceinline__ float q8k_at(const uint8_t* __restrict__ x, long long i) { - const uint8_t* blk = x + (i / Q8K_BLOCK_ELEMS) * Q8K_BLOCK_BYTES; - const float d = __ldg((const float*) blk); - const int8_t q = ((const int8_t*) (blk + 4))[i % Q8K_BLOCK_ELEMS]; - return d * (float) q; -} - -/// **THE Q8_0 ACTIVATION**, which is what the LEGACY block formats want: `block_q8_0` is `{fp16 d; int8 qs[32]}`, -/// 34 bytes per 32 elements, produced by `quantize_q8_0`. -/// -/// THE ENGINE HAD NO GEMV FOR THIS, and it was the last activation-contract gap (LEDGER L54). It was described -/// as "Q8_K is not implemented", which is not the situation: `ffn_down_shexp` is IQ4_NL/Q4_0/Q5_0/Q8_0 in EVERY -/// layer, whose `vec_dot_type` is Q8_0 - and its `n_in` is 640, which is not a multiple of 256, so **Q8_K is -/// STRUCTURALLY IMPOSSIBLE for it rather than merely absent**. Every other legacy tensor in the pack is Q2_0, -/// whose attributes happen to be S2's, which is how the S2-only kernel covered them and the hole stayed hidden. -constexpr int Q8_0_BLOCK_BYTES = 34; -constexpr int Q8_0_BLOCK_ELEMS = 32; - -__device__ __forceinline__ float q8_0_at(const uint8_t* __restrict__ x, long long i) { - const uint8_t* blk = x + (i / Q8_0_BLOCK_ELEMS) * Q8_0_BLOCK_BYTES; - // a `uint16_t` needs 2-byte alignment and the stride is 34, so every block's `d` is aligned - const float d = __half2float(__ushort_as_half(*(const uint16_t*) blk)); - const int8_t q = ((const int8_t*) (blk + 2))[i % Q8_0_BLOCK_ELEMS]; - return d * (float) q; -} - -/// The Q8_K path, with the SAME weight decode as `s_gemv_kernel` and a different activation loader. The two -/// are separate kernels rather than one templated on the activation kind because the activation POINTER TYPE -/// differs (`uint16_t*` vs `uint8_t*`) and a templated pointer would need a cast at every call site - which is -/// where a wrong stride would hide. -template -__global__ void s_gemv_q8k_kernel(const uint8_t* __restrict__ x, const uint8_t* __restrict__ codes, - const float* __restrict__ scales, const float* __restrict__ offset, - float* __restrict__ y, long long n_in, long long n_out, int bias, - int codebook, int group_elems, int has_offset) { - // THE CODEBOOK, IN SHARED MEMORY - 16 bytes, loaded once per block. See the note on `kIq4Nl`. - // THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN: `o` is per-THREAD in this kernel, so a thread - // that returned first would leave the others waiting at a barrier it never reaches. - __shared__ signed char s_iq4nl[16]; - if (threadIdx.x < 16) s_iq4nl[threadIdx.x] = kIq4Nl[threadIdx.x]; - __syncthreads(); - const long long o = (long long) blockIdx.x * blockDim.x + threadIdx.x; - if (o >= n_out) return; - - constexpr int PER_BYTE = 8 / CODE_BITS; - const long long n_groups = n_in / group_elems; - const long long codes_per_row = n_in / PER_BYTE; - const uint8_t* c = codes + o * codes_per_row; - const float* s = scales + o * n_groups; - const float* off = has_offset ? offset + o * n_groups : nullptr; - - float acc = 0.0f; - for (long long g = 0; g < n_groups; ++g) { - const float d = s[g]; - const float b = off ? off[g] : 0.0f; - const long long base = g * (long long) group_elems; - for (int j = 0; j < group_elems; ++j) { - const long long i = base + j; - const int code = (c[i / PER_BYTE] >> ((int) (i % PER_BYTE) * CODE_BITS)) & ((1 << CODE_BITS) - 1); - // The offset belongs to the WEIGHT and is applied before the activation multiply - see the note in - // `s_gemv_kernel`, where writing it the other way rounded differently and only the Q4_K case could - // tell. - const float w = decode_tbl(code, bias, codebook, s_iq4nl) * d + b; - acc += w * q8k_at(x, i); - } - } - y[o] = acc; -} - -/// One warp per output row, lanes striding the reduction axis: for a fixed `i` consecutive lanes read -/// consecutive activations, which is the coalescing that matters once the output width is small. -/// -/// **`group_shift`, NOT `group_elems`, AND IT COSTS A DIVISION PER ELEMENT IF YOU GET IT WRONG.** The -/// sibling fp16 kernel was given this treatment ("a 64-bit integer division on this hardware is a long -/// instruction sequence - one per element, in the hottest loop in the engine") and THIS one was not: it kept -/// `i / group_elems` with `group_elems` a RUNTIME value, once per element, in the kernel that carries most of -/// the model's weight bytes. Every group size the format defines is a power of two, so the divisor is passed -/// as its logarithm and the division becomes a shift; the host refuses a non-power-of-two group rather than -/// computing a wrong index. -/// ONE KERNEL FOR BOTH QUANTIZED ACTIVATIONS, templated on which block format `x` holds. A second copy with a -/// different loader would be a second thing to get wrong, and the only difference IS the loader - the weight -/// decode, the quad loop, the shared codebook and the reduction are identical. -template -__global__ void s_gemv_q8_split_kernel(const uint8_t* __restrict__ x, const uint8_t* __restrict__ codes, - const float* __restrict__ scales, const float* __restrict__ offset, - float* __restrict__ y, long long n_in, long long n_out, int bias, - int codebook, int group_shift, int has_offset) { - constexpr int PER_BYTE = 8 / CODE_BITS; - const int warps_per_block = (int) (blockDim.x >> 5); - const long long o = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5); - const int lane = threadIdx.x & 31; - - // THE CODEBOOK, IN SHARED MEMORY. 16 bytes, loaded once per block by the first 16 threads, instead of a - // divergent constant read per element - measured at 2.12x of this whole kernel (see the note on `kIq4Nl`). - // - // THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN, as in `s_gemv_q8k_kernel`. The return used to - // sit above them, so whenever `n_out % 8 != 0` the last block's surplus warps left before a barrier the - // others still waited at - undefined behaviour that every shape in the pack (a multiple of 8) happened to - // avoid. `o` is per-WARP, so the return below keeps whole warps together and the shuffle reduction's - // full mask stays valid. - __shared__ signed char s_iq4nl[16]; - if (threadIdx.x < 16) s_iq4nl[threadIdx.x] = kIq4Nl[threadIdx.x]; - __syncthreads(); - if (o >= n_out) return; - - const long long n_groups = n_in >> group_shift; - const long long codes_per_row = n_in / PER_BYTE; - const uint8_t* c = codes + o * codes_per_row; - const float* s = scales + o * n_groups; - const float* off = has_offset ? offset + o * n_groups : nullptr; - - float acc0 = 0.0f, acc1 = 0.0f, acc2 = 0.0f, acc3 = 0.0f; - float acc4 = 0.0f, acc5 = 0.0f, acc6 = 0.0f, acc7 = 0.0f; - float acc8 = 0.0f, acc9 = 0.0f, acc10 = 0.0f, acc11 = 0.0f; - float acc12 = 0.0f, acc13 = 0.0f, acc14 = 0.0f, acc15 = 0.0f; - // ---- EIGHT CONSECUTIVE ELEMENTS PER LANE, from TWO code loads and ONE scale. - // - // **THIS IS THE EXPERIMENT THE `#pragma unroll` NOTE BELOW LEFT OPEN**, and the note said what it would - // be: "Widening QE to 8 or 16 changes the LOADS THEMSELVES - two or four independent 16-bit words per - // lane - which an unroll cannot do because the extraction code is written for exactly four codes." So a - // lane now takes a double quad: two code words issued before either is consumed, which is what raises the - // bytes in flight. The scale and offset are still ONE load, because eight consecutive elements lie in one - // group whenever `group_elems % 8 == 0` - the launcher asserts that, and every group size this format - // defines (16, 32, 64) satisfies it. - // - // The loop used to take `i = lane, lane+32, ...` - a STRIDE, chosen so consecutive lanes read consecutive - // activations - and paid a code load, a shift-and-mask, and a scale load FOR EVERY ELEMENT. But four - // consecutive elements share one code word (1, 2 or 4 bytes depending on width) and lie in one group, - // because every group size this format defines is a multiple of four. So a lane takes a QUAD: - // - // one code load instead of four - // one scale load instead of four - // one shift per element instead of a divide, a modulo and a shift - // - // THE BIT ORDER IS THE SAME ONE, verified for all three widths: element `i+k` is bits - // `[k*CODE_BITS, (k+1)*CODE_BITS)` of the little-endian word at byte `i/PER_BYTE`, which is what the old - // `(c[e/PER_BYTE] >> ((e%PER_BYTE)*CODE_BITS)) & MASK` computed one element at a time. - // - // THE SUMMATION ORDER CHANGES, which is why `s_gemv_parity` and `s_gemv_q8k_parity` carry tolerances and - // compare against the naive kernel - they are the guard for this, and they are the reason it is safe to do. - constexpr int QE = 16; - // BYTES PER FOUR-CODE WORD, not per octet. The two are easy to confuse and the first version of this - // did: it branched on the octet's total width and so read a uint32 for S4 (whose four codes are a - // uint16) and single bytes for S8 (whose four codes are a uint32). `s_gemv_q8k_parity` failed on - // exactly that, which is what it is for. - constexpr int QW = 4 * CODE_BITS / 8; // 1 for S2, 2 for S4, 4 for S8 - constexpr unsigned MASK = (1u << CODE_BITS) - 1u; - long long i = (long long) lane * QE; - // **`#pragma unroll 4` WAS TRIED HERE AND DID NOTHING.** Measured: 184.6 -> 183.9 GB/s at n_out 10240, - // with `s_gemv_parity` and `s_gemv_q8k_parity` both still clean. The hypothesis it was testing is L93 - - // that this kernel's flat ~6 ns per output row is a bytes-in-flight limit, one code load and one scale - // load per lane-iteration with only 20 iterations. A 4x unroll issues four of each before the first is - // consumed, so either the compiler was already doing it or **the limit is not instruction scheduling.** - // Removed rather than kept, because a hint that does not change the timing is a claim that is not true. - // - // What it does NOT rule out is the structural version of the same idea: QE is 4, so a lane consumes ONE - // 2-byte code word per iteration. Widening QE to 8 or 16 changes the LOADS THEMSELVES - two or four - // independent 16-bit words per lane - which an unroll cannot do because the extraction code is written for - // exactly four codes. That is the experiment that would settle it, and it is not this one. - for (; i + QE <= n_in; i += 32 * QE) { - const long long g = i >> group_shift; // the whole octet is in one group: group_elems % 8 == 0 - const float d = s[g]; - const float b = off ? off[g] : 0.0f; - const uint8_t* cp = c + i / PER_BYTE; - unsigned v, v2, v3, v4; - if (QW == 1) { v = cp[0]; v2 = cp[1]; v3 = cp[2]; v4 = cp[3]; } - else if (QW == 2) { v = *(const uint16_t*) cp; v2 = *(const uint16_t*) (cp + 2); - v3 = *(const uint16_t*) (cp + 4); v4 = *(const uint16_t*) (cp + 6); } - else { v = *(const uint32_t*) cp; v2 = *(const uint32_t*) (cp + 4); - v3 = *(const uint32_t*) (cp + 8); v4 = *(const uint32_t*) (cp + 12); } - // ---- THE ACTIVATION BLOCK IS HOISTED OUT OF THE SIXTEEN ELEMENTS, AND THAT WAS THE KERNEL'S COST. - // - // `q8k_at(x, i + k)` computes `(i + k) / 256` and `(i + k) % 256` on EVERY call: a 64-bit integer - // division AND modulo per element, sixteen times per lane-iteration. A 64-bit division on a GPU is a - // software routine of roughly a hundred cycles, and the compiler cannot strength-reduce it because it - // cannot prove `(i + k) / 256 == i / 256` without knowing `i % 256`. - // - // But `QE` is 16, `Q8K_BLOCK_ELEMS` is 256 and `Q8_0_BLOCK_ELEMS` is 32, and the loop advances `i` by - // `32 * QE`. So `i % 256` and `i % 32` are ALWAYS multiples of 16 - which means all QE elements of one - // lane-iteration lie inside ONE block, for either activation kind. One division and one modulo per - // iteration replace sixteen of each, and the sixteen activations become sixteen consecutive int8 loads - // from a pointer computed once. - // - // This is exact, not an approximation: `xi + QE <= blk_elems` holds for every reachable `xi`, so no - // lane-iteration can straddle a block boundary. The tail loop below still uses the accessors because - // its elements do not share a block, and it runs at most once per lane. - const int blk_elems = Q8K ? Q8K_BLOCK_ELEMS : Q8_0_BLOCK_ELEMS; - const uint8_t* xb = x + (i / blk_elems) * (Q8K ? Q8K_BLOCK_BYTES : Q8_0_BLOCK_BYTES); - const int xi = (int) (i % blk_elems); - const float xd = Q8K ? __ldg((const float*) xb) - : __half2float(__ushort_as_half(*(const uint16_t*) xb)); - const int8_t* xq = (const int8_t*) (xb + (Q8K ? 4 : 2)) + xi; - - const float w0 = decode_tbl((int) (v & MASK), bias, codebook, s_iq4nl) * d + b; - const float w1 = decode_tbl((int) ((v >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b; - const float w2 = decode_tbl((int) ((v >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b; - const float w3 = decode_tbl((int) ((v >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b; - const float w4 = decode_tbl((int) (v2 & MASK), bias, codebook, s_iq4nl) * d + b; - const float w5 = decode_tbl((int) ((v2 >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b; - const float w6 = decode_tbl((int) ((v2 >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b; - const float w7 = decode_tbl((int) ((v2 >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b; - acc0 += w0 * (xd * (float) xq[0]); - acc1 += w1 * (xd * (float) xq[1]); - acc2 += w2 * (xd * (float) xq[2]); - acc3 += w3 * (xd * (float) xq[3]); - acc4 += w4 * (xd * (float) xq[4]); - acc5 += w5 * (xd * (float) xq[5]); - acc6 += w6 * (xd * (float) xq[6]); - acc7 += w7 * (xd * (float) xq[7]); - const float w8 = decode_tbl((int) (v3 & MASK), bias, codebook, s_iq4nl) * d + b; - const float w9 = decode_tbl((int) ((v3 >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b; - const float w10 = decode_tbl((int) ((v3 >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b; - const float w11 = decode_tbl((int) ((v3 >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b; - const float w12 = decode_tbl((int) (v4 & MASK), bias, codebook, s_iq4nl) * d + b; - const float w13 = decode_tbl((int) ((v4 >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b; - const float w14 = decode_tbl((int) ((v4 >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b; - const float w15 = decode_tbl((int) ((v4 >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b; - acc8 += w8 * (xd * (float) xq[8]); - acc9 += w9 * (xd * (float) xq[9]); - acc10 += w10 * (xd * (float) xq[10]); - acc11 += w11 * (xd * (float) xq[11]); - acc12 += w12 * (xd * (float) xq[12]); - acc13 += w13 * (xd * (float) xq[13]); - acc14 += w14 * (xd * (float) xq[14]); - acc15 += w15 * (xd * (float) xq[15]); - } - // the last, partial quad - at most one per lane - for (; i < n_in; i += 32 * QE) { - for (int k = 0; k < QE && i + k < n_in; ++k) { - const long long e = i + k; - const long long g = e >> group_shift; - const int code = (c[e / PER_BYTE] >> ((int) (e % PER_BYTE) * CODE_BITS)) & MASK; - acc0 += (decode_tbl(code, bias, codebook, s_iq4nl) * s[g] + (off ? off[g] : 0.0f)) * (Q8K ? q8k_at(x, e) : q8_0_at(x, e)); - } - } - float acc = (((acc0 + acc1) + (acc2 + acc3)) + ((acc4 + acc5) + (acc6 + acc7))) + - (((acc8 + acc9) + (acc10 + acc11)) + ((acc12 + acc13) + (acc14 + acc15))); - for (int step = 16; step > 0; step >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, step); - if (lane == 0) y[o] = acc; -} - -template -__global__ void s_gemv_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes, - const float* __restrict__ scales, const float* __restrict__ offset, - float* __restrict__ y, long long n_in, long long n_out, int bias, int codebook, - int group_elems, int has_offset) { - // THE CODEBOOK, IN SHARED MEMORY - 16 bytes, loaded once per block. See the note on `kIq4Nl`. - // THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN: `o` is per-THREAD in this kernel, so a thread - // that returned first would leave the others waiting at a barrier it never reaches. - __shared__ signed char s_iq4nl[16]; - if (threadIdx.x < 16) s_iq4nl[threadIdx.x] = kIq4Nl[threadIdx.x]; - __syncthreads(); - const long long o = (long long) blockIdx.x * blockDim.x + threadIdx.x; - if (o >= n_out) return; - - constexpr int PER_BYTE = 8 / CODE_BITS; - const long long n_groups = n_in / group_elems; - const long long codes_per_row = n_in / PER_BYTE; - const uint8_t* c = codes + o * codes_per_row; - const float* s = scales + o * n_groups; - const float* off = has_offset ? offset + o * n_groups : nullptr; - - float acc = 0.0f; - for (long long g = 0; g < n_groups; ++g) { - const float d = s[g]; - const float b = off ? off[g] : 0.0f; - const long long base = g * (long long) group_elems; - for (int j = 0; j < group_elems; ++j) { - const long long i = base + j; - const int code = (c[i / PER_BYTE] >> ((int) (i % PER_BYTE) * CODE_BITS)) & ((1 << CODE_BITS) - 1); - // The offset belongs to the WEIGHT, so it is applied to the decoded value BEFORE the activation - // multiply: `w = code*scale + offset; acc += w * x`. Writing `acc += code*scale*x + offset*x` - // computes a mathematically equal expression that ROUNDS DIFFERENTLY, because it performs two - // multiplications and an addition where this performs one of each. The no-offset types cannot - // tell the difference - which is why this was wrong until the Q4_K case was added. - const float w = decode_tbl(code, bias, codebook, s_iq4nl) * d + b; - acc += w * __half2float(__ushort_as_half(x[i])); - } - } - y[o] = acc; -} - -} // namespace - -void s_gemv(const uint16_t* x, const uint8_t* codes, const float* scales, const float* offset, float* y, - int64_t n_in, int64_t n_out, const SForm& form) { - if (n_in <= 0 || n_out <= 0) return; - if (form.group_elems <= 0 || n_in % form.group_elems != 0) { - std::fprintf(stderr, "s_gemv: n_in %lld is not a multiple of group_elems %d\n", (long long) n_in, - form.group_elems); - std::exit(1); - } - if (form.has_offset && offset == nullptr) { - std::fprintf(stderr, "s_gemv: form says has_offset but offset is null\n"); - std::exit(1); - } - const int threads = 128; - const long long blocks = (n_out + threads - 1) / threads; - const int cb = (int) form.codebook; - switch (form.code_bits) { - case 2: - s_gemv_kernel<2><<<(unsigned) blocks, threads>>>(x, codes, scales, offset, y, n_in, n_out, - form.code_bias, cb, form.group_elems, - form.has_offset ? 1 : 0); - break; - case 4: - s_gemv_kernel<4><<<(unsigned) blocks, threads>>>(x, codes, scales, offset, y, n_in, n_out, - form.code_bias, cb, form.group_elems, - form.has_offset ? 1 : 0); - break; - case 8: - s_gemv_kernel<8><<<(unsigned) blocks, threads>>>(x, codes, scales, offset, y, n_in, n_out, - form.code_bias, cb, form.group_elems, - form.has_offset ? 1 : 0); - break; - default: - std::fprintf(stderr, "s_gemv: unsupported code_bits %d\n", form.code_bits); - std::exit(1); - } - const cudaError_t e = cudaDeviceSynchronize(); - if (e != cudaSuccess) { - std::fprintf(stderr, "s_gemv: %s\n", cudaGetErrorString(e)); - std::exit(1); - } -} - -namespace { - -// One BLOCK per output row, `threads_per_row` threads splitting it. Parallelism becomes -// n_out * threads_per_row instead of n_out, which is the whole point: gate/up is [2560 x 640] and 640 threads -// cannot fill 48 SMs. -// -// The reduction is a fixed tree over shared memory rather than atomics, so the result is DETERMINISTIC for a -// given threads_per_row - a race would make the parity test flaky rather than wrong, which is the worst kind -// of failing test. -// NOTE ON `g = e >> group_shift`. The group index was `e / group_elems` with `group_elems` a RUNTIME value, -// and a 64-bit integer division on this hardware is a long instruction sequence - one per element, in the -// hottest loop in the engine. Every group size this format defines is a POWER OF TWO (16, 32, 64), so the -// divisor is passed as its logarithm and the division becomes a shift. The host wrapper refuses a -// non-power-of-two group rather than silently computing a wrong index. -template -__global__ void s_gemv_split_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes, - const float* __restrict__ scales, const float* __restrict__ offset, - float* __restrict__ y, long long n_in, long long n_out, int bias, - int codebook, int group_elems, int group_shift, int has_offset, - int threads_per_row) { - extern __shared__ float partial[]; - // THE CODEBOOK, IN SHARED MEMORY - 16 bytes, loaded once per block. See the note on `kIq4Nl`. - // THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN: `o` is per-THREAD in this kernel, so a thread - // that returned first would leave the others waiting at a barrier it never reaches. - __shared__ signed char s_iq4nl[16]; - if (threadIdx.x < 16) s_iq4nl[threadIdx.x] = kIq4Nl[threadIdx.x]; - __syncthreads(); - const long long o = blockIdx.x; - if (o >= n_out) return; - const int tid = threadIdx.x; - - constexpr int PER_BYTE = 8 / CODE_BITS; - const long long n_groups = n_in / group_elems; - const uint8_t* c = codes + o * (n_in / PER_BYTE); - const float* s = scales + o * n_groups; - const float* off = has_offset ? offset + o * n_groups : nullptr; - - // FOUR ACCUMULATORS, NOT ONE. L2 measured this kernel at 0.4% of FP32 peak and 2.1% of bandwidth, so - // neither limit is the constraint - the constraint is the DEPENDENCY CHAIN: a single `acc += ...` serialises - // every FMA behind the previous one's latency (4-6 cycles each, ~1 per 4 cycles achieved), so the SM sits - // idle. Four independent accumulators let the scheduler keep four FMAs in flight, and the loop is - // unrolled by four so the four chains are interleaved. The summation ORDER changes, which is why the - // parity test carries a tolerance and why this kernel's output is checked against the naive one. - // FOUR CONSECUTIVE ELEMENTS PER THREAD, from ONE code load and ONE scale - the same transformation the - // Q8_K kernel got, for the same reason and with the same guard (`s_gemv_parity`). See the long note there - // for the bit order, which is unchanged, and for why the group size is passed as a shift. - // - // THIS KERNEL IS THE ONE `attn_output` AND `shared_expert` USE, so the fix has to exist in both or half the - // model keeps the old instruction count. - constexpr int QE = 4; - constexpr int QB = QE * CODE_BITS / 8; // 1 for S2, 2 for S4, 4 for S8 - constexpr unsigned MASK = (1u << CODE_BITS) - 1u; - float acc0 = 0.0f, acc1 = 0.0f, acc2 = 0.0f, acc3 = 0.0f; - long long i = (long long) tid * QE; - for (; i + QE <= n_in; i += (long long) threads_per_row * QE) { - const long long g = i >> group_shift; - const float d = s[g]; - const float b = off ? off[g] : 0.0f; - const uint8_t* cp = c + i / PER_BYTE; - unsigned v; - if (QB == 1) v = cp[0]; - else if (QB == 2) v = *(const uint16_t*) cp; - else v = *(const uint32_t*) cp; - // four halves in ONE 8-byte load; `i` is a multiple of four, so `x + i` is 8-byte aligned - const float2 f01 = __half22float2(*reinterpret_cast(x + i)); - const float2 f23 = __half22float2(*reinterpret_cast(x + i + 2)); - acc0 += (decode_tbl((int) (v & MASK), bias, codebook, s_iq4nl) * d + b) * f01.x; - acc1 += (decode_tbl((int) ((v >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b) * f01.y; - acc2 += (decode_tbl((int) ((v >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b) * f23.x; - acc3 += (decode_tbl((int) ((v >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b) * f23.y; - } - // the last, partial quad - at most one per thread - for (; i < n_in; i += (long long) threads_per_row * QE) { - for (int k = 0; k < QE && i + k < n_in; ++k) { - const long long e = i + k; - const long long g = e >> group_shift; - const int code = (c[e / PER_BYTE] >> ((int) (e % PER_BYTE) * CODE_BITS)) & MASK; - acc0 += (decode_tbl(code, bias, codebook, s_iq4nl) * s[g] + (off ? off[g] : 0.0f)) * - __half2float(__ushort_as_half(x[e])); - } - } - partial[tid] = (acc0 + acc1) + (acc2 + acc3); - __syncthreads(); - for (int step = threads_per_row / 2; step > 0; step >>= 1) { - if (tid < step) partial[tid] += partial[tid + step]; - __syncthreads(); - } - if (tid == 0) y[o] = partial[0]; -} - -} // namespace - -static void s_gemv_split_impl(const uint16_t* x, const uint8_t* codes, const float* scales, - const float* offset, float* y, int64_t n_in, int64_t n_out, const SForm& form, - int threads_per_row, cudaStream_t stream, bool sync) { - if (n_in <= 0 || n_out <= 0) return; - if (threads_per_row < 1 || (threads_per_row & (threads_per_row - 1)) != 0 || threads_per_row > 1024) { - std::fprintf(stderr, "s_gemv_split: threads_per_row must be a power of two in 1..1024, got %d\n", - threads_per_row); - std::exit(1); - } - const int cb = (int) form.codebook; - // Every group size this format defines is a power of two, which is what lets the per-element group index - // be a shift. Refuse anything else rather than compute a wrong index quietly. - if (form.group_elems <= 0 || (form.group_elems & (form.group_elems - 1)) != 0) { - std::fprintf(stderr, "s_gemv_split: group_elems must be a power of two, got %d\n", form.group_elems); - std::exit(1); - } - // AND THE QUAD MUST FIT INSIDE ONE GROUP: four consecutive elements share a scale and the kernel reads - // exactly one. Every group size this format defines is 16, 32 or 64, so this cannot fire on a real pack. - if (form.group_elems % 4 != 0) { - std::fprintf(stderr, "s_gemv_split: group_elems %d is not a multiple of 4\n", form.group_elems); - std::exit(1); - } - int group_shift = 0; - while ((1 << group_shift) < form.group_elems) ++group_shift; - const size_t smem = (size_t) threads_per_row * sizeof(float); - const unsigned grid = (unsigned) n_out; - switch (form.code_bits) { - case 2: - s_gemv_split_kernel<2><<>>( - x, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, form.group_elems, - group_shift, form.has_offset ? 1 : 0, threads_per_row); - break; - case 4: - s_gemv_split_kernel<4><<>>( - x, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, form.group_elems, - group_shift, form.has_offset ? 1 : 0, threads_per_row); - break; - case 8: - s_gemv_split_kernel<8><<>>( - x, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, form.group_elems, - group_shift, form.has_offset ? 1 : 0, threads_per_row); - break; - default: - std::fprintf(stderr, "s_gemv_split: unsupported code_bits %d\n", form.code_bits); - std::exit(1); - } - if (sync) { - const cudaError_t e = cudaDeviceSynchronize(); - if (e != cudaSuccess) { - std::fprintf(stderr, "s_gemv_split: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - } -} - -void s_gemv_split(const uint16_t* x, const uint8_t* codes, const float* scales, const float* offset, - float* y, int64_t n_in, int64_t n_out, const SForm& form, int threads_per_row) { - s_gemv_split_impl(x, codes, scales, offset, y, n_in, n_out, form, threads_per_row, (cudaStream_t) 0, true); -} - -void s_gemv_split_async(const uint16_t* x, const uint8_t* codes, const float* scales, const float* offset, - float* y, int64_t n_in, int64_t n_out, const SForm& form, int threads_per_row, - void* stream) { - s_gemv_split_impl(x, codes, scales, offset, y, n_in, n_out, form, threads_per_row, (cudaStream_t) stream, - false); -} - -// ---- the Q8_K entry points ----------------------------------------------------------------------------- - -namespace { - -bool q8k_form_ok(const SForm& form, int64_t n_in, const char* who) { - if (form.group_elems <= 0 || n_in % form.group_elems != 0) { - std::fprintf(stderr, "%s: n_in %lld is not a multiple of group_elems %d\n", who, (long long) n_in, - form.group_elems); - return false; - } - if (n_in % Q8K_BLOCK_ELEMS != 0) { - // `quantize_q8_K` requires this too, and a partial block would read past the end of the activation. - std::fprintf(stderr, "%s: n_in %lld is not a multiple of the Q8_K block %d\n", who, (long long) n_in, - Q8K_BLOCK_ELEMS); - return false; - } - return true; -} - -void finish(const char* who, void* stream) { - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "%s launch: %s\n", who, cudaGetErrorString(e)); - std::exit(1); - } - if (stream != nullptr) return; - const cudaError_t s = cudaDeviceSynchronize(); - if (s != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", who, cudaGetErrorString(s)); - std::exit(1); - } -} - -} // namespace - -void s_gemv_q8k(const uint8_t* x_q8k, const uint8_t* codes, const float* scales, const float* offset, float* y, - int64_t n_in, int64_t n_out, const SForm& form, void* stream) { - if (n_in <= 0 || n_out <= 0) return; - if (!q8k_form_ok(form, n_in, "s_gemv_q8k")) std::exit(1); - const int threads = 128; - const unsigned blocks = (unsigned) ((n_out + threads - 1) / threads); - const int cb = (int) form.codebook; - const int ho = form.has_offset ? 1 : 0; - switch (form.code_bits) { - case 4: - s_gemv_q8k_kernel<4><<>>( - x_q8k, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, form.group_elems, ho); - break; - case 8: - s_gemv_q8k_kernel<8><<>>( - x_q8k, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, form.group_elems, ho); - break; - default: - // 2-bit S2 never has a Q8_K activation: its `vec_dot_type` is Q8_0. Refusing is better than - // running a kernel that would be numerically wrong in a way the caller cannot see. - std::fprintf(stderr, "s_gemv_q8k: code_bits %d has no Q8_K contract " - "(S2 uses Q8_0; see docs/activation-contract.md)\n", form.code_bits); - std::exit(1); - } - finish("s_gemv_q8k", stream); -} - -void s_gemv_q8k_split(const uint8_t* x_q8k, const uint8_t* codes, const float* scales, const float* offset, - float* y, int64_t n_in, int64_t n_out, const SForm& form, void* stream) { - if (n_in <= 0 || n_out <= 0) return; - if (!q8k_form_ok(form, n_in, "s_gemv_q8k_split")) std::exit(1); - // THE GROUP SIZE IS PASSED AS ITS LOGARITHM: see the note on the kernel. A non-power-of-two group would - // make the shift a WRONG INDEX rather than a slow one, so it is refused here. - int group_shift = 0; - while ((1 << group_shift) < form.group_elems) ++group_shift; - if ((1 << group_shift) != form.group_elems) { - std::fprintf(stderr, "s_gemv_q8k_split: group_elems %d is not a power of two\n", form.group_elems); - std::exit(1); - } - // AND THE QUAD MUST FIT INSIDE ONE GROUP. Four consecutive elements share a scale, so a group smaller - // than four would need two of them and the kernel reads exactly one. Every group size this format - // defines is 16, 32 or 64, so this cannot fire on a real pack - it is here because a future one could. - if (form.group_elems % 16 != 0) { - std::fprintf(stderr, "s_gemv_q8k_split: group_elems %d is not a multiple of 16\n", form.group_elems); - std::exit(1); - } - const int threads = 256; - const int warps = threads / 32; - const unsigned blocks = (unsigned) ((n_out + warps - 1) / warps); - const int cb = (int) form.codebook; - const int ho = form.has_offset ? 1 : 0; - switch (form.code_bits) { - case 4: - s_gemv_q8_split_kernel<4, true><<>>( - x_q8k, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, group_shift, ho); - break; - case 8: - s_gemv_q8_split_kernel<8, true><<>>( - x_q8k, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, group_shift, ho); - break; - default: - std::fprintf(stderr, "s_gemv_q8k_split: code_bits %d has no Q8_K contract\n", form.code_bits); - std::exit(1); - } - finish("s_gemv_q8k_split", stream); -} - -void s_gemv_q8_0_split(const uint8_t* x_q8_0, const uint8_t* codes, const float* scales, const float* offset, - float* y, int64_t n_in, int64_t n_out, const SForm& form, void* stream) { - if (n_in <= 0 || n_out <= 0) return; - // THE ACTIVATION IS `block_q8_0`, 32 elements per block, so `n_in` must be a multiple of 32 - which is a - // WEAKER requirement than Q8_K's 256 and is exactly why this kernel has to exist: `ffn_down_shexp` has - // n_in = 640, a multiple of 32 that is NOT a multiple of 256. - if (n_in % Q8_0_BLOCK_ELEMS != 0) { - std::fprintf(stderr, "s_gemv_q8_0_split: n_in %lld is not a multiple of %d\n", (long long) n_in, - Q8_0_BLOCK_ELEMS); - std::exit(1); - } - // the same two checks `s_gemv_q8k_split` makes, for the same reasons - see the notes there - if (form.group_elems <= 0 || (form.group_elems & (form.group_elems - 1)) != 0) { - std::fprintf(stderr, "s_gemv_q8_0_split: group_elems must be a power of two, got %d\n", - form.group_elems); - std::exit(1); - } - // SIXTEEN, NOT FOUR: a lane-iteration takes QE = 16 consecutive elements under ONE scale (see the kernel), - // so a group of 4 or 8 would read the wrong scale for most of them. The Q8_K launcher already said 16. - if (form.group_elems % 16 != 0) { - std::fprintf(stderr, "s_gemv_q8_0_split: group_elems %d is not a multiple of 16\n", form.group_elems); - std::exit(1); - } - int group_shift = 0; - while ((1 << group_shift) < form.group_elems) ++group_shift; - - const int threads = 256; - const int warps = threads / 32; - const unsigned blocks = (unsigned) ((n_out + warps - 1) / warps); - const int cb = (int) form.codebook; - const int ho = form.has_offset ? 1 : 0; - switch (form.code_bits) { - case 4: - s_gemv_q8_split_kernel<4, false><<>>( - x_q8_0, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, group_shift, ho); - break; - case 8: - s_gemv_q8_split_kernel<8, false><<>>( - x_q8_0, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, group_shift, ho); - break; - default: - std::fprintf(stderr, "s_gemv_q8_0_split: code_bits %d has no Q8_0 contract\n", form.code_bits); - std::exit(1); - } - finish("s_gemv_q8_0_split", stream); -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/sampler.cu b/src/kernels/cuda/sampler.cu deleted file mode 100644 index 8982a28..0000000 --- a/src/kernels/cuda/sampler.cu +++ /dev/null @@ -1,1081 +0,0 @@ -// src/kernels/cuda/sampler.cu - P2.S2: the sampler chain, in llama.cpp's order. -// -// penalties -> top_k -> top_p -> min_p -> temperature -> pick -// -// THE ORDER IS THE WHOLE CONTENT OF THIS FILE. llama.cpp builds its chain by walking `params.samplers`, whose -// default is { PENALTIES, DRY, TOP_N_SIGMA, TOP_K, TYPICAL_P, TOP_P, MIN_P, XTC, TEMPERATURE } (`common/common.h` -// at 3cf03257) - ONE penalties stage, first, and TEMPERATURE AFTER THE TRUNCATION FILTERS. (Issue #53: this file -// used to apply the penalties a second time after the temperature, and min_p before top_p - both taken from the -// order of the `case` labels in `common/sampling.cpp`, which is not the order the chain runs.) Every order -// produces a valid token, so only a comparison at the distribution level can tell them apart; the parity test -// does that against an independently computed distribution. -// -// `sampler_greedy_kernel` is the plain argmax, one block per token over the vocabulary (on sm_90+ without penalties, -// `sampler_greedy_cluster_kernel`: the same token from a cluster of 8 CTAs per row). The sampled chain has -// three implementations that pick the same token, bit for bit: -// - the SPLIT top_k (default): `sampler_split_part_kernel` cuts each row into 4,096-logit blocks over the whole -// GPU, each keeps its own top_k, and `sampler_split_merge_kernel` merges those lists and runs the tail; -// - `sampler_one_block_kernel` (`STRATA_SAMPLER_ONE_BLOCK=1`, and the fallback when the split cannot run): one -// block per token, `top_k` block-argmax rounds, each over the logits after the previous pick; -// - `sampler_kernel` (`STRATA_OLD_SAMPLER=1`), the kernel of engine 0.1.20, kept as the reference. -// The two new ones share `sampled_tail_warp` (top_p / min_p / temperature / draw on one warp). -#include "strata/kernels/sampler.hpp" -#include "strata/core/coupled_draft.hpp" -#include "strata/core/emulate.hpp" - -#include - -#include -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { - -// Philox 4x32-10, the counter-based generator the phase asks for. Counter-based matters because it makes the -// stream a function of (seed, position) rather than of how many draws came before - so a batch can be sampled -// in any order and a run is reproducible. -__device__ __forceinline__ uint32_t philox4x32_round(uint32_t& c0, uint32_t& c1, uint32_t& c2, uint32_t& c3, - uint32_t k0, uint32_t k1) { - const uint32_t hi0 = __umulhi(0x9E3779B9u, c0); - const uint32_t hi1 = __umulhi(0xBB67AE85u, c2); - const uint32_t lo0 = 0x9E3779B9u * c0; - const uint32_t lo1 = 0xBB67AE85u * c2; - const uint32_t n0 = hi1 ^ c1 ^ k0; - const uint32_t n1 = lo1; - const uint32_t n2 = hi0 ^ c3 ^ k1; - const uint32_t n3 = lo0; - c0 = n0; c1 = n1; c2 = n2; c3 = n3; - return 0; -} - -__device__ __forceinline__ float philox_uniform(uint64_t seed, uint64_t counter) { - uint32_t c0 = (uint32_t) counter, c1 = (uint32_t) (counter >> 32); - uint32_t c2 = (uint32_t) seed, c3 = (uint32_t) (seed >> 32); - for (int i = 0; i < 10; ++i) { - philox4x32_round(c0, c1, c2, c3, (uint32_t) i, 0u); - } - // 24 bits of mantissa, so the value is uniform in [0,1) with no rounding to 1.0 - return (float) (c0 >> 8) * (1.0f / 16777216.0f); -} - -// `count_in_history` and the penalty application, transcribed from `llama_sampler_penalties_apply`. -// The repeat penalty MULTIPLIES for non-positive logits and DIVIDES for positive ones - dividing -// unconditionally is the natural reading of the source paper and it INVERTS the penalty on half the -// vocabulary. The presence penalty is `float(count > 0)`, a boolean, not the count. -__device__ __forceinline__ int history_count(const int* __restrict__ h, int n, int v) { - int c = 0; - for (int i = 0; i < n; ++i) if (h[i] == v) ++c; - return c; -} - -__device__ __forceinline__ float apply_penalties(float logit, int count, const SamplerParams& p) { - if (count <= 0) return logit; - if (logit <= 0.0f) logit *= p.penalty_repeat; - else logit /= p.penalty_repeat; - logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present; - return logit; -} - -/// **THE GREEDY ARGMAX, ONE BLOCK PER TOKEN, COVERING THE VOCABULARY.** -/// -/// **WHY THIS IS A SEPARATE KERNEL AND NOT A BRANCH.** `sampler_kernel` is launched as a grid over TOKENS -/// with 64 threads and a `if (t >= n_tokens) return;` at the top. The decode path has `n_tokens == 1`, so -/// that launch was `<<<1, 64>>>`, 63 threads exited on the first line, and ONE THREAD walked all 248,320 -/// logits in a dependent loop on one SM of 48. Measured in isolation (`bench/micro/sampler_cost.cu`): -/// **3.11 ms per token**, 5.7% of an ~54 ms token, and the whole of round 309's `sample` phase - the two -/// synchronisations around it are 0.03 ms each. -/// -/// The obvious repair is to parallelise the scan inside `sampler_kernel`, and it is WRONG: with one thread -/// per token, a block reduction over the vocabulary has nothing to reduce, and the threads that returned -/// early are not there for `__syncthreads` or `__shfl_down_sync`. The first attempt did exactly that and -/// produced the token `5120` thirty-two times. The grid has to be over tokens with the BLOCK over the -/// vocabulary, which is a different launch configuration and therefore a different kernel. -/// -/// **THE TIE RULE IS UNCHANGED AND THAT IS THE WHOLE CORRECTNESS ARGUMENT.** The serial scan walked `v` -/// ascending with `if (s > bv)`, so the LOWEST index wins a tie. Each thread keeps that rule over its own -/// strided subset and the reduction resolves two candidates by taking the larger value and, on equality, the -/// SMALLER index - the same total order, so `sampler_parity` and C1 see no change. -__global__ void sampler_greedy_kernel(const float* __restrict__ logits, int n_vocab, - const int* __restrict__ history, int history_len, const SamplerParams p, - int pmin, int plen, int* __restrict__ out) { - const int t = blockIdx.x; - const float* l = logits + (size_t) t * n_vocab; - (void) pmin; - const int* hrow = history ? history + (size_t) t * history_len : nullptr; - int hlen = 0; - if (hrow) { - hlen = plen < history_len ? plen : history_len; - if (hlen < 0) hlen = 0; - hrow += history_len - hlen; // the window is the TAIL - } - - // PENALTY MEMBERSHIP AS A BITMAP. The history touches at most `hlen` tokens of a quarter-million - // vocabulary, but the naive `history_count` per candidate per argmax round costs O(k x n_vocab x hlen) - // integer compares (~318 M per token at k=20, hlen=64 - measured 45 -> 31 tok/s on a real workload). - // A shared bitmap gives an O(1) membership test, and only the (at most hlen) hits pay the count scan; - // the counts - and therefore every sampled value - are exactly what the per-candidate scan produced. - extern __shared__ unsigned int penal_bits[]; - const int bits_words = (int) ((n_vocab + 31) / 32); - // The gate needs a NON-EMPTY WINDOW (`hlen > 0`): the launch sizes the shared bitmap only when penalties - // are on, so a caller handing over a history buffer with `penalty_last_n == 0` must not touch it. - const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0; - if (use_bits) { - for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u; - __syncthreads(); - for (int i = threadIdx.x; i < hlen; i += blockDim.x) - if (hrow[i] >= 0 && hrow[i] < n_vocab) // an id outside the vocabulary is never a candidate - atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31)); - __syncthreads(); - } - auto hit_count = [&](int v) -> int { - if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0; - return history_count(hrow, hlen, v); - }; - - // `n_vocab` is the "no candidate" index: it loses every comparison to a real one, so a thread with no - // elements contributes nothing rather than contributing a bogus zero. - float bv = __int_as_float(0xff800000); // -inf - int best = n_vocab; - for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) { - const float s = apply_penalties(l[v], hit_count(v), p); - if (s > bv) { bv = s; best = v; } - } - for (int off = 16; off > 0; off >>= 1) { - const float ov = __shfl_down_sync(0xFFFFFFFFu, bv, off); - const int oi = __shfl_down_sync(0xFFFFFFFFu, best, off); - if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; } - } - __shared__ float sv[32]; - __shared__ int si[32]; - const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31); - if (lane == 0) { sv[warp] = bv; si[warp] = best; } - __syncthreads(); - if (warp == 0) { - const int nw = (int) ((blockDim.x + 31) >> 5); - float wv = lane < nw ? sv[lane] : __int_as_float(0xff800000); - int wi = lane < nw ? si[lane] : n_vocab; - for (int off = 16; off > 0; off >>= 1) { - const float ov = __shfl_down_sync(0xFFFFFFFFu, wv, off); - const int oi = __shfl_down_sync(0xFFFFFFFFu, wi, off); - if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; } - } - // A tie between two `-inf` candidates leaves `wi == n_vocab`, and the serial version answered 0. - if (lane == 0) out[t] = (wi < n_vocab) ? wi : 0; - } -} - -#if !defined(__HIPCC__) -/// **THE SAME ARGMAX ON A THREAD-BLOCK CLUSTER (sm_90+, S19), FOR THE CALLS WITHOUT PENALTIES.** One block per -/// token reads its 1 MB row (248,320 logits) on one SM with one load in flight per thread: latency-bound, 40 us per -/// call on an RTX 5070, for every verify window and every draft step. Here a cluster of `kAmCtas` CTAs shares the -/// row, each thread keeps four loads in flight, and the CTAs' results meet in CTA 0's shared memory (distributed -/// shared memory): 6 us (decode_cluster_parity --bench). -/// -/// The answer is a function of the row alone, so it is the one-block kernel's bit for bit: the LOWEST index whose value -/// is the largest non-NaN value above -inf (each thread walks its elements in ascending order with a strict `>`, and -/// every merge takes the larger value or, on equality, the smaller index - an order-free rule), and 0 when there is -/// none (all -inf / NaN), as there. NaN never wins a `>`. -/// -/// Barriers: a relaxed cluster arrive at entry, waited before the remote store (CTA 0 must be running); each CTA's -/// result goes to slot `rank` of CTA 0, released by the next arrive; CTAs 1.. then exit (a cluster wait counts the -/// threads that have not exited) and CTA 0 waits, reads its own slots, and writes the token. -constexpr int kAmCtas = 8; // CTAs per token (the portable cluster size) -constexpr int kAmThreads = 1024; -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900 -#define STRATA_AM_CLUSTER 1 -#else -#define STRATA_AM_CLUSTER 0 // older targets: a trap, never launched (sample_greedy_cluster checks) -#endif -#if STRATA_AM_CLUSTER -__device__ __forceinline__ void am_take(float s, int v, float& bv, int& best) { - if (s > bv) { bv = s; best = v; } -} -__device__ __forceinline__ void am_merge(float ov, int oi, float& bv, int& best) { - if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; } -} -#endif -// grid (kAmCtas, n_tokens), cluster (kAmCtas, 1, 1), kAmThreads threads -__global__ void __launch_bounds__(kAmThreads) sampler_greedy_cluster_kernel(const float* __restrict__ logits, - int n_vocab, int* __restrict__ out) { -#if STRATA_AM_CLUSTER - __shared__ float sv[32]; - __shared__ int si[32]; - __shared__ float cv[kAmCtas]; // on CTA 0: each CTA's result - __shared__ int ci[kAmCtas]; - unsigned rank; - asm volatile("mov.u32 %0, %%cluster_ctarank;\n" : "=r"(rank)); - asm volatile("barrier.cluster.arrive.relaxed.aligned;\n" ::: "memory"); - const float* l = logits + (size_t) blockIdx.y * n_vocab; - float bv = __int_as_float(0xff800000); // -inf; `n_vocab` is "no candidate", as in sampler_greedy_kernel - int best = n_vocab; - constexpr int S = kAmCtas * kAmThreads; - int v = (int) rank * kAmThreads + (int) threadIdx.x; - for (; v + 3 * S < n_vocab; v += 4 * S) { // four independent loads, then taken in ascending order - const float x0 = l[v], x1 = l[v + S], x2 = l[v + 2 * S], x3 = l[v + 3 * S]; - am_take(x0, v, bv, best); - am_take(x1, v + S, bv, best); - am_take(x2, v + 2 * S, bv, best); - am_take(x3, v + 3 * S, bv, best); - } - for (; v < n_vocab; v += S) am_take(l[v], v, bv, best); - for (int off = 16; off > 0; off >>= 1) - am_merge(__shfl_down_sync(0xFFFFFFFFu, bv, off), __shfl_down_sync(0xFFFFFFFFu, best, off), bv, best); - const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31); - if (lane == 0) { sv[warp] = bv; si[warp] = best; } - __syncthreads(); - if (warp == 0) { - bv = sv[lane]; - best = si[lane]; - for (int off = 16; off > 0; off >>= 1) - am_merge(__shfl_down_sync(0xFFFFFFFFu, bv, off), __shfl_down_sync(0xFFFFFFFFu, best, off), bv, best); - } - asm volatile("barrier.cluster.wait.acquire.aligned;\n" ::: "memory"); // CTA 0 runs - if (threadIdx.x == 0) { - uint64_t a; - asm volatile("mapa.u64 %0, %1, %2;\n" : "=l"(a) : "l"((uint64_t) &cv[rank]), "r"(0u)); - *reinterpret_cast(a) = bv; - asm volatile("mapa.u64 %0, %1, %2;\n" : "=l"(a) : "l"((uint64_t) &ci[rank]), "r"(0u)); - *reinterpret_cast(a) = best; - } - asm volatile("barrier.cluster.arrive.release.aligned;\n" ::: "memory"); - if (rank != 0) return; - asm volatile("barrier.cluster.wait.acquire.aligned;\n" ::: "memory"); - if (warp == 0) { - bv = lane < kAmCtas ? cv[lane] : __int_as_float(0xff800000); - best = lane < kAmCtas ? ci[lane] : n_vocab; - for (int off = 16; off > 0; off >>= 1) - am_merge(__shfl_down_sync(0xFFFFFFFFu, bv, off), __shfl_down_sync(0xFFFFFFFFu, best, off), bv, best); - if (lane == 0) out[blockIdx.y] = (best < n_vocab) ? best : 0; - } -#else - (void) logits; (void) n_vocab; (void) out; - __trap(); -#endif -} -#endif // !__HIPCC__ - -/// **THE SAMPLED PATH, ONE BLOCK PER TOKEN.** The kernel below replaced a version that ran the whole chain -/// in ONE THREAD per token (`<<>>`, so a 4-token window fielded four threads): `top_k` alone -/// was `k` sequential scans of the vocabulary with an inner sweep over the already-taken list - 20 x 248,320 -/// iterations of dependent work on one SM - and a verify window measured **1.6 s in the sampler**, which made -/// every temperature-bearing request ~30x slower than a greedy one. The selection is `k` argmax rounds, and -/// an argmax over the vocabulary parallelises exactly like `sampler_greedy_kernel` (block over the vocab), so -/// the rounds run back to back inside a block-per-token launch: the per-token cost falls to -/// `k x n_vocab / 1024` plus `k` block reductions. -/// -/// THE SEMANTICS ARE THE SERIAL ONES, EXACTLY. Each round's argmax resolves ties to the LOWEST index (the -/// serial scan's strict `>` keeps the first maximum it meets), so the kept sequence - both its set and its -/// order - is unchanged; `top_p`'s cut reads that order in double arithmetic as before; temperature and the -/// Philox draw apply after the cut. `sampler_parity` pins all of it against the host reference. -/// -/// **KEPT AS THE REFERENCE, BEHIND `STRATA_OLD_SAMPLER=1`.** Two costs remain in it: the `taken` -/// sweep is O(k) per logit per round, O(k^2 x n_vocab) per row (47 M shared-memory compares at k = 20, 500 M at -/// 64), and the double-precision tail runs on all 1,024 threads where one warp suffices - GeForce issues FP64 at -/// 1/64 of FP32. The kernels after this one remove both and select the same list in the same order. -__global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, int n_tokens, - const int* __restrict__ history, int history_len, const SamplerParams p, - int* __restrict__ out) { - const int t = blockIdx.x; - if (t >= n_tokens) return; - const float* l = logits + (size_t) t * n_vocab; - - // Temperature is needed by BOTH stages below, so it is computed here; the chain still APPLIES it after - // the truncation filters - the survivors are chosen on the raw logits and only then scaled. - const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f; - - // The penalty window is the last `penalty_last_n` entries of this row's history (disabled at this - // launch: `sample_tokens` refuses a non-zero `penalty_last_n` without a history buffer). - const int* hrow = history ? history + (size_t) t * history_len : nullptr; - int hlen = 0; - if (hrow) { - hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len; - if (hlen < 0) hlen = 0; - hrow += history_len - hlen; // the window is the TAIL - } - - // the membership bitmap, as in `sampler_greedy_kernel` - see the cost note there. The gate needs an - // NON-EMPTY WINDOW too: the launch sizes the bitmap only when penalties are on, so a caller that hands over - // a stale history buffer with `penalty_last_n == 0` must not touch it. - extern __shared__ unsigned int penal_bits[]; - const int bits_words = (int) ((n_vocab + 31) / 32); - const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0; - if (use_bits) { - for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u; - __syncthreads(); - for (int i = threadIdx.x; i < hlen; i += blockDim.x) - if (hrow[i] >= 0 && hrow[i] < n_vocab) // an id outside the vocabulary is never a candidate - atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31)); - __syncthreads(); - } - auto hit_count = [&](int v) -> int { - if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0; - return history_count(hrow, hlen, v); - }; - - // top_k in 1..64 is taken as given; 0 ("off") and anything wider mean the widest shortlist the kernel - // keeps, 64. Every row writes out[t]: a verify window reads all of them. - const int KMAX = 64; - int k = (p.top_k > 0 && p.top_k < KMAX) ? p.top_k : KMAX; - if (k > n_vocab) k = n_vocab; - - // ---- top_k: k rounds of a block argmax over the not-yet-taken. `sel_*` holds the kept ids and their - // raw logits in selection order: descending by value, ties to the lower index, which is the order the - // top_p cut below is defined over. - __shared__ int sel_ids[KMAX]; - __shared__ float sel_logit[KMAX]; - __shared__ float sv[32]; - __shared__ int si[32]; - for (int i = 0; i < k; ++i) { - // `n_vocab` is the "no candidate" index: it loses every comparison to a real one (same convention as - // the greedy kernel, whose tie rule this reduction shares). - float bv = __int_as_float(0xff800000); // -inf - int best = n_vocab; - for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) { - bool taken = false; - for (int j = 0; j < i; ++j) if (sel_ids[j] == v) { taken = true; break; } - if (taken) continue; - const float s = apply_penalties(l[v], hit_count(v), p); - if (s > bv) { bv = s; best = v; } - } - for (int off = 16; off > 0; off >>= 1) { - const float ov = __shfl_down_sync(0xFFFFFFFFu, bv, off); - const int oi = __shfl_down_sync(0xFFFFFFFFu, best, off); - if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; } - } - const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31); - if (lane == 0) { sv[warp] = bv; si[warp] = best; } - __syncthreads(); - if (warp == 0) { - const int nw = (int) ((blockDim.x + 31) >> 5); - float wv = lane < nw ? sv[lane] : __int_as_float(0xff800000); - int wi = lane < nw ? si[lane] : n_vocab; - for (int off = 16; off > 0; off >>= 1) { - const float ov = __shfl_down_sync(0xFFFFFFFFu, wv, off); - const int oi = __shfl_down_sync(0xFFFFFFFFu, wi, off); - if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; } - } - if (lane == 0) { sel_ids[i] = (wi < n_vocab) ? wi : 0; sel_logit[i] = wv; } - } - __syncthreads(); - } - - // ---- top_p over the top_k list (penalised logits, descending as the selection produced them), then min_p, - // then temperature and one Philox draw - llama.cpp's order (issue #53). Every thread computes the same chain - // redundantly over `sel_*` - the arithmetic is the serial kernel's, instruction for instruction - so they - // agree on `pick` and thread 0 writes it. - int n_keep = k; - float mx = sel_logit[0]; - for (int i = 1; i < k; ++i) mx = fmaxf(mx, sel_logit[i]); - if (p.top_p < 1.0f) { - double sum = 0.0; - for (int i = 0; i < k; ++i) sum += exp((double) sel_logit[i] - (double) mx); - double cum = 0.0; - int cut = k; - for (int i = 0; i < k; ++i) { - cum += exp((double) sel_logit[i] - (double) mx) / sum; - if (cum >= (double) p.top_p) { cut = i + 1; break; } - } - if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k; - n_keep = cut; - } - // ---- min_p on top_p's survivors: the descending prefix whose probability is at least `min_p` of the top - // token's. In logit space the threshold is `sel_logit[0] + logf(min_p)` - equivalent to `p >= min_p * p_max` - // without the overflow an exp of raw logits risks. 0 disables, and the head itself always survives - // (`expf(0) == 1 >= min_p` for min_p in 0..1), so the count never reaches zero. - if (p.min_p > 0.0f) { - const float thresh = sel_logit[0] + logf(p.min_p); - for (int i = 0; i < n_keep; ++i) - if (sel_logit[i] < thresh) { n_keep = i; break; } - } - // temperature only: the penalties were applied once, before the selection (issue #53: they were applied a - // second time here, after the temperature scaling - llama.cpp's chain has one penalties stage) - auto scaled = [&](int i) { return sel_logit[i] * inv_t; }; - float smx = scaled(0); - for (int i = 1; i < n_keep; ++i) smx = fmaxf(smx, scaled(i)); - double sum = 0.0; - for (int i = 0; i < n_keep; ++i) sum += exp((double) scaled(i) - (double) smx); - const float u = philox_uniform(p.seed, p.counter + (uint64_t) t); - double cum = 0.0; - int pick = sel_ids[n_keep - 1]; - for (int i = 0; i < n_keep; ++i) { - cum += exp((double) scaled(i) - (double) smx) / sum; - if ((double) u < cum) { pick = sel_ids[i]; break; } - } - if (threadIdx.x == 0) out[t] = pick; -} - -// ---- the same list, in the same order, without the `taken` sweep ---- -// -// THE SELECTION ORDER. `sampler_kernel`'s rounds rank a candidate (value, id) before (value', id') when value > -// value', or value == value' and id < id' - each thread's ascending scan keeps the first maximum it meets (strict -// `>`), and the reductions resolve a tie to the lower id. That is a strict total order (-0 and +0 compare equal and -// fall to the id, as there), so round i picks the i-th logit of the order. NaN and -inf are never picked (`s > bv` -// from -inf fails); a round that finds nothing yields the SENTINEL (-inf, n_vocab), stored as id 0. - -constexpr int kSelMax = 64; // the widest top_k list, `sampler_kernel`'s KMAX -constexpr unsigned kFullMask = 0xFFFFFFFFu; - -// top_k 1..64 as given; 0 ("off") and anything wider keep 64; never more than the vocabulary -__host__ __device__ __forceinline__ int sampled_k(int top_k, int n_vocab) { - int k = (top_k > 0 && top_k < kSelMax) ? top_k : kSelMax; - return k > n_vocab ? n_vocab : k; -} - -// (bv, bi) <- the first of (bv, bi) and (ov, oi) in the selection order -__device__ __forceinline__ void take_first(float& bv, int& bi, float ov, int oi) { - if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; } -} - -// The first of the warp's 32 candidates, left in EVERY lane. An XOR butterfly is exact here: "the first of two" is -// associative and commutative in a strict total order (two lanes never hold different candidates that compare -// equal - an id is in one lane at most, and two sentinels are the same pair), so every lane ends with the same pair. -__device__ __forceinline__ void warp_first(float& bv, int& bi) { -#pragma unroll - for (int off = 16; off > 0; off >>= 1) { - const float ov = __shfl_xor_sync(kFullMask, bv, off); - const int oi = __shfl_xor_sync(kFullMask, bi, off); - take_first(bv, bi, ov, oi); - } -} - -/// **THE TAIL ON ONE WARP, WITH `sampler_kernel`'S ARITHMETIC.** `sel_ids` / `sel_logit` (shared, `k` entries) are -/// the top_k list in selection order; the 32 lanes of one warp call this and lane 0 writes `out[t]`. The old tail -/// ran on all 1,024 threads, each computing the same ~4k double `exp`s - FP64 issues at 1/64 of FP32 on GeForce. -/// Here the lanes share the `exp`s (one per entry, into `ex`) and then the quotients, and lane 0 alone runs the two -/// ORDERED sums and the two cumulative scans. Every double is the one the old chain computed: the same `exp` of -/// the same argument, the sums in the same order, `cum += e / sum` with the same correctly rounded quotient - so -/// the cut, the survivors and the pick are the same. (`n_keep == 0`, reachable only with min_p > 1, which the -/// callers clamp, read `sel_ids[-1]` in the old tail; it reads `sel_ids[0]` here.) -/// kProb (the coupled draft only): lane 0 also writes the pick's probability under the final distribution to -/// `*prob_out`. The sampler's own calls take kProb = false, whose code is the tail above, unchanged. -template -__device__ void sampled_tail_warp(const int* sel_ids, const float* sel_logit, int k, const SamplerParams& p, int t, - int* __restrict__ out, double* ex, float* prob_out = nullptr) { - const int lane = (int) (threadIdx.x & 31); - const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f; - int n_keep = k; - float mx = sel_logit[0]; - for (int i = 1; i < k; ++i) mx = fmaxf(mx, sel_logit[i]); - if (p.top_p < 1.0f) { - for (int i = lane; i < k; i += 32) ex[i] = exp((double) sel_logit[i] - (double) mx); - __syncwarp(); - double sum = 0.0; - if (lane == 0) - for (int i = 0; i < k; ++i) sum += ex[i]; - sum = __shfl_sync(kFullMask, sum, 0); - __syncwarp(); // lane 0 has read every `ex` before it is overwritten - for (int i = lane; i < k; i += 32) ex[i] = ex[i] / sum; - __syncwarp(); - int cut = k; - if (lane == 0) { - double cum = 0.0; - for (int i = 0; i < k; ++i) { - cum += ex[i]; - if (cum >= (double) p.top_p) { cut = i + 1; break; } - } - } - cut = __shfl_sync(kFullMask, cut, 0); - if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k; - n_keep = cut; - __syncwarp(); // `ex` is written again below - } - // min_p on top_p's survivors, as in `sampler_kernel` (every lane, the same float arithmetic) - if (p.min_p > 0.0f) { - const float thresh = sel_logit[0] + logf(p.min_p); - for (int i = 0; i < n_keep; ++i) - if (sel_logit[i] < thresh) { n_keep = i; break; } - } - // temperature, then one Philox draw - float smx = sel_logit[0] * inv_t; - for (int i = 1; i < n_keep; ++i) smx = fmaxf(smx, sel_logit[i] * inv_t); - for (int i = lane; i < n_keep; i += 32) ex[i] = exp((double) (sel_logit[i] * inv_t) - (double) smx); - __syncwarp(); - double sum = 0.0; - if (lane == 0) - for (int i = 0; i < n_keep; ++i) sum += ex[i]; - sum = __shfl_sync(kFullMask, sum, 0); - __syncwarp(); - for (int i = lane; i < n_keep; i += 32) ex[i] = ex[i] / sum; - __syncwarp(); - if (lane == 0) { - const float u = philox_uniform(p.seed, p.counter + (uint64_t) t); - double cum = 0.0; - int pi = n_keep > 0 ? n_keep - 1 : 0; - int pick = sel_ids[pi]; - for (int i = 0; i < n_keep; ++i) { - cum += ex[i]; - if ((double) u < cum) { pick = sel_ids[i]; pi = i; break; } - } - out[t] = pick; - if constexpr (kProb) *prob_out = n_keep > 0 ? (float) ex[pi] : 1.0f; - } -} - -/// **THE ONE-BLOCK SAMPLED PATH: `sampler_kernel` WITHOUT THE `taken` SWEEP.** Round i's candidates are the logits -/// strictly AFTER round i-1's pick in the selection order, `s < prev_v || (s == prev_v && v > prev_i)`, which is -/// exactly the set `taken` left: the picks so far are the first i of the order, so what comes after the last one is -/// what has not been picked. The round is then the same block argmax with the same tie rule, so the list is the -/// same list in the same order. An empty round leaves (-inf, id 0) as before, and every round after it is empty -/// in both versions (nothing after -inf beats -inf). O(k x n_vocab) per row instead of O(k^2 x n_vocab), then warp -/// 0 runs the tail. `STRATA_SAMPLER_ONE_BLOCK=1`, and the fallback when the split path cannot run. -__global__ void __launch_bounds__(1024) -sampler_one_block_kernel(const float* __restrict__ logits, int n_vocab, const int* __restrict__ history, - int history_len, const SamplerParams p, int* __restrict__ out) { - const int t = blockIdx.x; - const float* l = logits + (size_t) t * n_vocab; - - // the penalty window and its membership bitmap, exactly as in `sampler_kernel` - const int* hrow = history ? history + (size_t) t * history_len : nullptr; - int hlen = 0; - if (hrow) { - hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len; - if (hlen < 0) hlen = 0; - hrow += history_len - hlen; // the window is the TAIL - } - extern __shared__ unsigned int penal_bits[]; - const int bits_words = (int) ((n_vocab + 31) / 32); - const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0; - if (use_bits) { - for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u; - __syncthreads(); - for (int i = threadIdx.x; i < hlen; i += blockDim.x) - if (hrow[i] >= 0 && hrow[i] < n_vocab) // an id outside the vocabulary is never a candidate - atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31)); - __syncthreads(); - } - auto hit_count = [&](int v) -> int { - if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0; - return history_count(hrow, hlen, v); - }; - - const int k = sampled_k(p.top_k, n_vocab); - __shared__ int sel_ids[kSelMax]; - __shared__ float sel_logit[kSelMax]; - __shared__ double ex[kSelMax]; - __shared__ float sv[32]; - __shared__ int si[32]; - const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31); - float prev_v = __int_as_float(0x7f800000); // +inf and id -1: round 0 takes every logit - int prev_i = -1; - for (int i = 0; i < k; ++i) { - float bv = __int_as_float(0xff800000); // -inf - int best = n_vocab; - for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) { - const float s = apply_penalties(l[v], hit_count(v), p); - if ((s < prev_v || (s == prev_v && v > prev_i)) && s > bv) { bv = s; best = v; } - } - for (int off = 16; off > 0; off >>= 1) { - const float ov = __shfl_down_sync(0xFFFFFFFFu, bv, off); - const int oi = __shfl_down_sync(0xFFFFFFFFu, best, off); - if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; } - } - if (lane == 0) { sv[warp] = bv; si[warp] = best; } - __syncthreads(); - if (warp == 0) { - const int nw = (int) ((blockDim.x + 31) >> 5); - float wv = lane < nw ? sv[lane] : __int_as_float(0xff800000); - int wi = lane < nw ? si[lane] : n_vocab; - for (int off = 16; off > 0; off >>= 1) { - const float ov = __shfl_down_sync(0xFFFFFFFFu, wv, off); - const int oi = __shfl_down_sync(0xFFFFFFFFu, wi, off); - if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; } - } - if (lane == 0) { sel_ids[i] = (wi < n_vocab) ? wi : 0; sel_logit[i] = wv; } - } - __syncthreads(); - // An empty round leaves (-inf, 0): nothing comes after it, as nothing was left untaken. - prev_v = sel_logit[i]; - prev_i = sel_ids[i]; - } - if (warp != 0) return; - sampled_tail_warp(sel_ids, sel_logit, k, p, t, out, ex); -} - -// ---- THE SPLIT top_k. `sampler_kernel` and the one-block kernel keep a row on ONE SM of 170 (5090) and walk its -// 248,320 logits k times. Here a warp keeps the top_k of 1,024 logits held in registers, four warps make a block of -// 4,096 logits that merges their lists, and a row is 61 such blocks over the whole GPU; one warp per row then -// merges the 61 lists and runs the tail. Exact, because the first k of a union are within the first k of each part -// and a merge of ordered lists is ordered - the selection order being a strict total order (above). -constexpr int kSplitPerLane = 32; // logits per lane, in registers -constexpr int kSplitWarpSpan = 32 * kSplitPerLane; // 1,024 logits per warp -constexpr int kSplitWarps = 4; -constexpr int kSplitBlockSpan = kSplitWarps * kSplitWarpSpan; // 4,096 logits per block -constexpr int kSplitMaxBlocks = 64; // lists the merge holds: n_vocab <= 262,144 -constexpr int kSplitMaxRows = 64; // rows per split launch (the scratch's bound) - -/// Merge `nl` (<= 64) lists of `k` candidates - list L at `lists[L * stride]`, each in the selection order and -/// padded with sentinels - into their first `k`: `sink(i, value, id)` runs in every lane for i = 0..k-1 with the -/// same pair. Lane owns lists `lane` and `lane + 32`; a round takes the first of all heads and advances the list -/// it came from. An id is in one list at most (the lists cover disjoint logits), so exactly one head matches. -template -__device__ __forceinline__ void warp_merge_lists(const int2* lists, int nl, int stride, int k, int n_vocab, - Sink&& sink) { - const int lane = (int) (threadIdx.x & 31); - float hv[2]; - int hi[2], pos[2]; -#pragma unroll - for (int m = 0; m < 2; ++m) { - const int L = lane + 32 * m; - pos[m] = 0; - hv[m] = __int_as_float(0xff800000); - hi[m] = n_vocab; - if (L < nl) { - const int2 c = lists[(size_t) L * stride]; - hi[m] = c.x; - hv[m] = __int_as_float(c.y); - } - } - for (int i = 0; i < k; ++i) { - float bv = hv[0]; - int bi = hi[0]; - take_first(bv, bi, hv[1], hi[1]); - warp_first(bv, bi); - sink(i, bv, bi); - if (bi < n_vocab) { -#pragma unroll - for (int m = 0; m < 2; ++m) { - if (hi[m] != bi) continue; - if (++pos[m] < k) { - const int2 c = lists[(size_t) (lane + 32 * m) * stride + pos[m]]; - hi[m] = c.x; - hv[m] = __int_as_float(c.y); - } else { - hi[m] = n_vocab; - hv[m] = __int_as_float(0xff800000); - } - } - } - } -} - -/// **SPLIT STAGE 1: THE top_k OF EACH 4,096-LOGIT BLOCK.** Grid (blocks per row, rows), 128 threads. Each warp -/// loads its 1,024 penalised logits once into registers (lane + 32 j: every load is one coalesced 128-byte line) -/// and runs `k` warp-argmax rounds over them with the threshold of `sampler_one_block_kernel` - no shared memory -/// and no block barrier per round. Warp 0 then merges the four warp lists into the block's list in `cand` -/// (row-major: row t, block b, entry i at `(t * n_blocks + b) * k + i`, as (id, value bits)). -__global__ void __launch_bounds__(kSplitWarps * 32) -sampler_split_part_kernel(const float* __restrict__ logits, int n_vocab, const int* __restrict__ history, - int history_len, const SamplerParams p, int k, int n_blocks, int2* __restrict__ cand) { - const int t = blockIdx.y; - const float* l = logits + (size_t) t * n_vocab; - const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31); - const int blo = (int) blockIdx.x * kSplitBlockSpan; - - const int* hrow = history ? history + (size_t) t * history_len : nullptr; - int hlen = 0; - if (hrow) { - hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len; - if (hlen < 0) hlen = 0; - hrow += history_len - hlen; // the window is the TAIL - } - // The membership bitmap of THIS BLOCK'S 4,096 logits (512 bytes, not the vocabulary's 31 KB): the same test, - // and a hit pays the same exact count over the whole window. - __shared__ unsigned int bits[kSplitBlockSpan / 32]; - const bool use_bits = hrow != nullptr && hlen > 0; - if (use_bits) { - for (int w = threadIdx.x; w < kSplitBlockSpan / 32; w += blockDim.x) bits[w] = 0u; - __syncthreads(); - for (int i = threadIdx.x; i < hlen; i += blockDim.x) { - const int h = hrow[i]; - if (h >= 0 && h < n_vocab && h >= blo && h - blo < kSplitBlockSpan) - atomicOr(&bits[(h - blo) >> 5], 1u << ((h - blo) & 31)); - } - __syncthreads(); - } - - // This warp's logits, penalised: `apply_penalties` with a zero count returns the logit unchanged, so only the - // bitmap's hits go through it. Past the vocabulary: -inf, which no round picks. - const int lo = blo + warp * kSplitWarpSpan; - float s[kSplitPerLane]; -#pragma unroll - for (int j = 0; j < kSplitPerLane; ++j) { - const int v = lo + 32 * j + lane; - s[j] = v < n_vocab ? l[v] : __int_as_float(0xff800000); - } - if (use_bits) { -#pragma unroll - for (int j = 0; j < kSplitPerLane; ++j) { - const int v = lo + 32 * j + lane, b = v - blo; - if (v < n_vocab && (bits[b >> 5] & (1u << (b & 31)))) - s[j] = apply_penalties(s[j], history_count(hrow, hlen, v), p); - } - } - - __shared__ int2 wl[kSplitWarps][kSelMax]; - float prev_v = __int_as_float(0x7f800000); // +inf and id -1: round 0 takes every logit - int prev_i = -1; - int i = 0; - for (; i < k; ++i) { - // two chains (even and odd j), each walked in ascending id with a strict `>`, so each keeps its first in - // the order; `take_first` then orders the two - float b0 = __int_as_float(0xff800000), b1 = __int_as_float(0xff800000); - int i0 = n_vocab, i1 = n_vocab; -#pragma unroll - for (int j = 0; j < kSplitPerLane; j += 2) { - const int v0 = lo + 32 * j + lane, v1 = v0 + 32; - const float x0 = s[j], x1 = s[j + 1]; - if ((x0 < prev_v || (x0 == prev_v && v0 > prev_i)) && x0 > b0) { b0 = x0; i0 = v0; } - if ((x1 < prev_v || (x1 == prev_v && v1 > prev_i)) && x1 > b1) { b1 = x1; i1 = v1; } - } - take_first(b0, i0, b1, i1); - warp_first(b0, i0); - if (i0 >= n_vocab) break; // the same in every lane: nothing left in these 1,024 logits - if (lane == 0) wl[warp][i] = make_int2(i0, __float_as_int(b0)); - prev_v = b0; - prev_i = i0; - } - for (int r = i + lane; r < k; r += 32) wl[warp][r] = make_int2(n_vocab, (int) 0xff800000u); // sentinels - __syncthreads(); - if (warp == 0) { - int2* dst = cand + ((size_t) t * n_blocks + blockIdx.x) * k; - warp_merge_lists(&wl[0][0], kSplitWarps, kSelMax, k, n_vocab, [&](int r, float v, int id) { - if (lane == 0) dst[r] = make_int2(id, __float_as_int(v)); - }); - } -} - -/// **SPLIT STAGE 2: ONE WARP PER ROW MERGES THE BLOCK LISTS, THEN RUNS THE TAIL.** The row's lists (at most 64 x -/// 64 entries, 32 KB) are copied to shared memory, merged into the row's top_k list, and `sampled_tail_warp` picks. -__global__ void __launch_bounds__(32) -sampler_split_merge_kernel(const int2* __restrict__ cand, int n_blocks, int n_vocab, const SamplerParams p, int k, - int* __restrict__ out) { - const int t = blockIdx.x; - const int lane = (int) threadIdx.x; - __shared__ int2 lists[kSplitMaxBlocks * kSelMax]; - __shared__ int sel_ids[kSelMax]; - __shared__ float sel_logit[kSelMax]; - __shared__ double ex[kSelMax]; - const int2* src = cand + (size_t) t * n_blocks * k; - for (int e = lane; e < n_blocks * k; e += 32) lists[e] = src[e]; - __syncwarp(); - warp_merge_lists(lists, n_blocks, k, k, n_vocab, [&](int i, float v, int id) { - if (lane == 0) { sel_ids[i] = id < n_vocab ? id : 0; sel_logit[i] = v; } - }); - __syncwarp(); - sampled_tail_warp(sel_ids, sel_logit, k, p, t, out, ex); -} - -// ---- COUPLED DRAFT SAMPLING (include/strata/core/coupled_draft.hpp): the MTP draft layer samples its draft with the -// target's chain and the target's Philox draw. Everything that varies per request or per round - the chain's -// parameters, the seed, the counter (from the cell's step record), the penalty history - is read from DEVICE memory: -// these kernels are captured into the drafter's round/step graphs. One row, `nv` logits: the draft head's -// vocabulary subset (rt/draft_vocab.bin) or the whole vocabulary; `sub_to_id` maps a subset index to its token id. - -/// The round's inputs: the request's SamplerParams and the history base (the last h slots before `cap`), from -/// mapped host memory into the device copies the chain's kernels read. -__global__ void coupled_stage_kernel(const SamplerParams* __restrict__ mp, const int* __restrict__ mh, - SamplerParams* __restrict__ dp, int* __restrict__ ring, int cap) { - const volatile int* s = (const volatile int*) mp; - int* d = (int*) dp; - for (int i = threadIdx.x; i < (int) (sizeof(SamplerParams) / sizeof(int)); i += blockDim.x) d[i] = s[i]; - const int h = strata::core::coupled_hist_len(((const volatile SamplerParams*) mp)->penalty_last_n, cap); - const volatile int* vh = (const volatile int*) mh; - for (int i = cap - h + (int) threadIdx.x; i < cap; i += blockDim.x) ring[i] = vh[i]; -} - -/// The penalties, applied in place to the draft logits before the selection - the target applies the same -/// `apply_penalties` to the same token with the same count over the same window before its own. Draft j's window -/// is the ring's [cap + j - h, cap + j): the base plus drafts 0 .. j-1. A history token outside the draft head's -/// subset has no logit here. Each distinct token is penalised once: the entry whose `atomicOr` sets its bit does it. -__global__ void coupled_penalize_kernel(float* __restrict__ logits, int nv, const int* __restrict__ id_to_sub, - int id_vocab, const SamplerParams* __restrict__ dp, const int* __restrict__ ring, - int cap, int j) { - const SamplerParams p = *dp; - const int h = strata::core::coupled_hist_len(p.penalty_last_n, cap); - if (h <= 0) return; - const int* hrow = ring + strata::core::coupled_hist_start(cap, j, h); - extern __shared__ unsigned int seen[]; - const int words = (nv + 31) / 32; - for (int w = threadIdx.x; w < words; w += blockDim.x) seen[w] = 0u; - __syncthreads(); - for (int i = threadIdx.x; i < h; i += blockDim.x) { - const int v = hrow[i]; - if (v < 0 || v >= id_vocab) continue; - const int s = id_to_sub != nullptr ? id_to_sub[v] : v; - if (s < 0 || s >= nv) continue; - const unsigned bit = 1u << (s & 31); - if (atomicOr(&seen[s >> 5], bit) & bit) continue; - logits[s] = apply_penalties(logits[s], history_count(hrow, h, v), p); - } -} - -/// The merge of `sampler_split_merge_kernel` (lists of `kpart` entries, the request's top_k taken from them), then -/// `sampled_tail_warp` with the counter of the row that will verify this draft. Lane 0 maps the pick to its token -/// id, writes it and its probability, and appends it to the ring for the next draft's penalty window. -__global__ void __launch_bounds__(32) -coupled_merge_kernel(const int2* __restrict__ cand, int n_blocks, int nv, int kpart, - const SamplerParams* __restrict__ dp, const int* __restrict__ step_rec, - const int* __restrict__ sub_to_id, int* __restrict__ ring, int cap, int j, int* __restrict__ out_id, - float* __restrict__ out_prob) { - const int lane = (int) threadIdx.x; - SamplerParams p = *dp; - p.counter = strata::core::coupled_draft_counter((int64_t) step_rec[0]); - const int k = sampled_k(p.top_k, nv); // <= kpart: the first k of a union lie in the first k of each list - __shared__ int2 lists[kSplitMaxBlocks * kSelMax]; - __shared__ int sel_ids[kSelMax]; - __shared__ float sel_logit[kSelMax]; - __shared__ double ex[kSelMax]; - __shared__ int pick[1]; - __shared__ float prob[1]; - for (int e = lane; e < n_blocks * kpart; e += 32) lists[e] = cand[e]; - __syncwarp(); - warp_merge_lists(lists, n_blocks, kpart, k, nv, [&](int i, float v, int id) { - if (lane == 0) { sel_ids[i] = id < nv ? id : 0; sel_logit[i] = v; } - }); - __syncwarp(); - if (p.greedy || p.temperature <= 0.0f) { // never launched for greedy requests; the argmax, defensively - if (lane == 0) { pick[0] = sel_ids[0]; prob[0] = 1.0f; } - } else { - sampled_tail_warp(sel_ids, sel_logit, k, p, 0, pick, ex, prob); - } - __syncwarp(); - if (lane == 0) { - const int s = pick[0]; - const int id = sub_to_id != nullptr ? sub_to_id[s] : s; - *out_id = id; - *out_prob = prob[0]; - ring[cap + j] = id; - } -} - -// Which sampled path runs, read once: `STRATA_OLD_SAMPLER=1` is `sampler_kernel` (engine 0.1.20), -// `STRATA_SAMPLER_ONE_BLOCK=1` the one-block kernel; by default the split top_k wherever it applies. -enum class SampledPath { Split, OneBlock, Old }; - -bool env_flag(const char* name) { - const char* e = std::getenv(name); - return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0; -} - -SampledPath sampled_path() { - static const SampledPath path = env_flag("STRATA_OLD_SAMPLER") ? SampledPath::Old - : env_flag("STRATA_SAMPLER_ONE_BLOCK") ? SampledPath::OneBlock - : SampledPath::Split; - return path; -} - -// A stream being captured into a graph must not reach `split_scratch` (cudaMalloc): it -// gets the one-block kernel, which needs no memory of its own. The legacy stream cannot be captured. -bool stream_capturing(void* stream) { - if (stream == nullptr) return false; - cudaStreamCaptureStatus st = cudaStreamCaptureStatusNone; - if (cudaStreamIsCapturing((cudaStream_t) stream, &st) != cudaSuccess) { - (void) cudaGetLastError(); - return true; - } - return st != cudaStreamCaptureStatusNone; -} - -// The split's block lists, one buffer per (device, stream): launches on one stream run in order, so a stream reuses -// its buffer with no sync, and two streams never share one. Grown on demand (at least doubling, up to the size of -// `kSplitMaxRows` rows at the widest vocabulary: 2 MB), never shrunk. A grown-out buffer is retired, not freed: a -// pointer handed out earlier (to another host thread on the same stream, say) may still be waiting for its launch, -// and freeing it would need a sync that proves nothing about that thread. Doubling keeps a slot's retired buffers -// smaller than its live one, so a slot holds about 4 MB at most (0.5 MB for the engine's <= 16 rows). nullptr -// when the memory cannot be had, and the caller falls back to the one-block kernel; a failed grow is remembered, so -// later calls of that size do not retry cudaMalloc each time. -int2* split_scratch(void* stream, size_t entries) { - struct Slot { - int device; - void* stream; - int2* ptr; - size_t entries; - size_t failed; // the smallest size cudaMalloc refused (0: none) - }; - static std::mutex mu; - static std::vector slots; - static std::vector retired; - int device = 0; - if (cudaGetDevice(&device) != cudaSuccess) { - (void) cudaGetLastError(); - return nullptr; - } - std::lock_guard lock(mu); - Slot* slot = nullptr; - for (Slot& s : slots) - if (s.device == device && s.stream == stream) slot = &s; - if (slot == nullptr) { - slots.push_back({device, stream, nullptr, 0, 0}); - slot = &slots.back(); - } - if (slot->entries >= entries) return slot->ptr; - if (slot->failed != 0 && entries >= slot->failed) return nullptr; - constexpr size_t kCap = (size_t) kSplitMaxRows * kSplitMaxBlocks * kSelMax; - size_t want = 2 * slot->entries < kCap ? 2 * slot->entries : kCap; - if (want < entries) want = entries; - int2* ptr = nullptr; - if (cudaMalloc(&ptr, want * sizeof(int2)) != cudaSuccess) { - (void) cudaGetLastError(); - want = entries; - if (cudaMalloc(&ptr, want * sizeof(int2)) != cudaSuccess) { - (void) cudaGetLastError(); - slot->failed = entries; - return nullptr; - } - } - if (slot->ptr != nullptr) retired.push_back(slot->ptr); - slot->ptr = ptr; - slot->entries = want; - return ptr; -} - -} // namespace - -bool sample_greedy_cluster(const float* logits, int n_tokens, int n_vocab, int* out, void* stream) { -#if defined(__HIPCC__) - (void) logits; (void) n_tokens; (void) n_vocab; (void) out; (void) stream; - return false; -#else - if (n_tokens <= 0 || n_vocab <= 0) return true; - if (n_tokens > 65535) return false; - // Per device (a layer split runs on several): 1 the cluster kernel runs here, 2 it does not - sm_90+ (the card's, - // or STRATA_EMULATE_CC's), code built for it (an older build's PTX holds a trap: the PTX version says which), and - // room for one cluster of kAmCtas CTAs. - static int ok[64] = {}; - int dev = 0; - if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } - cudaLaunchConfig_t cfg{}; - cudaLaunchAttribute at[1]; - at[0].id = cudaLaunchAttributeClusterDimension; - at[0].val.clusterDim.x = kAmCtas; - at[0].val.clusterDim.y = 1; - at[0].val.clusterDim.z = 1; - cfg.gridDim = dim3(kAmCtas, 1, 1); - cfg.blockDim = dim3(kAmThreads, 1, 1); - cfg.dynamicSmemBytes = 0; - cfg.stream = (cudaStream_t) stream; - cfg.attrs = at; - cfg.numAttrs = 1; - if (ok[dev] == 0) { - int major = 0, clusters = 0; - cudaFuncAttributes fa{}; - const bool runs = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess && - strata::cc_major_of(major) >= 9 && - cudaFuncGetAttributes(&fa, sampler_greedy_cluster_kernel) == cudaSuccess && - fa.ptxVersion >= 90 && fa.binaryVersion >= 90 && - cudaOccupancyMaxActiveClusters(&clusters, sampler_greedy_cluster_kernel, &cfg) == - cudaSuccess && - clusters >= 1; - cudaGetLastError(); - ok[dev] = runs ? 1 : 2; - } - if (ok[dev] != 1) return false; - cfg.gridDim = dim3(kAmCtas, (unsigned) n_tokens, 1); - const cudaError_t e = cudaLaunchKernelEx(&cfg, sampler_greedy_cluster_kernel, logits, n_vocab, out); - if (e != cudaSuccess) { - std::fprintf(stderr, "sample_tokens cluster launch: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - return true; -#endif -} - -void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len, - const SamplerParams& p, int* out, void* stream) { - if (n_tokens <= 0 || n_vocab <= 0) return; - if (p.penalty_last_n > 0 && (history == nullptr || history_len <= 0)) { - std::fprintf(stderr, "sample_tokens: penalty_last_n %d needs a history (got %p, len %d)\n", - p.penalty_last_n, (const void*) history, history_len); - std::exit(1); - } - const unsigned shmem = (history != nullptr && history_len > 0 && p.penalty_last_n > 0) - ? (unsigned) ((n_vocab + 31) / 32) * sizeof(unsigned) // the penalty bitmap - : 0; - if (p.greedy || p.temperature <= 0.0f) { - // Without penalties (shmem == 0: no window) on sm_90+, a cluster of CTAs per token - the same token; see - // `sampler_greedy_cluster_kernel`. STRATA_ARGMAX_MULTI=0: always the one-block kernel. - static const bool multi = [] { - const char* v = std::getenv("STRATA_ARGMAX_MULTI"); - return !v || std::atoi(v) != 0; - }(); - // One block per token, 1,024 threads over the vocabulary. See `sampler_greedy_kernel`. - const int gthreads = 1024; - if (!(multi && shmem == 0 && sample_greedy_cluster(logits, n_tokens, n_vocab, out, stream))) - sampler_greedy_kernel<<<(unsigned) n_tokens, gthreads, shmem, (cudaStream_t) stream>>>( - logits, n_vocab, history, history_len, p, p.penalty_last_n, p.penalty_last_n, out); - } else if (sampled_path() == SampledPath::Old) { - // The same block-per-token shape: the selection's k argmax rounds reduce inside the block. See - // `sampler_kernel`'s header for what the old one-thread-per-token launch cost. - sampler_kernel<<<(unsigned) n_tokens, 1024, shmem, (cudaStream_t) stream>>>( - logits, n_vocab, n_tokens, history, history_len, p, out); - } else { - // The split top_k by default: stage 1 over (61 blocks x rows) for 248,320 logits, stage 2 one warp per - // row. The one-block kernel when asked for, or when the split cannot run: a wider vocabulary than the merge - // holds, more than `kSplitMaxRows` rows (the engine samples at most a verify window), a stream under capture, - // no scratch. - const int k = sampled_k(p.top_k, n_vocab); - const int n_blocks = (n_vocab + kSplitBlockSpan - 1) / kSplitBlockSpan; - int2* scratch = nullptr; - if (sampled_path() == SampledPath::Split && n_blocks <= kSplitMaxBlocks && n_tokens <= kSplitMaxRows && - !stream_capturing(stream)) - // sized for 16 rows and 64 entries at least, so a verify window or a wider top_k does not regrow it - scratch = split_scratch(stream, (size_t) (n_tokens > 16 ? n_tokens : 16) * n_blocks * kSelMax); - if (scratch != nullptr) { - sampler_split_part_kernel<<>>(logits, n_vocab, history, history_len, p, k, - n_blocks, scratch); - sampler_split_merge_kernel<<<(unsigned) n_tokens, 32, 0, (cudaStream_t) stream>>>( - scratch, n_blocks, n_vocab, p, k, out); - } else { - sampler_one_block_kernel<<<(unsigned) n_tokens, 1024, shmem, (cudaStream_t) stream>>>( - logits, n_vocab, history, history_len, p, out); - } - } - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "sample_tokens launch: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - if (stream == nullptr) cudaDeviceSynchronize(); -} - -namespace { -int coupled_blocks(int nv) { return (nv + kSplitBlockSpan - 1) / kSplitBlockSpan; } -int coupled_kpart(int nv) { return nv < kSelMax ? nv : kSelMax; } -void coupled_check(const char* what) { - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { - std::fprintf(stderr, "%s launch: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} -} // namespace - -size_t coupled_draft_scratch_bytes(int nv) { - if (nv <= 0 || coupled_blocks(nv) > kSplitMaxBlocks) return 0; - return (size_t) coupled_blocks(nv) * (size_t) kSelMax * sizeof(int2); -} - -void coupled_draft_stage(const SamplerParams* mapped_params, const int32_t* mapped_hist, SamplerParams* params, - int32_t* ring, int cap, void* stream) { - coupled_stage_kernel<<<1, 256, 0, (cudaStream_t) stream>>>(mapped_params, mapped_hist, params, ring, cap); - coupled_check("coupled_draft_stage"); -} - -void coupled_draft_sample(float* logits, int nv, const int32_t* sub_to_id, const int32_t* id_to_sub, int id_vocab, - const SamplerParams* params, int32_t* ring, int cap, int j, const int32_t* step_rec, - void* scratch, int32_t* out_id, float* out_prob, void* stream) { - const cudaStream_t s = (cudaStream_t) stream; - const int n_blocks = coupled_blocks(nv), kpart = coupled_kpart(nv); - if (nv <= 0 || n_blocks > kSplitMaxBlocks || scratch == nullptr) { - std::fprintf(stderr, "coupled_draft_sample: %d logits need scratch and at most %d blocks\n", nv, kSplitMaxBlocks); - std::exit(1); - } - coupled_penalize_kernel<<<1, 1024, (unsigned) ((nv + 31) / 32) * sizeof(unsigned), s>>>(logits, nv, id_to_sub, - id_vocab, params, ring, cap, j); - coupled_check("coupled_penalize"); - // the selection of the split sampler, unchanged: every 4,096-logit block's first `kpart` (the widest list, - // since the request's top_k is only known on the device), penalties already applied above - sampler_split_part_kernel<<>>( - logits, nv, nullptr, 0, SamplerParams{}, kpart, n_blocks, (int2*) scratch); - coupled_check("coupled_draft split part"); - coupled_merge_kernel<<<1, 32, 0, s>>>((const int2*) scratch, n_blocks, nv, kpart, params, step_rec, sub_to_id, ring, - cap, j, out_id, out_prob); - coupled_check("coupled_draft merge"); -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/shared_expert.cu b/src/kernels/cuda/shared_expert.cu deleted file mode 100644 index 28bb7ed..0000000 --- a/src/kernels/cuda/shared_expert.cu +++ /dev/null @@ -1,384 +0,0 @@ -// src/kernels/cuda/shared_expert.cu - P2.S2: the shared expert. -// -// `ref/moe.py::shared_expert`, transcribed: -// -// h = silu(x @ gate_shexp.T) * (x @ up_shexp.T) <- SILU GOES ON GATE, not on up -// h = h @ down_shexp.T (nt, n_embd) -// g = sigmoid(x @ gate_inp_shexp) (nt,) ONE SCALAR PER TOKEN -// return h * g[:, None] -// -// TWO THINGS HERE WERE BELIEVED WRONG FOR MANY ROUNDS and `docs/semantics.md` records both. SILU GOES ON THE -// GATE TENSOR: the opposite reading is plausible, produces the right shapes, and is wrong. And -// `ffn_gate_inp_shexp` is `(n_embd,)` whose output is "one value per token" - a SCALAR gate obtained by dotting -// that vector with the hidden state, NOT a per-expert gate and NOT a per-dimension elementwise one. Both were -// live readings of the same shapes until the source comment settled them. -// -// The result is ADDED to the routed output - not router-weighted, not renormalised against it. -// -// The legacy canonical projections use their explicit Q8_0/Q8_K activation images. The optional native -// BF16 path affects only the scalar gate: it reads the original F32 input and uses pinned CUDA MMVF plus -// an FP32 sigmoid. Native projection overrides independently select CUDA Q8_1 MMVQ and FP32 SwiGLU. -#include "strata/kernels/shared_expert.hpp" -#include "strata/kernels/bf16_gemv.hpp" -#include "strata/kernels/bf16_bits.hpp" -#include "strata/kernels/f16_bits.hpp" -#include "strata/kernels/quantize_act.hpp" -#include "strata/kernels/s2_gemv_q8.hpp" -#include "strata/kernels/s_gemv.hpp" -#include "strata/kernels/native_mmvq.hpp" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int THREADS = 128; -bool native_bf16 = false; - -// `f32_to_f16` used to live here as a private copy. Round 198 found it - and the identical one in -// `quantize_act.cu` - returning a NaN for every FINITE value that overflows fp16 (1e30, 65536, 1e45) instead -// of saturating to inf, because `exp >= 31` conflates an f32 inf/NaN with an out-of-range finite exponent. -// This file's fixture is all O(1), so it could not see it. The conversion now lives in one place, with the -// regimes spelled out. - -// silu(x) = x / (1 + exp(-x)), written as `ref/moe.py` writes it, in DOUBLE then cast - the reference works in -// float64 and a float32 exp differs in the last bits. The multiplication by `up` is the reference's order. -__global__ void swiglu_kernel(const float* __restrict__ gate, const float* __restrict__ up, - float* __restrict__ out, int n) { - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n) return; - const double x = (double) gate[i]; - out[i] = (float) (x / (1.0 + exp(-x))) * up[i]; -} - -__global__ void native_swiglu_kernel(const float* gate, const float* up, float* out, int n) { - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n) return; - // Pinned CUDA unary.cuh op_silu, then unary_gated_op_kernel's multiply. - // Explicit intrinsics reproduce its --use_fast_math operations without - // changing compilation of the default legacy arithmetic in this file. - out[i] = __fdividef(gate[i], 1.0f + __expf(-gate[i])) * up[i]; -} - -__global__ void to_f16_kernel(const float* __restrict__ in, uint16_t* __restrict__ out, int n) { - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) out[i] = f16_from_f32(in[i]); -} - -// The per-token scalar gate: sigmoid(dot(x, w)) with w = `ffn_gate_inp_shexp` (n_embd,). -// -// **ONE THREAD WAS THE LARGEST SINGLE KERNEL IN THE MODEL, AND THE COMMENT DEFENDING IT SAID WHY IT SHOULD -// NOT BE.** It read: "n_embd is 2560, so this is a short serial loop and the parallelism is elsewhere." -// 2560 iterations is not short when each one is a DOUBLE multiply-add. This card's double rate is **1/64** of -// its float rate, so the loop is a 2560-long dependency chain through a 1/64-rate unit - tens of microseconds -// from the chain alone, before counting 2560 sequential global loads issued by one thread with no coalescing. -// -// MEASURED, and this is what the number looks like from outside: `shared_expert` is **0.2374 ms of a -// 0.8883 ms block - 26.7% of the whole block, 11.4 ms per token** - for three projections that read 5.5 MB and -// whose memory floor is 0.009 ms. It is seven kernels, and six of them are GEMVs or elementwise passes over -// 640-2560 elements. This is the one that cannot be explained by bandwidth. -// -// THE DOUBLE ACCUMULATOR IS KEPT. `ref/gr.py` reduces in float64 and `block_sum` in `gr.cu` exists for the -// same reason - the summation order of a tree is not the reference's, so the defence is enough precision that -// the order stops mattering. What changes is the CHAIN: ten terms per thread instead of 2560, then a -// tree-reduce. Through a sigmoid, a 1e-16 relative difference in the dot is not a difference. -// -// **BOTH OPERANDS ARE BF16, AND THAT IS THE REFERENCE'S CONTRACT, NOT A STORAGE DETAIL.** `gate_inp_shexp` is a -// BF16 weight, so ggml converts the activation to its `vec_dot_type` - BF16 - exactly as it does for the router -// (`docs/activation-contract.md`). This kernel used to take `const float* w` while the LOADER had already -// re-rounded the tensor to 2 B/elem, so it read 2560 floats out of a 5120-byte buffer: 5120 B past the end of -// the tensor, inside the 4.5 GiB arena, where nothing faults. The dot came out astronomically large, sigmoid -// saturated to 1.0, and `scale_kernel` multiplied the shared expert's output by it - which is why the FIRST -// symptom was 2560 non-finite outputs rather than a wrong scalar. -// -// A wrong scalar here is the quiet failure mode: sigmoid bounds the damage to [0,1], so a gate that should be -// 0.5 and reads 1.0 scales the shared expert by 2x and produces perfectly finite, perfectly plausible logits. -__device__ __forceinline__ double warp_sum_d(double v) { - for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off); - return __shfl_sync(0xFFFFFFFFu, v, 0); -} - -__global__ void scalar_gate_kernel(const uint16_t* __restrict__ x_bf16, const uint16_t* __restrict__ w_bf16, - float* __restrict__ out, int n_embd) { - __shared__ double scratch[8]; // 8 warps: the launch is <<<1, 256>>> - double acc = 0.0; - for (int i = threadIdx.x; i < n_embd; i += blockDim.x) - acc += (double) f32_from_bf16(x_bf16[i]) * (double) f32_from_bf16(w_bf16[i]); - __syncthreads(); - const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; - acc = warp_sum_d(acc); - if (lane == 0) scratch[warp] = acc; - __syncthreads(); - const int nw = ((int) blockDim.x + 31) >> 5; - if (warp == 0) { - acc = (threadIdx.x < nw) ? scratch[threadIdx.x] : 0.0; - acc = warp_sum_d(acc); - if (threadIdx.x == 0) out[0] = (float) (1.0 / (1.0 + exp(-acc))); - } -} - -__global__ void scale_kernel(float* __restrict__ out, const float* __restrict__ g, int n) { - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) out[i] *= g[0]; -} - -__global__ void native_scalar_sigmoid_kernel(float* gate) { - // Match the single-token CUDA sigmoid's FP32 fast-math operations without changing legacy kernels' - // compilation flags. The dot product was already reduced by the pinned native MMVF implementation. - gate[0] = __fdividef(1.0f, 1.0f + __expf(-gate[0])); -} -__global__ void native_scalar_sigmoid_multi_kernel(float* gate) { // thread t = token t, same expression - gate[threadIdx.x] = __fdividef(1.0f, 1.0f + __expf(-gate[threadIdx.x])); -} - -/// The MoE block's final combination. See the header for the two readings it exists to pin. -__global__ void moe_combine_kernel(const float* __restrict__ parts, const float* __restrict__ weights, - const float* __restrict__ shared, float* __restrict__ y, int n_embd, - int k, int has_shared) { - const int j = blockIdx.x * blockDim.x + threadIdx.x; - if (j >= n_embd) return; - // Accumulate in DOUBLE, in the reference's own order (`for i in range(k): out[t] += w[t,i] * g[0]`). - // f32 would be defensible for ten terms, but the reference is float64 and this is one line. - double acc = 0.0; - for (int e = 0; e < k; ++e) acc += (double) weights[e] * (double) parts[(size_t) e * n_embd + j]; - // The SHARED output is added PLAIN - not router-weighted, not renormalised against the routed sum. - if (has_shared) acc += (double) shared[j]; - y[j] = (float) acc; -} - -} // namespace - -void shared_expert_set_native_bf16(bool enabled) { native_bf16 = enabled; } -bool shared_expert_native_bf16_enabled() { return native_bf16; } - -namespace { -__global__ void scale_rows_kernel(float* __restrict__ out, const float* __restrict__ g, int n) { - const int t = blockIdx.y; - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) out[(size_t) t * n + i] *= g[t]; -} - -__global__ void sigmoid_scale_rows_kernel(float* __restrict__ out, const float* __restrict__ g, int n) { - const int t = blockIdx.y; - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) { - const float gt = __fdividef(1.0f, 1.0f + __expf(-g[t])); - out[(size_t) t * n + i] *= gt; - } -} - -bool fused_swiglu_q81_enabled() { - static const bool on = [] { - const char* v = std::getenv("STRATA_FUSED_SWIGLU_Q81"); - return v == nullptr || std::atoi(v) != 0; - }(); - return on; -} -} // namespace - -void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, const NativeSharedWeights& nw, - const uint16_t* gate_inp_bf16, float* gate, float* up, float* g, float* out, int64_t n_embd, - int64_t n_ff, void* stream) { - if (n_tok < 1 || n_tok > 8 || !nw.q8_1 || !nw.gate_data || !nw.up_data || !nw.down_data || !stream) - throw std::invalid_argument("shared_expert_multi: needs 1..8 tokens, native weights, scratch and a stream"); - cudaStream_t cs = (cudaStream_t) stream; - const void* x_q8_1 = nw.x_q8_1; - if (!x_q8_1) { - native_quantize_q8_1(x, nw.q8_1, (int) n_embd, n_tok, stream); - x_q8_1 = nw.q8_1; - } - native_mmvq(nw.gate_type, nw.gate_data, x_q8_1, gate, (int) n_embd, (int) n_ff, n_tok, stream); - native_mmvq(nw.up_type, nw.up_data, x_q8_1, up, (int) n_embd, (int) n_ff, n_tok, stream); - const int n = (int) (n_ff * n_tok); - if (fused_swiglu_q81_enabled()) { - native_swiglu_quantize_q8_1(gate, up, nw.q8_1, (int) n_ff, n_tok, stream); - } else { - native_swiglu_kernel<<<(unsigned) ((n + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate, up, gate, n); - native_quantize_q8_1(gate, nw.q8_1, (int) n_ff, n_tok, stream); - } - native_mmvq(nw.down_type, nw.down_data, nw.q8_1, out, (int) n_ff, (int) n_embd, n_tok, stream); - static const bool batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }(); - if (native_bf16 && batch && n_tok > 1) { // one gemv for all rows (outputs identical), fused sigmoid+scale - bf16_gemv_fp32_mmvf_multi(x, n_embd, gate_inp_bf16, g, 1, n_embd, 1, n_tok, stream); - sigmoid_scale_rows_kernel<<>>( - out, g, (int) n_embd); - } else if (native_bf16 && n_tok == 1) { - bf16_gemv_fp32_mmvf(x, gate_inp_bf16, g, n_embd, 1, stream); - sigmoid_scale_rows_kernel<<>>( - out, g, (int) n_embd); - } else { - for (int t = 0; t < n_tok; ++t) { - if (native_bf16) { - bf16_gemv_fp32_mmvf(x + (size_t) t * n_embd, gate_inp_bf16, g + t, n_embd, 1, stream); - native_scalar_sigmoid_kernel<<<1, 1, 0, cs>>>(g + t); - } else { - scalar_gate_kernel<<<1, 256, 0, cs>>>(x_bf16 + (size_t) t * n_embd, gate_inp_bf16, g + t, (int) n_embd); - } - } - scale_rows_kernel<<>>( - out, g, (int) n_embd); - } - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) throw std::runtime_error(std::string("shared_expert_multi: ") + cudaGetErrorString(e)); -} - -uint64_t shared_expert_scratch_bytes(int64_t n_ff) { - // gate (n_ff f32) | up (n_ff f32) | q8_0 (n_ff/32*34) | q8k (n_ff/256*292) | g (1 f32), 16-byte aligned - const uint64_t a = ((uint64_t) n_ff * 4 + 15) & ~15ull; - const uint64_t q0 = ((uint64_t) (n_ff / 32) * 34 + 15) & ~15ull; - const uint64_t qk = ((uint64_t) (n_ff / 256) * 292 + 15) & ~15ull; - return a * 2 + q0 + qk + 32; -} - -void shared_expert(const uint8_t* x_q8_0, const uint8_t* x_q8k, const uint16_t* x_bf16, const SForm& gate_form, - const uint8_t* gate_codes, const float* gate_scales, const float* gate_off, - const SForm& up_form, const uint8_t* up_codes, const float* up_scales, const float* up_off, - const SForm& down_form, const uint8_t* down_codes, const float* down_scales, - const float* down_off, const uint16_t* gate_inp_bf16, float* scratch, float* out, - int64_t n_embd, int64_t n_ff, int tpr, void* stream, const float* x_f32, - const NativeSharedWeights* native) { - if (n_embd <= 0 || n_ff <= 0) return; - const bool use_native = native_bf16; - const bool native_gate = native && native->gate_data && native_mmvq_supported(native->gate_type); - const bool native_up = native && native->up_data && native_mmvq_supported(native->up_type); - const bool native_down = native && native->down_data && native_mmvq_supported(native->down_type); - const bool native_projection = native_gate || native_up || native_down; - if ((use_native || native_gate || native_up) && !x_f32) - throw std::invalid_argument("shared_expert native input projection requires unrounded x_f32"); - if (native_projection) { - if (!native->q8_1 || !stream || n_embd > INT_MAX || n_ff > INT_MAX) - throw std::invalid_argument("shared_expert native projections require scratch, stream and int32 dimensions"); - // Validate every active shape before any kernel is enqueued. - if (native_gate) native_mmvq_weight_bytes(native->gate_type, (int) n_embd, (int) n_ff); - if (native_up) native_mmvq_weight_bytes(native->up_type, (int) n_embd, (int) n_ff); - if (native_down) native_mmvq_weight_bytes(native->down_type, (int) n_ff, (int) n_embd); - } - if (scratch == nullptr) { - std::fprintf(stderr, "shared_expert: scratch is null; the caller owns it " - "(see shared_expert_scratch_bytes)\n"); - std::exit(1); - } - // CARVED FROM THE CALLER'S SCRATCH. This used to be four `cudaMalloc`s and four `cudaFree`s per call, which - // is illegal during stream capture AND a token-path allocation - P2.T10 forbids both. - uint8_t* p = (uint8_t*) scratch; - const uint64_t a = ((uint64_t) n_ff * 4 + 15) & ~15ull; - const uint64_t q0 = ((uint64_t) (n_ff / 32) * 34 + 15) & ~15ull; - const uint64_t qk = ((uint64_t) (n_ff / 256) * 292 + 15) & ~15ull; - float* gate = (float*) p; - float* up = (float*) (p + a); - uint8_t* h_q8_0 = (uint8_t*) (p + a * 2); - uint8_t* h_q8k = (uint8_t*) (p + a * 2 + q0); - float* g = (float*) (p + a * 2 + q0 + qk); - - // WHICH ACTIVATION THIS PROJECTION WANTS, READ FROM ITS OWN FORM. See `SForm::act_kind`: the three - // families cannot be told apart by the other fields, so the kind is carried rather than derived. - auto gemv = [&](const SForm& f, const uint8_t* codes, const float* scales, const float* off, - const uint8_t* act80, const uint8_t* actq8k, float* y, int64_t nin, int64_t nout) { - if (f.code_bits == 2) { - s2_gemv_q8(act80, codes, scales, y, nin, nout, tpr, stream); - } else if (f.act_kind == 1) { - s_gemv_q8k_split(actq8k, codes, scales, off, y, nin, nout, f, stream); - } else { - s_gemv_q8_0_split(act80, codes, scales, off, y, nin, nout, f, stream); - } - }; - - const unsigned g_ff = (unsigned) ((n_ff + THREADS - 1) / THREADS); - const unsigned g_embd = (unsigned) ((n_embd + THREADS - 1) / THREADS); - - // gate and up projections, then silu(gate) * up in place in `gate` - if (native_gate || native_up) - native_quantize_q8_1(x_f32, native->q8_1, (int) n_embd, 1, stream); - if (native_gate) - native_mmvq(native->gate_type, native->gate_data, native->q8_1, gate, (int) n_embd, (int) n_ff, 1, stream); - else - gemv(gate_form, gate_codes, gate_scales, gate_off, x_q8_0, x_q8k, gate, n_embd, n_ff); - if (native_up) - native_mmvq(native->up_type, native->up_data, native->q8_1, up, (int) n_embd, (int) n_ff, 1, stream); - else - gemv(up_form, up_codes, up_scales, up_off, x_q8_0, x_q8k, up, n_embd, n_ff); - if (native_projection && native_down && fused_swiglu_q81_enabled()) { - native_swiglu_quantize_q8_1(gate, up, native->q8_1, (int) n_ff, 1, stream); - native_mmvq(native->down_type, native->down_data, native->q8_1, out, (int) n_ff, (int) n_embd, 1, stream); - } else { - if (native_projection) - native_swiglu_kernel<<>>(gate, up, gate, (int) n_ff); - else - swiglu_kernel<<>>(gate, up, gate, (int) n_ff); - - // down: (n_ff) -> (n_embd), and THE INTERMEDIATE IS QUANTIZED TO THE DOWN WEIGHT'S OWN CONTRACT - which is - // what `ggml_mul_mat` does for every matmul in the model. It used to be rounded to fp16 with no - // justification beyond "the kernel takes fp16". - if (native_down) { - native_quantize_q8_1(gate, native->q8_1, (int) n_ff, 1, stream); - native_mmvq(native->down_type, native->down_data, native->q8_1, out, (int) n_ff, (int) n_embd, 1, stream); - } else if (down_form.act_kind == 1) { - if (n_ff % 256 != 0) { - std::fprintf(stderr, "shared_expert: the down weight wants Q8_K but n_ff %lld is not a multiple " - "of 256; Q8_K is structurally impossible here\n", (long long) n_ff); - std::exit(1); - } - quantize_q8_K(gate, h_q8k, n_ff, stream); - gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd); - } else if (down_form.code_bits == 2) { - quantize_q8_0(gate, h_q8_0, n_ff, stream); - gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd); - } else { - quantize_q8_0(gate, h_q8_0, n_ff, stream); - gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd); - } - } - - // the per-token scalar gate, then the multiply. Note the gate is computed from `x`, the ORIGINAL hidden - // state, not from anything the expert produced. The historical branch uses BF16-rounded inputs; the - // native branch uses the pinned CUDA FP32 activation contract. - // `<<<1, 256>>>`: one block, because the output is ONE scalar and a second block would only add a global - // round trip. 256 threads is the reduction's width, not the problem's size. - if (use_native) { - bf16_gemv_fp32_mmvf(x_f32, gate_inp_bf16, g, n_embd, 1, stream); - sigmoid_scale_rows_kernel<<>>(out, g, (int) n_embd); - } else { - scalar_gate_kernel<<<1, 256, 0, (cudaStream_t) stream>>>(x_bf16, gate_inp_bf16, g, (int) n_embd); - scale_kernel<<>>(out, g, (int) n_embd); - } - - if (stream == nullptr) { - const cudaError_t e = cudaDeviceSynchronize(); - if (e != cudaSuccess) { - std::fprintf(stderr, "shared_expert: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - } -} - -void moe_combine(const float* parts, const float* weights, const float* shared, float* y, int64_t n_embd, - int64_t k, void* stream) { - if (n_embd <= 0 || k <= 0) return; - // k > 64 is refused rather than truncated: silently summing the first 64 of a longer list would be a - // wrong answer that looks like a right one, and no geometry in this artifact comes close to it. - if (k > 64) { - std::fprintf(stderr, "moe_combine: k = %lld exceeds 64\n", (long long) k); - std::exit(1); - } - const unsigned grid = (unsigned) ((n_embd + THREADS - 1) / THREADS); - moe_combine_kernel<<>>(parts, weights, shared, y, (int) n_embd, - (int) k, shared != nullptr); - if (stream == nullptr) { - const cudaError_t e = cudaDeviceSynchronize(); - if (e != cudaSuccess) { - std::fprintf(stderr, "moe_combine: %s\n", cudaGetErrorString(e)); - std::exit(1); - } - } -} - -} // namespace strata::kernels diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu deleted file mode 100644 index 77f4de5..0000000 --- a/src/kernels/cuda/verify_kernels.cu +++ /dev/null @@ -1,685 +0,0 @@ -// src/kernels/cuda/verify_kernels.cu - see include/strata/kernels/verify_kernels.hpp. -// -// The per-token arithmetic of every kernel here is transcribed from its single-token original (fused_gdn.cu, -// elementwise.cu) with the same operation order, so a verify window reproduces plain decode bit for bit. -#include "strata/kernels/verify_kernels.hpp" -#include "strata/kernels/dp4a.hpp" - -#include - -#include -#include - -namespace strata::kernels { -namespace { - -constexpr int S = 128; // GDN state size -constexpr int RG = 4; -constexpr int RPG = S / RG; - -void check(const char* what) { - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(1); } -} - -__global__ void __launch_bounds__(S) gdn_conv_l2_multi_kernel(const float* __restrict__ hist, - const float* __restrict__ qkv, - const float* __restrict__ w, float* __restrict__ h, - int C, int qk_heads, float eps, int t_begin) { - __shared__ float part[S / 32]; - const int t = t_begin + blockIdx.y; - const int c = blockIdx.x * S + threadIdx.x; - // the window of token t: [hist0, hist1, hist2, x_0, ..., x_t], its last four entries - float win[3]; -#pragma unroll - for (int j = 0; j < 3; ++j) { - const int src = t + j; // index into [hist(3) | x...] - win[j] = src < 3 ? hist[c * 3 + src] : qkv[(size_t) (src - 3) * C + c]; - } - const float v0 = win[0], v1 = win[1], v2 = win[2], x = qkv[(size_t) t * C + c]; - float sum = v0 * w[c * 4] + v1 * w[c * 4 + 1] + v2 * w[c * 4 + 2] + x * w[c * 4 + 3]; - float y = sum / (1.0f + __expf(-sum)); - if ((int) blockIdx.x < qk_heads) { - float sq = y * y; - for (int o = 16; o > 0; o >>= 1) sq += __shfl_xor_sync(0xffffffffu, sq, o); - if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sq; - __syncthreads(); - const float ss = part[0] + part[1] + part[2] + part[3]; - y *= rsqrtf(ss + eps); - } - h[(size_t) t * C + c] = y; -} - -__global__ void gdn_conv_commit_kernel(float* __restrict__ hist, const float* __restrict__ qkv, int C, - const int32_t* __restrict__ n_keep) { - const int c = blockIdx.x * blockDim.x + threadIdx.x; - if (c >= C) return; - const int n = *n_keep; - if (n <= 0) return; - float seq[3]; -#pragma unroll - for (int j = 0; j < 3; ++j) { - const int src = n + j; // the last three of [hist(3) | x_0..x_{n-1}] - seq[j] = src < 3 ? hist[c * 3 + src] : qkv[(size_t) (src - 3) * C + c]; - } - hist[c * 3] = seq[0]; - hist[c * 3 + 1] = seq[1]; - hist[c * 3 + 2] = seq[2]; -} - -template -__global__ void __launch_bounds__(64) gdn_ab_multi_kernel(const float* __restrict__ x, const uint16_t* __restrict__ wa, - const uint16_t* __restrict__ wb, - const float* __restrict__ dt, - const float* __restrict__ ssm_a, float* __restrict__ gate, - float* __restrict__ beta, int n, int h_v, int T) { - const int row = blockIdx.x * 2 + (threadIdx.x >> 5), lane = threadIdx.x & 31; - if (row >= 2 * h_v) return; - const bool is_beta = row >= h_v; - const int r = is_beta ? row - h_v : row; - const uint4* w4 = reinterpret_cast((is_beta ? wb : wa) + (size_t) r * n); - float acc[MAX_T]; -#pragma unroll - for (int t = 0; t < MAX_T; ++t) acc[t] = 0.0f; - for (int j = lane; j < n / 8; j += 32) { - const uint4 wv = __ldg(w4 + j); -#pragma unroll - for (int t = 0; t < MAX_T; ++t) { - if (t >= T) break; - const float* xt = x + (size_t) t * n; - const float4 xa = *reinterpret_cast(xt + j * 8); - const float4 xb = *reinterpret_cast(xt + j * 8 + 4); - float a = acc[t]; - a = fmaf(__uint_as_float(wv.x << 16), xa.x, a); a = fmaf(__uint_as_float(wv.x & 0xffff0000u), xa.y, a); - a = fmaf(__uint_as_float(wv.y << 16), xa.z, a); a = fmaf(__uint_as_float(wv.y & 0xffff0000u), xa.w, a); - a = fmaf(__uint_as_float(wv.z << 16), xb.x, a); a = fmaf(__uint_as_float(wv.z & 0xffff0000u), xb.y, a); - a = fmaf(__uint_as_float(wv.w << 16), xb.z, a); a = fmaf(__uint_as_float(wv.w & 0xffff0000u), xb.w, a); - acc[t] = a; - } - } -#pragma unroll - for (int t = 0; t < MAX_T; ++t) { - if (t >= T) break; - float a = acc[t]; - for (int o = 16; o > 0; o >>= 1) a += __shfl_xor_sync(0xffffffffu, a, o); - if (lane != 0) continue; - if (is_beta) { - beta[(size_t) t * h_v + r] = 1.0f / (1.0f + __expf(-a)); - } else { - const float v = a + dt[r]; - const float sp = v > 20.0f ? v : log1pf(__expf(v)); - gate[(size_t) t * h_v + r] = sp * ssm_a[r]; - } - } -} - -// State-only commit kernel: each head's 128 independent state columns are split across 4 blocks of 32 columns -// (48 * 4 = 192 blocks of 128 threads across all SMs, vs 48 blocks of 512 threads), with no sq/o/norm/z/y work. -__global__ void __launch_bounds__(32 * RG) gdn_step_commit_kernel(float* __restrict__ state, - const float* __restrict__ hbuf, int C, - const float* __restrict__ gate, - const float* __restrict__ beta, - int h_k, int h_v, - const int32_t* __restrict__ n_keep) { - const int n = *n_keep; - if (n <= 0) return; - __shared__ float sk[S]; - __shared__ float red[RG][32]; - const int head = blockIdx.x; - const int col_local = threadIdx.x; - const int col = blockIdx.y * 32 + col_local; - const int rg = threadIdx.y; - const int tid = rg * 32 + col_local; // 0 .. 127 - const int qh = head % h_k; - const int qk = S * h_k; - float s[RPG]; - float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col; - const size_t row_stride = (size_t) h_v * S; -#pragma unroll - for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride]; - for (int t = 0; t < n; ++t) { - const float* ht = hbuf + (size_t) t * C; - __syncthreads(); - sk[tid] = ht[qk + qh * S + tid]; - __syncthreads(); - const float g = __expf(gate[(size_t) t * h_v + head]); - float kv = 0.0f; -#pragma unroll - for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); - red[rg][col_local] = kv; - __syncthreads(); - const float kv_col = red[0][col_local] + red[1][col_local] + red[2][col_local] + red[3][col_local]; - const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head]; -#pragma unroll - for (int r = 0; r < RPG; ++r) s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); - } -#pragma unroll - for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r]; -} - -__global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __restrict__ state, - const float* __restrict__ hbuf, int C, - const float* __restrict__ gate, - const float* __restrict__ beta, - const float* __restrict__ z, - const float* __restrict__ gamma, float eps, - float* __restrict__ y, int h_k, int h_v, int T, - const int32_t* __restrict__ n_keep, int t_out_begin, - int silu) { - __shared__ float sk[S], sq[S]; - __shared__ float red[RG][S]; - __shared__ float wsum[S * RG / 32]; - const int head = blockIdx.x; - const int col = threadIdx.x; - const int rg = threadIdx.y; - const int tid = rg * S + col; - const int qh = head % h_k; - const int qk = S * h_k; // q at [0, qk), k at [qk, 2qk), v at [2qk, ...) - const int value_dim = S * h_v; - const int n = n_keep ? *n_keep : T; - float s[RPG]; - float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col; - const size_t row_stride = (size_t) h_v * S; -#pragma unroll - for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride]; - for (int t = 0; t < n; ++t) { - const float* ht = hbuf + (size_t) t * C; - const bool need_out = (t >= t_out_begin); - __syncthreads(); // the previous token is done with sk/sq/red/wsum - if (tid < S) { - sk[tid] = ht[qk + qh * S + tid]; - if (need_out) sq[tid] = ht[qh * S + tid]; - } - __syncthreads(); - const float g = __expf(gate[(size_t) t * h_v + head]); - float kv = 0.0f; -#pragma unroll - for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); - red[rg][col] = kv; - __syncthreads(); - const float kv_col = red[0][col] + red[1][col] + red[2][col] + red[3][col]; - const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head]; - if (!need_out) { -#pragma unroll - for (int r = 0; r < RPG; ++r) s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); - continue; - } - float o = 0.0f; -#pragma unroll - for (int r = 0; r < RPG; ++r) { - s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); - o = fmaf(s[r], sq[rg * RPG + r], o); - } - __syncthreads(); - red[rg][col] = o; - __syncthreads(); - float oc = 0.0f, sq_part = 0.0f; - if (rg == 0) { - oc = (red[0][col] + red[1][col] + red[2][col] + red[3][col]) * rsqrtf((float) S); - sq_part = oc * oc; - } - for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part += __shfl_xor_sync(0xffffffffu, sq_part, o2); - if ((tid & 31) == 0) wsum[tid >> 5] = sq_part; - __syncthreads(); - if (rg == 0) { - const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; - const float scale = rsqrtf(ss / (float) S + eps); - const float zz = z[(size_t) t * value_dim + head * S + col]; - const float act = silu ? zz / (1.0f + __expf(-zz)) : (1.0f / (1.0f + __expf(-zz))); // bitwise fused_gdn_step_norm - y[(size_t) t * value_dim + head * S + col] = oc * scale * gamma[col] * act; - } - } - if (n_keep != nullptr && n > 0) { -#pragma unroll - for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r]; - } -} - -__global__ void embedding_gather_dev_kernel(const uint8_t* __restrict__ codes, const float* __restrict__ scales, - const float* __restrict__ offsets, const int32_t* __restrict__ tokens, - int64_t n, int code_bits, int code_bias, int group_elems, - unsigned long long row_codes, unsigned long long row_groups, - float* __restrict__ out) { - const int t = blockIdx.y; - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n) return; - const unsigned long long token = (unsigned long long) tokens[t]; - const uint8_t* c = codes + token * row_codes; - const float* sc = scales + token * row_groups; - const float* of = offsets ? offsets + token * row_groups : nullptr; - const int per_byte = 8 / code_bits; - const unsigned mask = (1u << code_bits) - 1u; - const int code = (c[i / per_byte] >> ((i % per_byte) * code_bits)) & mask; - const int64_t group = i / group_elems; - const float product = __fmul_rn((float) (code + code_bias), sc[group]); - out[(size_t) t * n + i] = __fadd_rn(product, of ? of[group] : 0.0f); -} - -__global__ void broadcast_streams_kernel(const float* __restrict__ x, float* __restrict__ R, int64_t n, int hc) { - const int t = blockIdx.y; - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n * hc) return; - R[(size_t) t * n * hc + i] = x[(size_t) t * n + i % n]; -} - -__global__ void copy_indexed_kernel(float* __restrict__ dst, const float* __restrict__ src, int64_t stride, - const int32_t* __restrict__ index, int64_t n) { - const int idx = *index; - if (idx < 0) return; - for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) - dst[i] = src[(size_t) idx * stride + i]; -} - -__global__ void fetch_blobs_kernel(const unsigned long long* __restrict__ src, const int32_t* __restrict__ n, - uint4* __restrict__ dst, long long per) { - const long long total = (long long) *n * per; - for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < total; - i += (long long) gridDim.x * blockDim.x) { - const long long k = i / per, off = i - k * per; - dst[i] = ((const uint4*) src[k])[off]; - } -} - -__global__ void rebase_ptrs_kernel(unsigned long long* ptr, const int32_t* n, unsigned long long base, long long bytes) { - const int k = threadIdx.x; - if (k < *n) ptr[k] = base + (unsigned long long) k * (unsigned long long) bytes; -} - -__global__ void add_streams_broadcast_kernel(const float* __restrict__ h, const float* __restrict__ e, - float* __restrict__ R, int64_t n, int hc) { - const int t = blockIdx.y; - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n * hc) return; - R[(size_t) t * n * hc + i] = h[(size_t) t * n * hc + i] + e[(size_t) t * n + i % n]; -} - -__global__ void ident_hits_kernel(const int32_t* __restrict__ ids, int n, int32_t* __restrict__ slot, - int32_t* __restrict__ dst, int32_t* __restrict__ count) { - const int i = threadIdx.x; - if (i < n) { slot[i] = ids[i]; dst[i] = i; } - if (i == 0) *count = n; -} - -// E = the widest element the row size divides into (16, 4 or 1 bytes): a Q6_K head row of 2560 values is 2100 bytes -template -__global__ void gather_rows_kernel(const E* __restrict__ src, long long row_e, const int32_t* __restrict__ ids, - long long n, E* __restrict__ dst) { - const long long total = n * row_e; - for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < total; i += (long long) gridDim.x * blockDim.x) { - const long long r = i / row_e, o = i - r * row_e; - dst[i] = src[(long long) ids[r] * row_e + o]; - } -} - -__global__ void map_ids_kernel(int32_t* ids, const int32_t* __restrict__ table, int n) { - const int i = threadIdx.x; - if (i < n) ids[i] = table[ids[i]]; -} - -__global__ void row_top_prob_kernel(const float* __restrict__ logits, int n_vocab, const int32_t* __restrict__ ids, - float* __restrict__ probs) { - __shared__ float part[32]; - const int t = blockIdx.x; - const float* l = logits + (size_t) t * n_vocab; - const float m = l[ids[t]]; - float s = 0.0f; - for (int i = threadIdx.x; i < n_vocab; i += blockDim.x) s += __expf(l[i] - m); - for (int o = 16; o > 0; o >>= 1) s += __shfl_xor_sync(0xffffffffu, s, o); - if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = s; - __syncthreads(); - if (threadIdx.x == 0) { - float tot = 0.0f; - for (int w = 0; w < (int) (blockDim.x >> 5); ++w) tot += part[w]; - probs[t] = 1.0f / tot; - } -} - -__global__ void mtp_select_kernel(const float* __restrict__ R_src, int64_t stride, const int32_t* __restrict__ ids, - const int32_t* __restrict__ row_dev, float* __restrict__ R_dst, - int32_t* __restrict__ tok_dst, int32_t* out, int j, const float* probs, float* out_p) { - const int row = *row_dev; - for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < stride; i += (int64_t) gridDim.x * blockDim.x) - R_dst[i] = R_src[(size_t) row * stride + i]; - __syncthreads(); - if (blockIdx.x == 0 && threadIdx.x == 0) { - const int32_t tok = ids[row]; - *tok_dst = tok; - if (probs != nullptr && out_p != nullptr) ((volatile float*) out_p)[j] = probs[row]; - __threadfence_system(); - if (out != nullptr) ((volatile int32_t*) out)[j] = tok; - } -} - -__global__ void dense_steps_kernel(const int32_t* __restrict__ cells, int n, int32_t* __restrict__ steps) { - const int i = threadIdx.x; - if (i >= n) return; - const int c = cells[i]; - steps[i * 4 + 0] = c; - steps[i * 4 + 1] = c + 1; - steps[i * 4 + 2] = (c + 1) / 4; - steps[i * 4 + 3] = c + 1; -} - -} // namespace - -void fetch_blobs(const unsigned long long* src, const int32_t* n, uint8_t* dst, int64_t blob_bytes, int cap, void* stream) { - if (cap <= 0) return; - if (blob_bytes % 16 != 0) { std::fprintf(stderr, "fetch_blobs: blob size must be a multiple of 16\n"); std::exit(1); } - fetch_blobs_kernel<<<48 * 8, 256, 0, (cudaStream_t) stream>>>(src, n, (uint4*) dst, (long long) (blob_bytes / 16)); - check("fetch_blobs"); -} - -void rebase_ptrs(unsigned long long* ptr, const int32_t* n, uint8_t* base, int64_t blob_bytes, void* stream) { - rebase_ptrs_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(ptr, n, (unsigned long long) base, (long long) blob_bytes); - check("rebase_ptrs"); -} - -void add_streams_broadcast(const float* h, const float* e, float* R, int64_t n_embd, int hc, int n_tok, void* stream) { - add_streams_broadcast_kernel<<>>(h, e, R, n_embd, hc); - check("add_streams_broadcast"); -} - -void ident_hits(const int32_t* ids, int n, int32_t* slot, int32_t* dst, int32_t* count, void* stream) { - if (n < 1 || n > 1024) { std::fprintf(stderr, "ident_hits: n out of range\n"); std::exit(1); } - ident_hits_kernel<<<1, 1024, 0, (cudaStream_t) stream>>>(ids, n, slot, dst, count); - check("ident_hits"); -} - -void mtp_select(const float* R_src, int64_t R_stride, const int32_t* ids, const int32_t* row_dev, float* R_dst, - int32_t* tok_dst, int32_t* out, int j, void* stream, const float* probs, float* out_p) { - mtp_select_kernel<<<1, 256, 0, (cudaStream_t) stream>>>(R_src, R_stride, ids, row_dev, R_dst, tok_dst, out, j, - probs, out_p); - check("mtp_select"); -} - -void gather_rows(const uint8_t* src, int64_t row_bytes, const int32_t* ids, int64_t n, uint8_t* dst, void* stream) { - cudaStream_t s = (cudaStream_t) stream; - if (row_bytes % 16 == 0) - gather_rows_kernel<<<48 * 8, 256, 0, s>>>((const uint4*) src, row_bytes / 16, ids, n, (uint4*) dst); - else if (row_bytes % 4 == 0) - gather_rows_kernel<<<48 * 8, 256, 0, s>>>((const uint32_t*) src, row_bytes / 4, ids, n, (uint32_t*) dst); - else - gather_rows_kernel<<<48 * 8, 256, 0, s>>>(src, row_bytes, ids, n, dst); - check("gather_rows"); -} - -void map_ids(int32_t* ids, const int32_t* table, int n, void* stream) { - map_ids_kernel<<<1, 64, 0, (cudaStream_t) stream>>>(ids, table, n); - check("map_ids"); -} - -void row_top_prob(const float* logits, int n_rows, int n_vocab, const int32_t* ids, float* probs, void* stream) { - row_top_prob_kernel<<>>(logits, n_vocab, ids, probs); - check("row_top_prob"); -} - -namespace { -__global__ void window_ids_kernel(int32_t* steps, int window, int32_t* ids, long long stride) { - const int q = blockIdx.y; - int32_t* st = steps + q * 4; - const int n_kv = st[1]; - const int start = n_kv > window ? n_kv - window : 0; - const int width = n_kv - start; - for (int j = blockIdx.x * blockDim.x + threadIdx.x; j < width; j += gridDim.x * blockDim.x) - ids[q * stride + j] = start + j; - __syncthreads(); - if (blockIdx.x == 0 && threadIdx.x == 0) st[3] = width; -} -} // namespace - -void window_ids(int32_t* steps, int n, int window, int32_t* ids, int64_t ids_stride, void* stream) { - window_ids_kernel<<>>(steps, window, ids, (long long) ids_stride); - check("window_ids"); -} - -void dense_steps(const int32_t* cells, int n, int32_t* steps, void* stream) { - dense_steps_kernel<<<1, 64, 0, (cudaStream_t) stream>>>(cells, n, steps); - check("dense_steps"); -} - -void gdn_conv_l2_multi(const float* history, const float* qkv, const float* conv_w, float* h, int channels, - int qk_heads, float eps, int n_tok, void* stream, int t_begin) { - if (!history || !qkv || !conv_w || !h || channels % S != 0 || n_tok < 1 || n_tok > kVerifyMaxT) { - std::fprintf(stderr, "gdn_conv_l2_multi: invalid arguments\n"); - std::exit(1); - } - gdn_conv_l2_multi_kernel<<>>( - history, qkv, conv_w, h, channels, qk_heads, eps, t_begin); - check("gdn_conv_l2_multi"); -} - -void gdn_conv_commit(float* history, const float* qkv, int channels, const int32_t* n_keep, void* stream) { - gdn_conv_commit_kernel<<<(unsigned) ((channels + 255) / 256), 256, 0, (cudaStream_t) stream>>>(history, qkv, - channels, n_keep); - check("gdn_conv_commit"); -} - -void gdn_ab_multi(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, int n_tok, void* stream) { - if (n_embd % 8 != 0 || n_tok < 1 || n_tok > kVerifyMaxT) { - std::fprintf(stderr, "gdn_ab_multi: invalid arguments\n"); - std::exit(1); - } - const unsigned blocks = (unsigned) ((2 * h_v + 1) / 2); - if (n_tok <= 4) { - gdn_ab_multi_kernel<4><<>>( - x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok); - } else { - gdn_ab_multi_kernel<<>>( - x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok); - } - check("gdn_ab_multi"); -} - -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) { - if (!state || !h || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v % h_k || n_tok < 1 || - n_tok > kVerifyMaxT) { - std::fprintf(stderr, "gdn_step_norm_multi: invalid arguments\n"); - std::exit(1); - } - static const bool commit_split = [] { - const char* e = std::getenv("STRATA_GDN_COMMIT_SPLIT"); - return !e || e[0] != '0'; - }(); - if (commit_split && n_keep != nullptr && t_out_begin >= n_tok) { - gdn_step_commit_kernel<<>>( - state, h, conv_channels, gate, beta, h_k, h_v, n_keep); - } else { - gdn_step_norm_multi_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>( - state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, n_keep, t_out_begin, - act == GdnGate::Silu ? 1 : 0); - } - check("gdn_step_norm_multi"); -} - -namespace { -__global__ void wait_flag_ge_kernel(const volatile uint32_t* flag, uint32_t value) { - while (*flag < value) strata_spin_pause(); - __threadfence_system(); -} -} // namespace - -namespace { -// one thread per window entry: up to kVerifyMaxT tokens x 10 routed experts (80), so 128 (#646 had 64: a window of -// 7+ tokens lost its last entries) -constexpr int kResidentPlanMax = 128; -static_assert(kVerifyMaxT * 10 <= kResidentPlanMax, "resident_plan: one thread per entry"); -__global__ void __launch_bounds__(kResidentPlanMax) resident_plan_kernel(const int32_t* __restrict__ ids, int n, int k, const int32_t* __restrict__ res, - int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off, - long long blob, int32_t* __restrict__ pl, long long capx, uint32_t* skip, - uint32_t ring) { - __shared__ int32_t s_ids[kResidentPlanMax]; - __shared__ unsigned long long s_ptr[kResidentPlanMax]; - __shared__ int32_t s_first[kResidentPlanMax]; - __shared__ int32_t s_cnt[kResidentPlanMax]; - __shared__ int32_t s_gstart[kResidentPlanMax]; - __shared__ int s_bad; - const int tid = threadIdx.x; - if (tid == 0) s_bad = 0; - __syncthreads(); - - int32_t eid = -1; - if (tid < n) { - eid = ids[tid]; - s_ids[tid] = eid; - const int32_t slot = (eid >= 0 && eid < n_expert) ? res[eid] : -1; - if (slot < 0) { - atomicOr(&s_bad, 1); - } else { - s_ptr[tid] = (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob)); - } - } - __syncthreads(); - if (s_bad) { - if (tid == 0 && skip != nullptr) *skip = 0; - return; - } - - int first_j = tid; - int rank_in_group = 0; - int count_same = 0; - if (tid < n) { - for (int j = 0; j < n; ++j) { - if (s_ids[j] == eid) { - if (j < first_j) first_j = j; - if (j < tid) ++rank_in_group; - ++count_same; - } - } - const bool is_first = (first_j == tid); - s_first[tid] = is_first ? 1 : 0; - s_cnt[tid] = is_first ? count_same : 0; - } - __syncthreads(); - - int32_t* counts = pl; - int32_t* start = pl + 4; - int32_t* dst = start + capx + 1; - int32_t* tok = dst + capx; - const long long ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll; - unsigned long long* ptr = (unsigned long long*) (pl + ptr_off); - int32_t* start2 = pl + ptr_off + 4 * capx; - - if (tid < n && first_j == tid) { - int grp_idx = 0; - int ent_start = 0; - for (int j = 0; j < tid; ++j) { - grp_idx += s_first[j]; - ent_start += s_cnt[j]; - } - ptr[grp_idx] = s_ptr[tid]; - start[grp_idx] = ent_start; - s_gstart[tid] = ent_start; - } - __syncthreads(); - - if (tid < n) { - const int out_idx = s_gstart[first_j] + rank_in_group; - dst[out_idx] = tid; - tok[out_idx] = tid / k; - } - if (tid == 0) { - int groups = 0; - for (int j = 0; j < n; ++j) groups += s_first[j]; - start[groups] = n; - start2[0] = n; - counts[0] = groups; - counts[1] = n; - counts[2] = 0; - if (skip != nullptr) { - __threadfence(); - *skip = ring; - } - } -} -__global__ void wait_flag_ge_or_kernel(const volatile uint32_t* flag, uint32_t value, const volatile uint32_t* skip) { - if (*skip == value) return; - while (*flag < value) strata_spin_pause(); - __threadfence_system(); -} -__global__ void copy_i32_unless_kernel(int32_t* __restrict__ dst, const volatile int32_t* src, int n, - const uint32_t* skip, uint32_t value) { - if (*skip == value) return; - for (int i = threadIdx.x; i < n; i += blockDim.x) dst[i] = src[i]; -} -__global__ void copy_or_zero_kernel(float4* __restrict__ dst, const volatile float4* src, long long n4, - const uint32_t* skip, uint32_t value) { - const bool zero = *skip == value; - for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < n4; i += (long long) gridDim.x * blockDim.x) - dst[i] = zero ? make_float4(0.f, 0.f, 0.f, 0.f) : const_cast(src)[i]; -} -} // namespace - -void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_layer, int n_expert, - const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan, - long long capx, uint32_t* skip, uint32_t ring, void* stream) { - resident_plan_kernel<<<1, kResidentPlanMax, 0, (cudaStream_t) stream>>>(ids, n_entries, k, res_layer, n_expert, cache_base, slot_off, - blob, plan, capx, skip, ring); - check("resident_plan"); -} -void wait_flag_ge_or(const uint32_t* flag, uint32_t value, const uint32_t* skip, void* stream) { - wait_flag_ge_or_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(flag, value, skip); - check("wait_flag_ge_or"); -} -void copy_i32_from_mapped_unless(int32_t* dst, const int32_t* src, long long n, const uint32_t* skip, uint32_t value, - void* stream) { - if (n <= 0) return; - copy_i32_unless_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(dst, (const volatile int32_t*) src, (int) n, skip, value); - check("copy_i32_from_mapped_unless"); -} -void copy_or_zero_from_mapped(float* dst, const float* src, long long n, const uint32_t* skip, uint32_t value, - void* stream) { - if (n <= 0) return; - const long long n4 = n / 4; - const int blocks = (int) ((n4 + 255) / 256 < 64 ? (n4 + 255) / 256 : 64); - copy_or_zero_kernel<<>>((float4*) dst, (const volatile float4*) src, n4, skip, - value); - check("copy_or_zero_from_mapped"); -} - -void wait_flag_ge(const uint32_t* flag, uint32_t value, void* stream) { - wait_flag_ge_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(flag, value); - check("wait_flag_ge"); -} - -void embedding_gather_dev(const uint8_t* codes, const float* scales, const float* offsets, const int32_t* tokens, - int n_tok, int64_t n, int code_bits, int code_bias, int group_elems, uint64_t row_codes, - uint64_t row_groups, float* out, void* stream) { - embedding_gather_dev_kernel<<>>(codes, scales, offsets, tokens, n, code_bits, code_bias, - group_elems, row_codes, row_groups, out); - check("embedding_gather_dev"); -} - -void broadcast_streams(const float* x, float* R, int64_t n_embd, int hc, int n_tok, void* stream) { - broadcast_streams_kernel<<>>(x, R, n_embd, hc); - check("broadcast_streams"); -} - -void copy_indexed(float* dst, const float* src, int64_t stride, const int32_t* index, int64_t n, void* stream) { - const unsigned blocks = (unsigned) ((n + 255) / 256 < 64 ? (n + 255) / 256 : 64); - copy_indexed_kernel<<>>(dst, src, stride, index, n); - check("copy_indexed"); -} - -// a GPU timestamp (ns, %globaltimer) into buf[i] - the verify window's stage profiler -namespace { __global__ void gpu_stamp_kernel(unsigned long long* buf, int i) { - unsigned long long t; -#if defined(STRATA_HIP_GFX906) - t = wall_clock64() * 40ull; // gfx906: the wall clock runs at 25 MHz (hipDeviceAttributeWallClockRate) -> ns -#elif defined(__HIPCC__) - t = wall_clock64() * 10ull; // gfx10.3 / gfx11 / gfx12: a constant 100 MHz counter, in ns -#else - asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); -#endif - buf[i] = t; -} } -void gpu_stamp(unsigned long long* buf, int i, void* stream) { - gpu_stamp_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(buf, i); -} - -} // namespace strata::kernels diff --git a/src/kernels/cvec_parity.cpp b/src/kernels/cvec_parity.cpp deleted file mode 100644 index 6176c63..0000000 --- a/src/kernels/cvec_parity.cpp +++ /dev/null @@ -1,223 +0,0 @@ -// src/kernels/cvec_parity.cpp - the control vector kernel (strata/kernels/cvec.hpp) against a host reference. -// 1. project: h - s (h.v) v per stream and token, against double precision; the steered component is gone. -// 2. add: h + d. -// 3. switched off: R unchanged without a pending write; with one, R is BITWISE the write the fused read folds -// (fused_gr_read with apply), which is what keeps a loaded-but-off vector identical to the stock engine. -// 4. a layer without a direction is untouched. - -#include "strata/kernels/cvec.hpp" -#include "strata/kernels/fused_gr.hpp" - -#include - -#include -#include -#include -#include -#include -#include - -namespace k = strata::kernels; - -namespace { - -int g_fail = 0; - -void ck(cudaError_t e, const char* w) { - if (e != cudaSuccess) { - std::fprintf(stderr, "CUDA error in %s: %s\n", w, cudaGetErrorString(e)); - std::exit(2); - } -} - -template -T* dalloc(size_t n) { - T* p = nullptr; - ck(cudaMalloc(&p, n * sizeof(T)), "malloc"); - return p; -} - -template -void up(T* d, const std::vector& h) { ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "up"); } -template -std::vector down(const T* d, size_t n) { - std::vector h(n); - ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "down"); - return h; -} - -void check(bool ok, const char* what) { - std::printf(" %-66s %s\n", what, ok ? "ok" : "FAIL"); - if (!ok) ++g_fail; -} - -} // namespace - -int main() { - constexpr int64_t L = 48, N = 2560, HC = 4, LR = 320, T = 5, D = HC * N; - constexpr int64_t kLayer = 7, kOff = 3; // steered / not steered - std::mt19937 rng(1234); - std::normal_distribution nd(0.0f, 1.0f); - - // a unit direction at kLayer with a norm-2 scaled one's s = 2; nothing at kOff - std::vector dir((size_t) (L * N), 0.0f), s((size_t) L, 0.0f); - { - double nrm = 0.0; - std::vector v((size_t) N); - for (auto& x : v) { x = nd(rng); nrm += (double) x * x; } - nrm = std::sqrt(nrm); - for (int64_t j = 0; j < N; ++j) dir[(size_t) (kLayer * N + j)] = (float) (v[(size_t) j] / nrm); - s[(size_t) kLayer] = 2.0f; - } - std::string err; - if (!k::cvec_upload(dir, s, /*project*/ 0, 4, 44, N, HC, err)) { std::fprintf(stderr, "%s\n", err.c_str()); return 2; } - check(k::cvec().covers(kLayer) && !k::cvec().covers(kOff) && !k::cvec().covers(45), "covers(): steered layers only"); - - std::vector R((size_t) (T * D)), bo((size_t) (T * N)), inj((size_t) (T * HC)); - for (auto& x : R) x = nd(rng) * 3.0f; - for (auto& x : bo) x = nd(rng); - for (auto& x : inj) x = nd(rng); - float* dR = dalloc(R.size()); - float* dbo = dalloc(bo.size()); - float* dinj = dalloc(inj.size()); - up(dbo, bo); - up(dinj, inj); - - // ---- 1. project, no pending write - std::printf("project\n"); - up(dR, R); - k::cvec_apply(dR, kLayer, T, D, nullptr, 0, nullptr, 0, false, nullptr); - ck(cudaDeviceSynchronize(), "project"); - { - const auto got = down(dR, R.size()); - double worst = 0.0, worst_dot = 0.0; - for (int64_t t = 0; t < T; ++t) - for (int64_t c = 0; c < HC; ++c) { - const float* h = R.data() + t * D + c * N; - const float* v = dir.data() + kLayer * N; - double dot = 0.0; - for (int64_t j = 0; j < N; ++j) dot += (double) h[j] * v[j]; - double after = 0.0; - for (int64_t j = 0; j < N; ++j) { - const double want = h[j] - 2.0 * dot * v[j]; - const double g = got[(size_t) (t * D + c * N + j)]; - worst = std::fmax(worst, std::fabs(g - want)); - after += g * v[j]; - } - // s = 2 reflects the component: h.v -> -h.v - worst_dot = std::fmax(worst_dot, std::fabs(after + dot)); - } - std::printf(" max |err| %.3g, max |h'.v + h.v| %.3g\n", worst, worst_dot); - check(worst < 1e-4, "project matches h - s (h.v) v (s = 2)"); - check(worst_dot < 1e-3, "the component along v is reflected (s = 2)"); - } - // s = 1 removes it - s[(size_t) kLayer] = 1.0f; - if (!k::cvec_upload(dir, s, 0, 4, 44, N, HC, err)) return 2; - up(dR, R); - k::cvec_apply(dR, kLayer, T, D, nullptr, 0, nullptr, 0, false, nullptr); - ck(cudaDeviceSynchronize(), "project s=1"); - { - const auto got = down(dR, R.size()); - double worst = 0.0; - for (int64_t t = 0; t < T; ++t) - for (int64_t c = 0; c < HC; ++c) { - double after = 0.0; - for (int64_t j = 0; j < N; ++j) after += (double) got[(size_t) (t * D + c * N + j)] * dir[(size_t) (kLayer * N + j)]; - worst = std::fmax(worst, std::fabs(after)); - } - std::printf(" max |h'.v| %.3g\n", worst); - check(worst < 1e-3, "s = 1 projects the direction out"); - } - - // ---- 4. a layer without a direction - up(dR, R); - k::cvec_apply(dR, kOff, T, D, nullptr, 0, nullptr, 0, false, nullptr); - ck(cudaDeviceSynchronize(), "off layer"); - check(std::memcmp(down(dR, R.size()).data(), R.data(), R.size() * 4) == 0, "a layer without a direction is untouched"); - - // ---- 3. switched off - std::printf("switched off\n"); - k::cvec_set_enabled(false); - check(!k::cvec_enabled(), "cvec_enabled() follows the switch"); - up(dR, R); - k::cvec_apply(dR, kLayer, T, D, nullptr, 0, nullptr, 0, false, nullptr); - ck(cudaDeviceSynchronize(), "off"); - check(std::memcmp(down(dR, R.size()).data(), R.data(), R.size() * 4) == 0, "off, no pending write: R unchanged"); - { - // the fused read's folded write, one token at a time, against the kernel's write-only pass - std::vector wd((size_t) (LR * D)), wu((size_t) (D * LR)), wi((size_t) (HC * D)); - std::vector wn((size_t) D); - auto bf = [&](float x) { uint32_t u; std::memcpy(&u, &x, 4); return (uint16_t) (u >> 16); }; - for (auto& x : wd) x = bf(nd(rng) * 0.02f); - for (auto& x : wu) x = bf(nd(rng) * 0.02f); - for (auto& x : wi) x = bf(nd(rng) * 0.02f); - for (auto& x : wn) x = 1.0f + 0.1f * nd(rng); - uint16_t* dwd = dalloc(wd.size()); - uint16_t* dwu = dalloc(wu.size()); - uint16_t* dwi = dalloc(wi.size()); - float* dwn = dalloc(wn.size()); - up(dwd, wd); up(dwu, wu); up(dwi, wi); up(dwn, wn); - float* lo = dalloc(LR); - float* rs = dalloc(HC); - float* inj_out = dalloc(HC); - float* mixed = dalloc(N); - float* dF = dalloc(R.size()); - up(dF, R); - for (int64_t t = 0; t < T; ++t) { - k::FusedGrArgs a; - a.R = dF + t * D; a.R_out = dF + t * D; a.apply = true; - a.bo_prev = dbo + t * N; a.inj_prev = dinj + t * HC; - a.w_norm = dwn; a.w_down = dwd; a.w_up = dwu; a.w_inject = dwi; - a.lo = lo; a.rs = rs; a.inject_out = inj_out; a.mixed = mixed; - k::fused_gr_read(a, nullptr); - } - up(dR, R); - k::cvec_apply(dR, kLayer, T, D, dbo, N, dinj, HC, true, nullptr); - ck(cudaDeviceSynchronize(), "write only"); - const auto fused = down(dF, R.size()), mine = down(dR, R.size()); - check(std::memcmp(fused.data(), mine.data(), R.size() * 4) == 0, - "off, pending write: bitwise the fused read's folded write"); - k::cvec_set_enabled(true); - // on, with the write: the write, then the projection (reference from the fused result) - up(dR, R); - k::cvec_apply(dR, kLayer, T, D, dbo, N, dinj, HC, true, nullptr); - ck(cudaDeviceSynchronize(), "write+project"); - const auto both = down(dR, R.size()); - double worst = 0.0; - for (int64_t t = 0; t < T; ++t) - for (int64_t c = 0; c < HC; ++c) { - const float* h = fused.data() + t * D + c * N; - const float* v = dir.data() + kLayer * N; - double dot = 0.0; - for (int64_t j = 0; j < N; ++j) dot += (double) h[j] * v[j]; - for (int64_t j = 0; j < N; ++j) - worst = std::fmax(worst, std::fabs(both[(size_t) (t * D + c * N + j)] - (h[j] - dot * v[j]))); - } - std::printf(" write + project: max |err| %.3g\n", worst); - check(worst < 1e-4, "on, pending write: the write, then the projection"); - } - - // ---- 2. add - std::printf("add\n"); - for (int64_t j = 0; j < N; ++j) dir[(size_t) (kLayer * N + j)] *= 0.1f; // d = 0.1 v, s = 1 - s[(size_t) kLayer] = 1.0f; - if (!k::cvec_upload(dir, s, /*add*/ 1, 4, 44, N, HC, err)) return 2; - up(dR, R); - k::cvec_apply(dR, kLayer, T, D, nullptr, 0, nullptr, 0, false, nullptr); - ck(cudaDeviceSynchronize(), "add"); - { - const auto got = down(dR, R.size()); - bool same = true; - for (int64_t t = 0; t < T; ++t) - for (int64_t c = 0; c < HC; ++c) - for (int64_t j = 0; j < N; ++j) { - const size_t i = (size_t) (t * D + c * N + j); - same = same && got[i] == R[i] + dir[(size_t) (kLayer * N + j)]; - } - check(same, "add is h + d in every stream (bitwise)"); - } - - std::printf(g_fail ? "cvec_parity: %d FAILED\n" : "cvec_parity: all passed\n", g_fail); - return g_fail ? 1 : 0; -} diff --git a/src/kernels/decode_cluster_parity.cpp b/src/kernels/decode_cluster_parity.cpp deleted file mode 100644 index 665fe6f..0000000 --- a/src/kernels/decode_cluster_parity.cpp +++ /dev/null @@ -1,424 +0,0 @@ -// src/kernels/decode_cluster_parity.cpp - S19: the decode kernels on thread-block clusters (sm_90+) against the ones -// they replace, bit for bit (GPU, synthetic, no model). -// -// QSA top-k : qsa_block_topk_cluster vs qsa_block_topk's one-CTA dispatch (the register kernel up to 33,792 blocks, -// block_topk_kernel above) and vs qsa_block_topk_ref - every id of every row of the `cap`-wide buffer, -// including the entries past the width that neither may write. -// argmax : sample_greedy_cluster vs sample_tokens' one-block greedy kernel. -// -// Inputs: random scores like a real indexer's, and adversarial ones - all equal, a few distinct values (ties at the -// threshold across the CTAs of a cluster), NaN, +-inf, -0.0 against +0.0, denormals, monotone rows, all NaN; contexts -// from below the selection width (the identity) to 262,144 cells, every tail weight (n_kv mod 4), 1-16 queries; and -// one CUDA graph that captures both cluster launches, replayed with new inputs. -// -// decode_cluster_parity --selftest parity (exit 0 = identical everywhere); skipped (exit 0) below sm_90 -// decode_cluster_parity --bench per-call times, old vs new, at 32K / 128K / 262K -// -// The old paths are reached through the public dispatchers with STRATA_QSA_CLUSTER=0 / STRATA_ARGMAX_MULTI=0, set -// here before their first call (they read the variables once). -#include "strata/kernels/qsa.hpp" -#include "strata/kernels/qsa_select.hpp" -#include "strata/kernels/sampler.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace k = strata::kernels; - -namespace { - -void ck(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(2); - } -} - -void set_env(const char* name, const char* value) { -#if defined(_WIN32) - _putenv_s(name, value); -#else - setenv(name, value, 1); -#endif -} - -template struct Dev { - T* p = nullptr; - size_t n = 0; - explicit Dev(size_t count) : n(count) { ck(cudaMalloc(&p, count * sizeof(T) + 64), "cudaMalloc"); } - ~Dev() { cudaFree(p); } - void put(const std::vector& h) { - ck(cudaMemcpy(p, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "up"); - // #548 #536: a pageable cudaMemcpy can return before its DMA lands, and the graph replays and the timing - // cases run on a cudaStreamNonBlocking stream that does not wait for the legacy stream - so wait here - ck(cudaDeviceSynchronize(), "up landed"); - } - std::vector get() const { - std::vector h(n); - ck(cudaMemcpy(h.data(), p, n * sizeof(T), cudaMemcpyDeviceToHost), "down"); - return h; - } -}; - -const float kNaN = std::numeric_limits::quiet_NaN(), kInf = std::numeric_limits::infinity(); - -// ---- QSA top-k fixtures -enum Pattern { kRandom, kAllEqual, kFewValues, kNaNs, kInfs, kSignedZero, kDenormal, kAscending, kDescending, kAllNaN, - kQuantized, kPatterns }; -const char* pattern_name(int p) { - static const char* n[] = {"random", "all-equal", "few-values", "nan", "inf", "signed-zero", "denormal", "ascending", - "descending", "all-nan", "quantized"}; - return n[p]; -} - -// one query's row of block scores (blocks 0..n_bid); the tail block gets the +1e9 the score kernel gives it -void fill_row(float* row, int64_t n_kv, int64_t n_bid, int pattern, std::mt19937& rng) { - std::normal_distribution nd(0.f, 1.f); - std::uniform_int_distribution pick(0, 99); - for (int64_t b = 0; b <= n_bid; ++b) { - float v = 0.f; - const float g = nd(rng); - switch (pattern) { - case kRandom: v = std::fmax(0.f, g) * 3.f + std::fmax(0.f, nd(rng)); break; // relu sums: exact zeros too - case kAllEqual: v = 1.f; break; - case kFewValues: v = (float) (pick(rng) % 4) * 0.5f; break; - case kNaNs: v = pick(rng) < 15 ? kNaN : std::fabs(g); break; - case kInfs: { - const int r = pick(rng); - v = r < 5 ? kInf : r < 15 ? -kInf : r < 30 ? -std::fabs(g) : g; - break; - } - case kSignedZero: v = pick(rng) < 50 ? -0.0f : (pick(rng) < 50 ? 0.0f : -std::fabs(g) * 1e-3f); break; - case kDenormal: v = (float) (pick(rng) % 7) * 1e-41f; break; - case kAscending: v = (float) b; break; - case kDescending: v = (float) (n_bid - b); break; - case kAllNaN: v = kNaN; break; - case kQuantized: v = std::round(std::fabs(g) * 8.f) / 8.f; break; - } - row[b] = v; - } - if (n_kv % 4 != 0 && pattern != kAllNaN && pattern != kAllEqual) row[n_bid] += 1e9f; -} - -struct TopkCase { - int64_t ctx; // the last query's n_kv - int64_t capacity; // --max-context: max_blocks = capacity / 4 + 2 (the engine's rule) - int nq; - int pattern; -}; - -int run_topk_case(const TopkCase& c, std::mt19937& rng, bool verbose) { - const k::QsaShapes s = k::qsa_real_shapes(); - const int64_t max_blocks = c.capacity / 4 + 2, cap = k::qsa_selection_width(k::kTopkMaxCells, s); - std::vector sc((size_t) (c.nq * max_blocks), 0.f); - std::vector steps((size_t) c.nq * k::kStepCount); - for (int i = 0; i < c.nq; ++i) { - const int64_t n_kv = c.ctx - (c.nq - 1 - i); // the window's queries, one cell apart, the last at ctx - int32_t* st = steps.data() + (size_t) i * k::kStepCount; - st[k::kStepPos] = (int32_t) (n_kv - 1); - st[k::kStepNKv] = (int32_t) n_kv; - st[k::kStepNBid] = (int32_t) (n_kv / s.idx_block); - st[k::kStepWidth] = (int32_t) k::qsa_selection_width(n_kv, s); - fill_row(sc.data() + (size_t) i * max_blocks, n_kv, n_kv / s.idx_block, c.pattern, rng); - } - Dev d_sc(sc.size()); - const size_t n_ids = (size_t) (c.nq * cap); - Dev d_st(steps.size()), d_new(n_ids), d_old(n_ids), d_ref(n_ids); - d_sc.put(sc); - d_st.put(steps); - ck(cudaMemset(d_new.p, 0xA5, d_new.n * 4), "memset"); - ck(cudaMemset(d_old.p, 0xA5, d_old.n * 4), "memset"); - ck(cudaMemset(d_ref.p, 0xA5, d_ref.n * 4), "memset"); - if (!k::qsa_block_topk_cluster(d_sc.p, d_st.p, c.nq, max_blocks, cap, s, d_new.p, nullptr)) { - std::printf("FAIL topk ctx %lld cap %lld nq %d: the cluster kernel did not run\n", (long long) c.ctx, - (long long) c.capacity, c.nq); - return 1; - } - k::qsa_block_topk(d_sc.p, d_st.p, c.nq, max_blocks, cap, s, d_old.p, nullptr); - k::qsa_block_topk_ref(d_sc.p, d_st.p, c.nq, max_blocks, cap, s, d_ref.p, nullptr); - ck(cudaDeviceSynchronize(), "topk sync"); - const std::vector a = d_new.get(), b = d_old.get(), r = d_ref.get(); - int64_t diff_old = 0, diff_ref = 0, first = -1; - for (size_t i = 0; i < a.size(); ++i) { - if (a[i] != b[i]) { ++diff_old; if (first < 0) first = (int64_t) i; } - if (a[i] != r[i]) ++diff_ref; - } - const bool ok = diff_old == 0 && diff_ref == 0; - if (!ok || verbose) - std::printf("%s topk ctx %7lld cap %7lld nq %2d %-11s: %lld ids differ from the one-CTA dispatch, %lld from " - "the reference%s\n", ok ? "ok " : "FAIL", (long long) c.ctx, (long long) c.capacity, c.nq, - pattern_name(c.pattern), (long long) diff_old, (long long) diff_ref, - first >= 0 ? (" (first at " + std::to_string(first) + ")").c_str() : ""); - return ok ? 0 : 1; -} - -// ---- argmax fixtures -enum AmPattern { aRandom, aTies, aAllEqual, aAllNegInf, aAllNaN, aNaNMax, aPosInf, aSignedZero, aLast, aFirst, - aDenormal, aTiesAcross, aPatterns }; -const char* am_name(int p) { - static const char* n[] = {"random", "ties", "all-equal", "all--inf", "all-nan", "nan+max", "+inf", "signed-zero", - "max-last", "max-first", "denormal", "ties-across"}; - return n[p]; -} - -void fill_logits(float* l, int nv, int pattern, std::mt19937& rng) { - std::normal_distribution nd(0.f, 3.f); - std::uniform_int_distribution at(0, nv - 1); - for (int v = 0; v < nv; ++v) l[v] = nd(rng); - switch (pattern) { - case aRandom: break; - case aTies: { const int n = 1 + at(rng) % 9; for (int i = 0; i < n; ++i) l[at(rng)] = 100.f; break; } - case aAllEqual: for (int v = 0; v < nv; ++v) l[v] = 0.25f; break; - case aAllNegInf: for (int v = 0; v < nv; ++v) l[v] = -kInf; break; - case aAllNaN: for (int v = 0; v < nv; ++v) l[v] = kNaN; break; - case aNaNMax: - for (int v = 0; v < nv; ++v) if (at(rng) % 3 == 0) l[v] = kNaN; - l[at(rng)] = 50.f; - l[at(rng)] = 50.f; - break; - case aPosInf: for (int i = 0; i < 4; ++i) l[at(rng)] = kInf; break; - case aSignedZero: - for (int v = 0; v < nv; ++v) l[v] = -std::fabs(l[v]) - 1.f; - for (int i = 0; i < 6; ++i) l[at(rng)] = (i & 1) ? 0.0f : -0.0f; - break; - case aLast: l[nv - 1] = 1e30f; break; - case aFirst: l[0] = 1e30f; if (nv > 1) l[nv - 1] = 1e30f; break; - case aDenormal: for (int v = 0; v < nv; ++v) l[v] = (float) (at(rng) % 5) * 1e-42f - 1e-30f * (v & 1); break; - case aTiesAcross: // the same maximum in several CTAs' and threads' ranges (8 x 1024 stride), plus -inf, NaN - for (int v = 0; v < nv; v += 1 + at(rng) % 9000) l[v] = 7.f; - for (int v = 3; v < nv; v += 11) l[v] = kNaN; - for (int v = 5; v < nv; v += 13) l[v] = -kInf; - break; - } -} - -int run_argmax_case(int nv, int T, int pattern, std::mt19937& rng, bool verbose) { - std::vector l((size_t) nv * T); - for (int t = 0; t < T; ++t) fill_logits(l.data() + (size_t) t * nv, nv, t % 2 == 0 ? pattern : aRandom, rng); - Dev d_l(l.size()); - Dev d_new((size_t) T), d_old((size_t) T); - d_l.put(l); - ck(cudaMemset(d_new.p, 0xA5, (size_t) T * 4), "memset"); - ck(cudaMemset(d_old.p, 0x5A, (size_t) T * 4), "memset"); - k::SamplerParams sp; - sp.greedy = true; - sp.temperature = 0.f; - if (!k::sample_greedy_cluster(d_l.p, T, nv, d_new.p, nullptr)) { - std::printf("FAIL argmax nv %d T %d: the cluster kernel did not run\n", nv, T); - return 1; - } - k::sample_tokens(d_l.p, T, nv, nullptr, 0, sp, d_old.p, nullptr); - ck(cudaDeviceSynchronize(), "argmax sync"); - const std::vector a = d_new.get(), b = d_old.get(); - // and an independent host answer: the lowest index of the largest non-NaN value above -inf, else 0 - int bad = 0; - for (int t = 0; t < T; ++t) { - const float* r = l.data() + (size_t) t * nv; - int hb = -1; - for (int v = 0; v < nv; ++v) - if (r[v] > -kInf && (hb < 0 || r[v] > r[hb])) hb = v; - if (hb < 0) hb = 0; - if (a[(size_t) t] != b[(size_t) t] || a[(size_t) t] != hb) ++bad; - } - if (bad || verbose) - std::printf("%s argmax nv %6d T %d %-11s: %d rows differ (new %d, old %d)\n", bad ? "FAIL" : "ok ", nv, T, - am_name(pattern), bad, a[0], b[0]); - return bad ? 1 : 0; -} - -// both cluster launches captured in one graph, replayed over new inputs written into the same buffers -int run_graph_case(std::mt19937& rng) { - const k::QsaShapes s = k::qsa_real_shapes(); - const int nq = 5, nv = 248320; - const int64_t capacity = 131072 + 272, max_blocks = capacity / 4 + 2; - const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s); - Dev d_sc((size_t) (nq * max_blocks)), d_l((size_t) nv * nq); - Dev d_st((size_t) nq * k::kStepCount), d_new((size_t) (nq * cap)), d_old((size_t) (nq * cap)); - Dev a_new((size_t) nq), a_old((size_t) nq); - ck(cudaMemset(d_new.p, 0, d_new.n * 4), "memset"); // the entries past a row's width: written by neither - ck(cudaMemset(d_old.p, 0, d_old.n * 4), "memset"); - cudaStream_t cs; - ck(cudaStreamCreateWithFlags(&cs, cudaStreamNonBlocking), "stream"); - cudaGraph_t g = nullptr; - cudaGraphExec_t ge = nullptr; - ck(cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal), "begin capture"); - const bool l1 = k::qsa_block_topk_cluster(d_sc.p, d_st.p, nq, max_blocks, cap, s, d_new.p, cs); - const bool l2 = k::sample_greedy_cluster(d_l.p, nq, nv, a_new.p, cs); - ck(cudaStreamEndCapture(cs, &g), "end capture"); - if (!l1 && !l2) { // no cluster code here (a card or a build below sm_90): nothing to compare - if (g) cudaGraphDestroy(g); - cudaStreamDestroy(cs); - return -1; - } - if (!l1 || !l2) { std::printf("FAIL graph: one cluster kernel did not run\n"); return 1; } - ck(cudaGraphInstantiate(&ge, g, 0), "instantiate"); - int fails = 0; - for (int rep = 0; rep < 6; ++rep) { - const int64_t ctx = 100000 + rep * 4001 + rep % 4; - std::vector sc((size_t) (nq * max_blocks), 0.f), l((size_t) nv * nq); - std::vector steps((size_t) nq * k::kStepCount); - for (int i = 0; i < nq; ++i) { - const int64_t n_kv = ctx - (nq - 1 - i); - int32_t* st = steps.data() + (size_t) i * k::kStepCount; - st[k::kStepPos] = (int32_t) (n_kv - 1); - st[k::kStepNKv] = (int32_t) n_kv; - st[k::kStepNBid] = (int32_t) (n_kv / 4); - st[k::kStepWidth] = (int32_t) k::qsa_selection_width(n_kv, s); - fill_row(sc.data() + (size_t) i * max_blocks, n_kv, n_kv / 4, rep % 2 ? kFewValues : kRandom, rng); - fill_logits(l.data() + (size_t) i * nv, nv, rep % 2 ? aTiesAcross : aRandom, rng); - } - d_sc.put(sc); - d_st.put(steps); - d_l.put(l); - ck(cudaGraphLaunch(ge, cs), "graph launch"); - k::qsa_block_topk(d_sc.p, d_st.p, nq, max_blocks, cap, s, d_old.p, cs); - k::SamplerParams sp; - sp.greedy = true; - k::sample_tokens(d_l.p, nq, nv, nullptr, 0, sp, a_old.p, cs); - ck(cudaStreamSynchronize(cs), "graph sync"); - const auto x = d_new.get(), y = d_old.get(); - const auto u = a_new.get(), v = a_old.get(); - int64_t d1 = 0, d2 = 0; - for (size_t i = 0; i < x.size(); ++i) d1 += x[i] != y[i]; - for (size_t i = 0; i < u.size(); ++i) d2 += u[i] != v[i]; - if (d1 || d2) ++fails; - std::printf("%s graph replay %d (ctx %lld): %lld ids, %lld tokens differ\n", d1 || d2 ? "FAIL" : "ok ", rep, - (long long) ctx, (long long) d1, (long long) d2); - } - cudaGraphExecDestroy(ge); - cudaGraphDestroy(g); - cudaStreamDestroy(cs); - return fails; -} - -// back-to-back launches on `cs` (the engine's are too: one stream, inside a graph) -template float time_us(cudaStream_t cs, F&& f, int reps = 300) { - cudaEvent_t a, b; - cudaEventCreate(&a); - cudaEventCreate(&b); - for (int i = 0; i < 5; ++i) f(); - cudaEventRecord(a, cs); - for (int i = 0; i < reps; ++i) f(); - cudaEventRecord(b, cs); - ck(cudaEventSynchronize(b), "time"); - float ms = 0.f; - cudaEventElapsedTime(&ms, a, b); - cudaEventDestroy(a); - cudaEventDestroy(b); - return ms * 1000.f / (float) reps; -} - -int bench() { - std::mt19937 rng(11); - const k::QsaShapes s = k::qsa_real_shapes(); - const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s); - cudaStream_t cs; - ck(cudaStreamCreateWithFlags(&cs, cudaStreamNonBlocking), "stream"); - std::printf("QSA top-k, per call (us); capacity = context + 272 as the speed runs set --max-context\n"); - for (const int64_t ctx : {32768LL, 131072LL, 262144LL - 272}) { - for (const int nq : {1, 5}) { - const int64_t capacity = ctx + 272, max_blocks = capacity / 4 + 2; - std::vector sc((size_t) (nq * max_blocks), 0.f); - std::vector steps((size_t) nq * k::kStepCount); - for (int i = 0; i < nq; ++i) { - const int64_t n_kv = ctx - (nq - 1 - i); - int32_t* st = steps.data() + (size_t) i * k::kStepCount; - st[k::kStepPos] = (int32_t) (n_kv - 1); - st[k::kStepNKv] = (int32_t) n_kv; - st[k::kStepNBid] = (int32_t) (n_kv / 4); - st[k::kStepWidth] = (int32_t) k::qsa_selection_width(n_kv, s); - fill_row(sc.data() + (size_t) i * max_blocks, n_kv, n_kv / 4, kRandom, rng); - } - Dev d_sc(sc.size()); - Dev d_st(steps.size()), d_ids((size_t) (nq * cap)); - d_sc.put(sc); - d_st.put(steps); - const float* sp = d_sc.p; - const int32_t* st = d_st.p; - int32_t* ids = d_ids.p; - const float t_old = time_us(cs, [&] { k::qsa_block_topk(sp, st, nq, max_blocks, cap, s, ids, cs); }); - const float t_ref = time_us(cs, [&] { k::qsa_block_topk_ref(sp, st, nq, max_blocks, cap, s, ids, cs); }); - const float t_new = time_us(cs, [&] { k::qsa_block_topk_cluster(sp, st, nq, max_blocks, cap, s, ids, cs); }); - std::printf(" ctx %6lld nq %d: one-CTA dispatch %7.1f (ref %7.1f) cluster %6.1f -> %.1fx\n", - (long long) ctx, nq, t_old, t_ref, t_new, t_old / t_new); - } - } - std::printf("argmax, per call (us)\n"); - for (const int nv : {248320, 32768}) { - for (const int T : {1, 5}) { - std::vector l((size_t) nv * T); - for (int t = 0; t < T; ++t) fill_logits(l.data() + (size_t) t * nv, nv, aRandom, rng); - Dev d_l(l.size()); - Dev d_o((size_t) T); - d_l.put(l); - k::SamplerParams sp; - sp.greedy = true; - const float t_old = time_us(cs, [&] { k::sample_tokens(d_l.p, T, nv, nullptr, 0, sp, d_o.p, cs); }); - const float t_new = time_us(cs, [&] { k::sample_greedy_cluster(d_l.p, T, nv, d_o.p, cs); }); - std::printf(" n_vocab %6d T %d: one block %6.1f cluster %5.1f -> %.1fx\n", nv, T, t_old, t_new, - t_old / t_new); - } - } - cudaStreamDestroy(cs); - return 0; -} - -} // namespace - -int main(int argc, char** argv) { - set_env("STRATA_QSA_CLUSTER", "0"); // the dispatchers: the one-CTA kernels (the cluster ones called directly) - set_env("STRATA_ARGMAX_MULTI", "0"); - const bool do_bench = argc > 1 && std::strcmp(argv[1], "--bench") == 0; - const bool verbose = argc > 2 && std::strcmp(argv[2], "-v") == 0; - int dev = 0, major = 0; - ck(cudaGetDevice(&dev), "device"); - ck(cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev), "cc"); - std::mt19937 rng(20261002); - // first, so that both kernels' first calls (their per-device checks and opt-ins) happen inside a stream capture, - // as in the engine's decode graphs - const int gfails = run_graph_case(rng); - if (gfails < 0) { - std::printf("SKIP: no thread-block clusters on this card / build (compute capability %d)\n", major); - return 0; - } - if (do_bench) return bench(); - int fails = 0, cases = 0; - // contexts: below the width (identity), at it, just past it, odd tails, the register kernel's range, past it - // (block_topk_kernel), up to 262,144; capacities: tight (the speed runs) and 262,144 (a long --max-context) - const int64_t ctxs[] = {7, 2050, 2051, 2052, 2053, 2054, 2055, 3001, 9000, 32768, 32769, 65538, 100003, - 131072, 135170, 135171, 200001, 262142, 262143, 262144}; - for (const int64_t ctx : ctxs) { - for (const int64_t capacity : {ctx + 272, (int64_t) 262144 + 272}) { - if (capacity < ctx) continue; - for (int p = 0; p < kPatterns; ++p) { - const int nq = (p % 3 == 0) ? 1 : (p % 3 == 1 ? 5 : 16); - if (nq > ctx) continue; - fails += run_topk_case({ctx, capacity, nq, p}, rng, verbose); - ++cases; - } - } - } - std::printf("QSA top-k: %d cases, %d failed\n", cases, fails); - int afails = 0, acases = 0; - for (const int nv : {248320, 248321, 248319, 32771, 24576, 8193, 1000, 33, 1}) { - for (int p = 0; p < aPatterns; ++p) { - for (const int T : {1, 5}) { - afails += run_argmax_case(nv, T, p, rng, verbose); - ++acases; - } - } - } - std::printf("argmax: %d cases, %d failed\n", acases, afails); - const int total = fails + afails + gfails; - std::printf("%s\n", total == 0 ? "PASS: the cluster kernels are bitwise identical" : "FAIL"); - return total == 0 ? 0 : 1; -} diff --git a/src/kernels/dequant_bf16_test.cpp b/src/kernels/dequant_bf16_test.cpp deleted file mode 100644 index 80d3d53..0000000 --- a/src/kernels/dequant_bf16_test.cpp +++ /dev/null @@ -1,108 +0,0 @@ -// src/kernels/dequant_bf16_test.cpp - plan v0.3 P5: the device dequantizers against the artifact's validated CPU -// dequantizers (`strata/artifact/dequant.hpp`), on one real tensor of every type the model uses. -// -// dequant_bf16_test SHARD1.gguf [SHARD2.gguf] -// -// For each type: the first 4 rows of the first tensor of that type, FP32 path compared with a relative tolerance of -// 1e-6 (the products are the reference's, reordered at most), BF16 path within half a BF16 ulp of the CPU value. -#include "strata/artifact/dequant.hpp" -#include "strata/artifact/gguf_reader.hpp" -#include "strata/kernels/dequant_bf16.hpp" - -#include - -#include -#include -#include -#include -#include -#include - -namespace { - -bool cpu_block(int type, const uint8_t* b, float* out) { - using namespace strata; - switch (type) { - case 2: dequantize_q4_0(b, out); return true; - case 6: dequantize_q5_0(b, out); return true; - case 8: dequantize_q8_0(b, out); return true; - case 11: dequantize_q3_K(b, out); return true; - case 12: dequantize_q4_K(b, out); return true; - case 13: dequantize_q5_K(b, out); return true; - case 14: dequantize_q6_K(b, out); return true; - case 20: dequantize_iq4_nl(b, out); return true; - case 23: dequantize_iq4_xs(b, out); return true; - case 42: dequantize_q2_0(b, out); return true; - default: return false; - } -} - -float bf16_to_f32(uint16_t h) { - uint32_t u = (uint32_t) h << 16; - float f; - std::memcpy(&f, &u, 4); - return f; -} - -} // namespace - -int main(int argc, char** argv) { - if (argc < 2) { - std::fprintf(stderr, "usage: dequant_bf16_test SHARD.gguf [SHARD2.gguf]\n"); - return 2; - } - std::map done; - int fails = 0, checked = 0; - for (int a = 1; a < argc; ++a) { - strata::GgufFile gguf(argv[a]); - for (const auto& t : gguf.tensors()) { - const int type = (int) t.type; - if (done.count(type) || !strata::kernels::dequant_bf16_supported(type) || t.shape.size() != 2) continue; - int be = 0, bb = 0; - if (!strata::block_geometry(t.type, be, bb)) continue; - const int64_t cols = (int64_t) t.shape[0]; - const int64_t rows = (std::min)(4, (int64_t) t.shape[1]); - const int64_t row_bytes = cols / be * bb; - const uint8_t* host = (const uint8_t*) gguf.tensor_data(t); - void* d_blocks = nullptr; - float* d_f = nullptr; - uint16_t* d_h = nullptr; - cudaMalloc(&d_blocks, (size_t) (rows * row_bytes)); - cudaMalloc(&d_f, (size_t) (rows * cols) * 4); - cudaMalloc(&d_h, (size_t) (rows * cols) * 2); - cudaMemcpy(d_blocks, host, (size_t) (rows * row_bytes), cudaMemcpyHostToDevice); - strata::kernels::dequant_f32(type, d_blocks, 0, rows, cols, d_f, nullptr); - strata::kernels::dequant_bf16(type, d_blocks, 0, rows, cols, d_h, nullptr); - std::vector gf((size_t) (rows * cols)); - std::vector gh((size_t) (rows * cols)); - cudaMemcpy(gf.data(), d_f, gf.size() * 4, cudaMemcpyDeviceToHost); - cudaMemcpy(gh.data(), d_h, gh.size() * 2, cudaMemcpyDeviceToHost); - cudaFree(d_blocks); - cudaFree(d_f); - cudaFree(d_h); - std::vector ref((size_t) (rows * cols)); - for (int64_t r = 0; r < rows; ++r) - for (int64_t b = 0; b < cols / be; ++b) - cpu_block(type, host + r * row_bytes + b * bb, ref.data() + r * cols + b * be); - int64_t bad_f = 0, bad_h = 0; - double worst = 0; - for (size_t i = 0; i < ref.size(); ++i) { - const double e = std::fabs((double) gf[i] - ref[i]); - const double tol = 1e-6 * std::fabs((double) ref[i]) + 1e-30; - if (e > tol) ++bad_f; - worst = (std::max)(worst, e / (std::fabs((double) ref[i]) + 1e-30)); - const double eh = std::fabs((double) bf16_to_f32(gh[i]) - ref[i]); - if (eh > std::ldexp(std::fabs((double) ref[i]), -8) + 1e-30) ++bad_h; - } - ++checked; - done[type] = true; - const bool ok = bad_f == 0 && bad_h == 0; - if (!ok) ++fails; - std::printf("type %2d %-40s %lld x %lld: f32 %s (%lld off, worst rel %.2e), bf16 %s (%lld off)\n", type, - t.name.c_str(), (long long) rows, (long long) cols, bad_f ? "FAIL" : "ok", (long long) bad_f, - worst, bad_h ? "FAIL" : "ok", (long long) bad_h); - } - } - std::printf("dequant_bf16_test: %d types checked, %s\n", checked, fails ? "FAILED" : "OK"); - return fails ? 1 : 0; -} diff --git a/src/kernels/dequant_s2_parity.cpp b/src/kernels/dequant_s2_parity.cpp deleted file mode 100644 index 58e3970..0000000 --- a/src/kernels/dequant_s2_parity.cpp +++ /dev/null @@ -1,143 +0,0 @@ -// src/kernels/dequant_s2_parity.cpp - P2.S2's parity test for the S2 decode. -// -// THE REFERENCE IS THE CHAIN, NOT A SECOND OPINION. `strata::dequantize_q2_0` (include/strata/artifact/ -// dequant.hpp) is a scalar transcription that `bench/micro/dequant_xcheck` checks against **ggml's own** -// dequantizer on real block bytes; and `tools/canonical_xcheck.py --full` checks that the canonical form -// decodes to the same values on every block of the artifact. So this compares "GPU canonical decode" against -// "CPU decode already proven equal to ggml", and a fault in either the canonicaliser or the kernel shows up -// here. A parity test whose two sides were written together would show neither. -#include "strata/artifact/dequant.hpp" -#include "strata/kernels/dequant_s2.hpp" - -#include - -#include -#include -#include -#include -#include - -namespace { - -constexpr int QK = 64; - -void check(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -// fp16 patterns that are finite, normal and exactly representable. Random 16-bit patterns would include NaN -// and infinity, and a NaN makes `!=` true for a reason that has nothing to do with the kernel - the test -// would fail for the wrong cause, or worse, a real fault would hide behind a NaN it caused itself. -const uint16_t kScales[] = {0x3C00, 0x3800, 0x3400, 0x3000, 0x2C00, 0x2800, 0x2000, - 0xBC00, 0xB800, 0xB400, 0xB000, 0xAC00, 0x1800, 0x1400}; - -} // namespace - -int main(int argc, char** argv) { - long long n_blocks = 200000; - bool selftest = false; - for (int i = 1; i < argc; ++i) { - if (std::strcmp(argv[i], "--selftest") == 0) selftest = true; - else if (std::strcmp(argv[i], "--blocks") == 0 && i + 1 < argc) n_blocks = std::atoll(argv[++i]); - else { - std::fprintf(stderr, "usage: dequant_s2_parity [--selftest] [--blocks N]\n"); - return 2; - } - } - if (n_blocks <= 0) { std::fprintf(stderr, "--blocks must be positive\n"); return 2; } - - std::mt19937 rng(12345); - const int n_scales = (int) (sizeof(kScales) / sizeof(kScales[0])); - - // raw Q2_0 blocks: { fp16 d ; uint8 qs[16] } - what ggml produced and what the artifact stores - std::vector raw((size_t) n_blocks * 18); - for (long long b = 0; b < n_blocks; ++b) { - const uint16_t d = kScales[rng() % n_scales]; - raw[(size_t) b * 18 + 0] = (uint8_t) (d & 0xFF); - raw[(size_t) b * 18 + 1] = (uint8_t) (d >> 8); - for (int t = 0; t < 16; ++t) raw[(size_t) b * 18 + 2 + t] = (uint8_t) (rng() & 0xFF); - } - - // the CPU reference, over the RAW blocks - std::vector cpu((size_t) n_blocks * QK); - for (long long b = 0; b < n_blocks; ++b) { - strata::dequantize_q2_0(&raw[(size_t) b * 18], &cpu[(size_t) b * QK]); - } - - // canonical planes: S2 packs 4 codes per byte exactly as Q2_0 stores them, so the codes plane is the raw - // qs bytes; the scales plane is the fp16 `d` widened. Copied into planes of their own rather than - // aliased, because that is what the kernel will read in the engine. - std::vector codes((size_t) n_blocks * 16); - std::vector scales((size_t) n_blocks); - for (long long b = 0; b < n_blocks; ++b) { - std::memcpy(&codes[(size_t) b * 16], &raw[(size_t) b * 18 + 2], 16); - const uint16_t d = (uint16_t) (raw[(size_t) b * 18] | (raw[(size_t) b * 18 + 1] << 8)); - scales[(size_t) b] = strata::fp16_to_fp32(d); - } - - uint8_t* d_codes = nullptr; - float *d_scales = nullptr, *d_out = nullptr; - check(cudaMalloc(&d_codes, codes.size()), "cudaMalloc codes"); - check(cudaMalloc(&d_scales, scales.size() * sizeof(float)), "cudaMalloc scales"); - check(cudaMalloc(&d_out, cpu.size() * sizeof(float)), "cudaMalloc out"); - check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "copy codes"); - check(cudaMemcpy(d_scales, scales.data(), scales.size() * sizeof(float), cudaMemcpyHostToDevice), - "copy scales"); - - strata::kernels::dequant_s2(d_codes, d_scales, d_out, n_blocks); - - std::vector gpu(cpu.size()); - check(cudaMemcpy(gpu.data(), d_out, gpu.size() * sizeof(float), cudaMemcpyDeviceToHost), "copy back"); - - long long bad = 0, first_bad = -1; - for (size_t i = 0; i < cpu.size(); ++i) { - // bit comparison, not a tolerance: S2's decode is exact integer-to-float arithmetic, so ANY - // difference is a bug and a tolerance would only hide which one - if (std::memcmp(&cpu[i], &gpu[i], sizeof(float)) != 0) { - if (first_bad < 0) first_bad = (long long) i; - ++bad; - } - } - - // NON-VACUITY. Two buffers of zeros compare equal, and so do two buffers a broken test filled with the - // same constant - an agreement check that cannot distinguish "both correct" from "both empty" is the - // failure this project keeps finding. So the data must actually vary, and the four codes must all occur: - // an S2 decode that only ever saw one code would agree while being unable to tell -1 from +2. - bool seen[4] = {false, false, false, false}; - for (size_t i = 0; i < codes.size(); ++i) { - for (int t = 0; t < 4; ++t) seen[(codes[i] >> (2 * t)) & 3] = true; - } - int distinct = 0; - for (bool s : seen) distinct += s ? 1 : 0; - long long distinct_vals = 0; - for (size_t i = 0; i < cpu.size() && distinct_vals < 8; ++i) { - bool dup = false; - for (size_t j = 0; j < i && !dup; ++j) dup = (cpu[j] == cpu[i]); - if (!dup) ++distinct_vals; - } - std::printf(" non-vacuity: %d of 4 codes present, %lld distinct values in the first elements\n", distinct, - distinct_vals); - if (distinct != 4 || distinct_vals < 4) { - std::fprintf(stderr, "VACUOUS: the comparison could not have distinguished a wrong decode\n"); - return 1; - } - - std::printf("dequant_s2: %lld blocks, %lld elements, %lld mismatched\n", n_blocks, (long long) cpu.size(), - bad); - if (bad) { - std::printf(" first mismatch at element %lld (block %lld, offset %d): cpu %.9g gpu %.9g\n", - (long long) first_bad, (long long) (first_bad / QK), (int) (first_bad % QK), - (double) cpu[(size_t) first_bad], (double) gpu[(size_t) first_bad]); - return 1; - } - std::printf(" bit-exact against the scalar dequantizer that dequant_xcheck proved equal to ggml\n"); - if (selftest) std::printf("dequant_s2_parity OK\n"); - - cudaFree(d_codes); - cudaFree(d_scales); - cudaFree(d_out); - return 0; -} diff --git a/src/kernels/elementwise_parity.cpp b/src/kernels/elementwise_parity.cpp deleted file mode 100644 index 9a8fc3f..0000000 --- a/src/kernels/elementwise_parity.cpp +++ /dev/null @@ -1,475 +0,0 @@ -// src/kernels/elementwise_parity.cpp - P2.S5's test for the layer glue. -// -// The ops are small; the CONVENTIONS in them are not, and each one is a place where a plausible reading -// gives a plausible number: -// -// 1. `softplus` HAS A LARGE-x BRANCH. `log1p(exp(x))` overflows f32 at x > 88 and loses relative precision -// well before that; `ggml_compute_softplus_f32` returns `x` above 20. A rival without the branch is -// asserted observable, because a gate that saturates to +inf makes `exp(gate)` inf and the whole -// recurrence NaN - which reads as a state bug and not as a missing branch. -// 2. `ssm_a` IS NEGATIVE. `gate = softplus(...) * ssm_a`, so `exp(gate) < 1` and the state DECAYS. A -// fixture with a positive `ssm_a` would still produce finite output and the recurrence would blow up -// instead of decaying, so the sign is checked as a property and not assumed. -// 3. `silu` IS COMPUTED IN DOUBLE then cast, because `ref/gdn.py`'s numpy does. f32 `expf` differs in the -// last bits, and the test measures that rather than asserting it away. -#include "strata/kernels/dequant_bf16.hpp" -#include "strata/kernels/elementwise.hpp" -#include "strata/kernels/f16_bits.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace { - -void check(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -double rel_l1(const std::vector& a, const std::vector& 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); -} - -} // namespace - -int main(int argc, char** argv) { - bool selftest = false; - for (int i = 1; i < argc; ++i) { - if (std::string(argv[i]) == "--selftest") selftest = true; - else { std::fprintf(stderr, "usage: elementwise_parity [--selftest]\n"); return 2; } - } - int bad = 0; - const int64_t H_V = 48; - - // ---- 1. gdn_gate, with the reference's own softplus - { - const int n = (int) H_V; - std::mt19937 rng(11); - std::normal_distribution g(0.0f, 1.0f); - std::vector alpha(n), dt(n), a(n), want(n); - for (int i = 0; i < n; ++i) { - // A MIXTURE THAT ACTUALLY CROSSES THE BRANCH. The first version drew alpha from a normal with - // sigma 3, so the largest value was about 9 and `softplus` never took its `x > 20` path - the - // "branch is observable" check then reported **0.00% apart, 0 non-finite**, which is the fixture - // saying it cannot see the thing it was written to see. Every third head is now large. - const bool large = (i % 3) == 0; - // Up to ~120, so the fixture spans WELL PAST f32's `exp` overflow at 88. A fixture that stopped - // at 88 would show the branch as unobservable and would be right: `log1pf(expf(x))` equals `x` to - // f32 precision for the whole range 20..88, so ggml's threshold of 20 is CONSERVATIVE and the - // behaviour only actually changes where `expf` overflows. - alpha[i] = large ? (22.0f + 6.0f * (float) (i % 17)) : g(rng) * 3.0f; - dt[i] = g(rng) * 0.5f; - // NEGATIVE, as the artifact's `ssm_a = -exp(A_log)` is. Checked below as a property. - a[i] = -(std::fabs(g(rng)) + 0.1f); - const double x = (double) alpha[i] + (double) dt[i]; - const double sp = x > 20.0 ? x : std::log1p(std::exp(x)); - want[(size_t) i] = (float) (sp * (double) a[i]); - } - // the fixture must EXERCISE the branch, or check 1 below measures nothing - { - int over = 0, past_overflow = 0; - for (int i = 0; i < n; ++i) { - const float x = alpha[(size_t) i] + dt[(size_t) i]; - if (x > 20.0f) ++over; - if (x > 88.0f) ++past_overflow; - } - std::printf(" %-44s %s (%d above 20, %d above 88)\n", "the fixture crosses the branch", - over ? "yes" : "*** NO ***", over, past_overflow); - if (!over) ++bad; - } - // the sign property, asserted rather than assumed - int positive = 0; - for (int i = 0; i < n; ++i) if (a[(size_t) i] >= 0.0f) ++positive; - std::printf(" %-44s %s (%d of %d non-negative)\n", "the fixture's ssm_a is negative", - positive ? "*** NO ***" : "yes", positive, n); - if (positive) ++bad; - - float *d_a = nullptr, *d_dt = nullptr, *d_sa = nullptr, *d_g = nullptr; - check(cudaMalloc(&d_a, n * 4), "a"); - check(cudaMalloc(&d_dt, n * 4), "dt"); - check(cudaMalloc(&d_sa, n * 4), "sa"); - check(cudaMalloc(&d_g, n * 4), "g"); - check(cudaMemcpy(d_a, alpha.data(), n * 4, cudaMemcpyHostToDevice), "ca"); - check(cudaMemcpy(d_dt, dt.data(), n * 4, cudaMemcpyHostToDevice), "cd"); - check(cudaMemcpy(d_sa, a.data(), n * 4, cudaMemcpyHostToDevice), "cs"); - strata::kernels::gdn_gate(d_a, d_dt, d_sa, d_g, 1, H_V, nullptr); - std::vector got((size_t) n); - check(cudaMemcpy(got.data(), d_g, n * 4, cudaMemcpyDeviceToHost), "cg"); - - const double rel = rel_l1(want, got); - std::printf(" %-44s rel %.3e\n", "gdn_gate vs the reference", rel); - // double softplus and double multiply on both sides, then one cast - if (!(rel <= 1e-6)) { std::printf(" *** over 1e-6 ***\n"); ++bad; } - - // TRAP: no large-x branch. `log1p(exp(x))` in f32, with no `x > 20` path. - // - // AND THE MEASUREMENT SAYS WHERE THE BRANCH ACTUALLY MATTERS. The first version of this fixture - // spanned 20..88 and reported **0 heads differ**: `log1pf(expf(x))` agrees with `x` to f32 precision - // over that whole range, so ggml's threshold of 20 is CONSERVATIVE - the branch changes the answer only - // where `expf` OVERFLOWS, at about 88. The check reports the smallest x at which the two readings - // part company, so the number is in the output rather than in this comment. - { - int wrong = 0, differing = 0; - float first_differ = -1.0f; - std::vector rival((size_t) n); - for (int i = 0; i < n; ++i) { - const float x = alpha[(size_t) i] + dt[(size_t) i]; - const float sp = std::log1p(std::exp(x)); // no branch, f32 - rival[(size_t) i] = sp * a[(size_t) i]; - if (!std::isfinite(sp)) ++wrong; - const float branched = x > 20.0f ? x : std::log1pf(std::exp(x)); - if (sp != branched) { - ++differing; - if (first_differ < 0.0f || x < first_differ) first_differ = x; - } - } - const double r = rel_l1(want, rival); - const bool visible = r > 0.05 || wrong > 0; - std::printf(" %-44s %s (%.2f%% apart, %d non-finite, %d heads differ, first at x = %.1f)\n", - "the softplus large-x branch is observable", visible ? "yes" : "*** NO ***", - r * 100, wrong, differing, (double) first_differ); - if (!visible) ++bad; - } - // PROPERTY: exp(gate) < 1 for every element, which is what makes the state decay - { - int over = 0; - for (float v : got) if (!(std::exp(v) < 1.0f)) ++over; - std::printf(" %-44s %s (%d of %d not < 1)\n", "exp(gate) < 1 for every head", - over ? "*** NO ***" : "yes", over, n); - if (over) ++bad; - } - cudaFree(d_a); cudaFree(d_dt); cudaFree(d_sa); cudaFree(d_g); - } - - // ---- 2. silu, in double then cast - { - const int n = 4096; - std::mt19937 rng(22); - std::normal_distribution g(0.0f, 3.0f); - std::vector x((size_t) n), want((size_t) n); - for (int i = 0; i < n; ++i) { - x[(size_t) i] = g(rng); - const double v = (double) x[(size_t) i]; - want[(size_t) i] = (float) (v / (1.0 + std::exp(-v))); - } - float* d_x = nullptr; - check(cudaMalloc(&d_x, n * 4), "sx"); - check(cudaMemcpy(d_x, x.data(), n * 4, cudaMemcpyHostToDevice), "csx"); - strata::kernels::silu_inplace(d_x, n, nullptr); - std::vector got((size_t) n); - check(cudaMemcpy(got.data(), d_x, n * 4, cudaMemcpyDeviceToHost), "csg"); - const double rel = rel_l1(want, got); - std::printf("\n %-44s rel %.3e\n", "silu (double) vs the reference", rel); - if (!(rel <= 1e-7)) { std::printf(" *** over 1e-7 ***\n"); ++bad; } - cudaFree(d_x); - } - - // ---- 3. scale and the f32->f16 bridge - { - const int n = 1024; - std::vector x((size_t) n), want((size_t) n); - for (int i = 0; i < n; ++i) x[(size_t) i] = (float) (i - n / 2) * 0.013f; - const float s = 1.0f / std::sqrt(128.0f); - for (int i = 0; i < n; ++i) want[(size_t) i] = x[(size_t) i] * s; - - float* d_x = nullptr; - uint16_t* d_h = nullptr; - check(cudaMalloc(&d_x, n * 4), "ex"); - check(cudaMalloc(&d_h, n * 2), "eh"); - check(cudaMemcpy(d_x, x.data(), n * 4, cudaMemcpyHostToDevice), "cex"); - strata::kernels::scale_inplace(d_x, n, s, nullptr); - std::vector got((size_t) n); - check(cudaMemcpy(got.data(), d_x, n * 4, cudaMemcpyDeviceToHost), "ceg"); - int diff = 0; - for (int i = 0; i < n; ++i) if (got[(size_t) i] != want[(size_t) i]) ++diff; - std::printf(" %-44s %d of %d differ\n", "scale_inplace is exact", diff, n); - if (diff) ++bad; - - strata::kernels::f32_to_f16_bulk(d_x, d_h, n, nullptr); - std::vector h((size_t) n); - check(cudaMemcpy(h.data(), d_h, n * 2, cudaMemcpyDeviceToHost), "ceh"); - int hbad = 0; - for (int i = 0; i < n; ++i) - if (h[(size_t) i] != strata::kernels::f16_from_f32(got[(size_t) i])) ++hbad; - std::printf(" %-44s %d of %d differ\n", "f32_to_f16_bulk uses the shared conversion", hbad, n); - if (hbad) ++bad; - cudaFree(d_x); cudaFree(d_h); - } - - // ---- 4. rms_norm_weighted, and the TWO RIVAL READINGS it exists to be told apart from. - // - // This kernel's whole reason for being a separate entry point from `gdn_l2_norm` is that the two differ by - // one `/ cols`, and that a swap produces a well-scaled, plausible tensor. So the test computes BOTH wrong - // readings and requires each to differ from the right one by more than the tolerance before it judges the - // kernel - the same discipline the shared-expert test uses for silu-on-gate. - { - const int64_t rows = 24, cols = 256; // the real `attn_q`-norm shape - const float eps = 1e-6f; - std::vector x((size_t) (rows * cols)); - for (size_t i = 0; i < x.size(); ++i) x[i] = (float) std::sin((double) i * 0.017) * 1.7f + 0.4f; - std::vector w((size_t) cols); - for (int64_t c = 0; c < cols; ++c) w[(size_t) c] = 0.5f + 0.002f * (float) (c % 97); - - // the oracle: f64, mean, times w - auto ref = [&](bool use_sum, bool use_w) { - std::vector y((size_t) (rows * cols)); - for (int64_t r = 0; r < rows; ++r) { - double ss = 0; - for (int64_t c = 0; c < cols; ++c) { - const double v = x[(size_t) (r * cols + c)]; - ss += v * v; - } - const double den = std::sqrt((use_sum ? ss : ss / (double) cols) + (double) eps); - for (int64_t c = 0; c < cols; ++c) { - const double v = x[(size_t) (r * cols + c)]; - y[(size_t) (r * cols + c)] = (v / den) * (use_w ? (double) w[(size_t) c] : 1.0); - } - } - std::vector out((size_t) (rows * cols)); - for (size_t i = 0; i < out.size(); ++i) out[i] = (float) y[i]; - return out; - }; - const std::vector want = ref(false, true); - const std::vector rival_sum = ref(true, false); // what gdn_l2_norm computes - const std::vector rival_now = ref(false, false); // the (1+w)-vs-w / no-weight confusion - - auto rel = [&](const std::vector& a, const std::vector& 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); - }; - const double r_sum = rel(want, rival_sum), r_now = rel(want, rival_now); - std::printf(" %-44s %.2f%% apart\n", "sum-vs-mean is observable", r_sum * 100); - std::printf(" %-44s %.2f%% apart\n", "with-w-vs-without-w is observable", r_now * 100); - // `sqrt(cols)` = 16 for the first and the weight's own spread for the second; a fixture that cannot - // separate them is not testing the kernel that was written. - if (!(r_sum > 0.5)) { std::printf(" *** the sum reading is NOT observable ***\n"); ++bad; } - if (!(r_now > 0.5)) { std::printf(" *** the no-weight reading is NOT observable ***\n"); ++bad; } - - float* d_x = nullptr; - float* d_w = nullptr; - check(cudaMalloc(&d_x, x.size() * 4), "m rmsx"); - check(cudaMalloc(&d_w, w.size() * 4), "m rmsw"); - check(cudaMemcpy(d_x, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "c rmsx"); - check(cudaMemcpy(d_w, w.data(), w.size() * 4, cudaMemcpyHostToDevice), "c rmsw"); - strata::kernels::rms_norm_weighted(d_x, d_w, rows, cols, eps, nullptr); - std::vector got((size_t) (rows * cols)); - check(cudaMemcpy(got.data(), d_x, got.size() * 4, cudaMemcpyDeviceToHost), "c rmsg"); - - const double r_got = rel(want, got); - double worst = 0; - for (size_t i = 0; i < got.size(); ++i) { - const double m = std::fabs((double) want[i]); - const double e = std::fabs((double) got[i] - (double) want[i]) / (m > 1e-30 ? m : 1e-30); - if (e > worst) worst = e; - } - int nonfinite = 0; - for (float v : got) if (!std::isfinite(v)) ++nonfinite; - std::printf(" %-44s rel %.3e worst %.3e nonfinite %d\n", "rms_norm_weighted vs f64 oracle", r_got, - worst, nonfinite); - if (nonfinite) ++bad; - // The kernel accumulates in f32 over 256 terms; 1e-6 is loose enough for that and far tighter than the - // 16x the rival readings are off by. - if (!(r_got < 1e-6)) { std::printf(" *** rms_norm_weighted is WRONG ***\n"); ++bad; } - // and a null `w` must be legal, because `ref/qsa.py` allows it. - // - // THE INPUT HAS TO BE RE-UPLOADED FIRST. The kernel is IN PLACE, so `d_x` currently holds the - // NORMALISED tensor from the call above; running it again normalises a second time and every element - // differs. That is exactly what the first version of this check reported - "6144 of 6144 differ" - - // and it is a fixture bug rather than a kernel bug: the oracle reads the ORIGINAL `x`, so the two - // sides were never looking at the same input. - const std::vector want_null = ref(false, false); - check(cudaMemcpy(d_x, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "c rmsx2"); - strata::kernels::rms_norm_weighted(d_x, nullptr, rows, cols, eps, nullptr); - check(cudaMemcpy(got.data(), d_x, got.size() * 4, cudaMemcpyDeviceToHost), "c rmsn"); - int null_bad = 0; - for (size_t i = 0; i < got.size(); ++i) - if (std::fabs((double) got[i] - (double) want_null[i]) > 1e-6) ++null_bad; - std::printf(" %-44s %d of %zu differ\n", "a null weight is legal", null_bad, got.size()); - if (null_bad) ++bad; - cudaFree(d_x); - cudaFree(d_w); - } - - // Packed embedding rows: every code width, scale-group size, optional offset, - // row boundary and partial CUDA block. Compare bits with a scalar CPU decoder. - // Volatile materializes the multiply so this oracle cannot silently use FMA. - { - cudaStream_t stream; - check(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), "embedding stream"); - std::mt19937 rng(77); - std::uniform_real_distribution values(-2.0f, 2.0f); - int mismatches = 0, guards = 0, fma_diff = 0, cases = 0; - for (const int bits : {2, 4, 8}) { - const int bias = bits == 2 ? -1 : bits == 4 ? -7 : -16; - const int per_byte = 8 / bits; - const unsigned mask = (1u << bits) - 1u; - for (const int group : {16, 32, 64}) { - for (const int n : {320, 2560}) { - const int row_bytes = n / per_byte, row_groups = n / group; - std::vector codes((size_t) 3 * row_bytes, 0); - std::vector scales((size_t) 3 * row_groups), offsets(scales.size()); - std::vector unpacked((size_t) 3 * n); - for (size_t i = 0; i < unpacked.size(); ++i) { - const unsigned code = (unsigned) (i * 13 + i / n * 7) & mask; - unpacked[i] = (int) code; - codes[i / per_byte] |= (uint8_t) (code << ((i % per_byte) * bits)); - } - for (size_t i = 0; i < scales.size(); ++i) { - scales[i] = values(rng); - offsets[i] = values(rng); - } - scales[0] = -0.0f; - offsets[0] = 0.0f; - uint8_t* dc = nullptr; - float *ds = nullptr, *dof = nullptr, *out = nullptr; - check(cudaMalloc(&dc, codes.size()), "embedding codes"); - check(cudaMalloc(&ds, scales.size() * sizeof(float)), "embedding scales"); - check(cudaMalloc(&dof, offsets.size() * sizeof(float)), "embedding offsets"); - check(cudaMalloc(&out, ((size_t) n + 2) * sizeof(float)), "embedding output"); - check(cudaMemcpyAsync(dc, codes.data(), codes.size(), cudaMemcpyHostToDevice, stream), "embedding codes upload"); - check(cudaMemcpyAsync(ds, scales.data(), scales.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "embedding scales upload"); - check(cudaMemcpyAsync(dof, offsets.data(), offsets.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "embedding offsets upload"); - check(cudaStreamSynchronize(stream), "embedding upload sync"); - - for (const bool with_offset : {false, true}) { - for (int row = 0; row < 3; ++row) { - std::vector want((size_t) n), got((size_t) n + 2, -12345.0f); - for (int i = 0; i < n; ++i) { - const size_t gi = (size_t) row * row_groups + i / group; - const float code = (float) (unpacked[(size_t) row * n + i] + bias); - volatile float product = code * scales[gi]; - const float offset = with_offset ? offsets[gi] : 0.0f; - want[(size_t) i] = product + offset; - const float fused = std::fma(code, scales[gi], offset); - if (std::memcmp(&fused, &want[(size_t) i], sizeof(float)) != 0) ++fma_diff; - } - check(cudaMemcpyAsync(out, got.data(), got.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "embedding output guards"); - strata::kernels::embedding_gather(dc + (size_t) row * row_bytes, - ds + (size_t) row * row_groups, - with_offset ? dof + (size_t) row * row_groups : nullptr, - n, bits, bias, group, out + 1, stream); - check(cudaMemcpyAsync(got.data(), out, got.size() * sizeof(float), cudaMemcpyDeviceToHost, stream), "embedding result"); - check(cudaStreamSynchronize(stream), "embedding sync"); - for (int i = 0; i < n; ++i) { - if (std::memcmp(&want[(size_t) i], &got[(size_t) i + 1], sizeof(float)) != 0) ++mismatches; - } - if (got.front() != -12345.0f || got.back() != -12345.0f) ++guards; - ++cases; - - // Capturing the gather proves that it has no hidden synchronization. - // A following scale also checks that it uses the caller's stream. - if (row == 1) { - cudaGraph_t graph; - cudaGraphExec_t exec; - check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "embedding capture"); - strata::kernels::embedding_gather(dc + (size_t) row * row_bytes, - ds + (size_t) row * row_groups, - with_offset ? dof + (size_t) row * row_groups : nullptr, - n, bits, bias, group, out + 1, stream); - strata::kernels::scale_inplace(out + 1, n, 2.0f, stream); - check(cudaStreamEndCapture(stream, &graph), "embedding capture end"); - check(cudaGraphInstantiate(&exec, graph, 0), "embedding instantiate"); - check(cudaGraphLaunch(exec, stream), "embedding replay"); - check(cudaMemcpyAsync(got.data(), out, got.size() * sizeof(float), cudaMemcpyDeviceToHost, stream), "embedding graph result"); - check(cudaStreamSynchronize(stream), "embedding graph sync"); - for (int i = 0; i < n; ++i) { - const float expected = want[(size_t) i] * 2.0f; - if (std::memcmp(&expected, &got[(size_t) i + 1], sizeof(float)) != 0) ++mismatches; - } - if (got.front() != -12345.0f || got.back() != -12345.0f) ++guards; - check(cudaGraphExecDestroy(exec), "embedding exec destroy"); - check(cudaGraphDestroy(graph), "embedding graph destroy"); - } - } - } - cudaFree(dc); cudaFree(ds); cudaFree(dof); cudaFree(out); - } - } - } - check(cudaStreamDestroy(stream), "embedding stream destroy"); - std::printf(" embedding gather: %d row cases, %d bit mismatches, %d guard failures, %d FMA differences\n", - cases, mismatches, guards, fma_diff); - if (mismatches || guards || fma_diff == 0) ++bad; - } - - // ---- THE f32 -> bf16 CONVERSIONS KEEP A NaN A NaN. `f32_to_bf16_bulk` (the header's `bf16_from_f32` - // on the device) and the prompt path's dequantizer (its own `f2bf`) against ggml_compute_fp32_to_bf16's rule; - // before the fix 0x7FFFFFFF came back as -0 and 0x7F800001 as +inf. `bf16_bits_test` covers every f32 on - // the host; this is the same header compiled by nvcc, plus the second copy in dequant_bf16.cu. - { - auto ggml_bf16 = [](uint32_t u) -> uint16_t { - if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64); - return (uint16_t) ((u + (0x7fffu + ((u >> 16) & 1u))) >> 16); - }; - std::vector bits = {0x7FFFFFFFu, 0xFFFFFFFFu, 0x7F800001u, 0xFF800001u, 0x7FC00000u, 0x7FBFFFFFu, - 0x7F800000u, 0xFF800000u, 0x7F7FFFFFu, 0x00000000u, 0x80000000u, 0x3F808000u, - 0x3F818000u, 0x00008000u, 0x7F7F8000u}; - std::mt19937 rng(13); - while (bits.size() < 4096) bits.push_back((uint32_t) rng()); - const size_t n = bits.size(); - float* dx = nullptr; - uint16_t* dy = nullptr; - check(cudaMalloc(&dx, n * 4), "bf16 x"); - check(cudaMalloc(&dy, n * 2), "bf16 y"); - check(cudaMemcpy(dx, bits.data(), n * 4, cudaMemcpyHostToDevice), "bf16 cx"); - strata::kernels::f32_to_bf16_bulk(dx, dy, (int64_t) n, nullptr); - std::vector got(n); - check(cudaMemcpy(got.data(), dy, n * 2, cudaMemcpyDeviceToHost), "bf16 cy"); - int wrong = 0; - for (size_t i = 0; i < n; ++i) wrong += got[i] != ggml_bf16(bits[i]); - - // A Q8_0 block (type 8) whose fp16 scale is a NaN: every dequantized value is NaN * q, a NaN, and it must - // still be one in BF16. A second block with an ordinary scale checks the finite path did not move. - std::vector blk(2 * 34, 0); - blk[0] = 0x00; blk[1] = 0x7E; // fp16 quiet NaN - blk[34] = 0x00; blk[35] = 0x3C; // fp16 1.0 - for (int j = 0; j < 32; ++j) { - blk[(size_t) (2 + j)] = (uint8_t) (int8_t) (j - 16); - blk[(size_t) (36 + j)] = (uint8_t) (int8_t) (3 * j - 50); - } - uint8_t* db = nullptr; - uint16_t* dq = nullptr; - check(cudaMalloc(&db, blk.size()), "q8 blk"); - check(cudaMalloc(&dq, 64 * 2), "q8 out"); - check(cudaMemcpy(db, blk.data(), blk.size(), cudaMemcpyHostToDevice), "q8 cblk"); - strata::kernels::dequant_bf16(8, db, 0, 2, 32, dq, nullptr); - check(cudaDeviceSynchronize(), "dequant_bf16"); - std::vector q(64); - check(cudaMemcpy(q.data(), dq, 64 * 2, cudaMemcpyDeviceToHost), "q8 cout"); - int dq_wrong = 0; - for (int j = 0; j < 32; ++j) { - if (!((q[(size_t) j] & 0x7FFFu) > 0x7F80u)) ++dq_wrong; // row 0: NaN scale -> NaN - const float v = (float) (3 * j - 50); // row 1: d = 1.0 -> the integer - uint32_t vb; - std::memcpy(&vb, &v, 4); - if (q[(size_t) (32 + j)] != ggml_bf16(vb)) ++dq_wrong; - } - std::printf(" f32 -> bf16 (NaN kept): bulk %d of %zu differ from ggml, dequant_bf16 %d of 64 wrong\n", - wrong, n, dq_wrong); - if (wrong || dq_wrong) ++bad; - cudaFree(dx); cudaFree(dy); cudaFree(db); cudaFree(dq); - } - - std::printf("\nelementwise: %d failures\n", bad); - if (bad) return 1; - if (selftest) std::printf("elementwise_parity OK\n"); - return 0; -} diff --git a/src/kernels/fused_gr_bench.cpp b/src/kernels/fused_gr_bench.cpp deleted file mode 100644 index b7b8452..0000000 --- a/src/kernels/fused_gr_bench.cpp +++ /dev/null @@ -1,116 +0,0 @@ -// src/kernels/fused_gr_bench.cpp - fused_gr_read_multi: the AMD fast kernels (STRATA_GR_FAST) against the old -// ones, bit for bit on every output (lo, rs, inject, mixed, the in-place R), and each one's time. -// -// build/fused_gr_bench [iters] [T min] [T max] -#include "strata/kernels/fused_gr.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace K = strata::kernels; - -static uint16_t bf16(float x) { - uint32_t u; - std::memcpy(&u, &x, 4); - return (uint16_t) ((u + 0x7fff + ((u >> 16) & 1)) >> 16); -} - -int main(int argc, char** argv) { - setvbuf(stdout, nullptr, _IONBF, 0); - const int iters = argc > 1 ? std::atoi(argv[1]) : 500; - const int t_lo = argc > 2 ? std::atoi(argv[2]) : 1, t_hi = argc > 3 ? std::atoi(argv[3]) : 6; - const int N = 2560, HC = 4, D = N * HC, LR = 320, TM = K::kFusedGrMaxT; - std::mt19937 rng(7); - std::normal_distribution nd(0.f, 1.f); - auto fill = [&](std::vector& v, float sc) { for (auto& x : v) x = sc * nd(rng); }; - std::vector R((size_t) TM * D), bo((size_t) TM * N), inj((size_t) TM * HC), wn(D); - fill(R, 1.0f); fill(bo, 0.5f); fill(inj, 1.0f); fill(wn, 0.3f); - for (auto& x : wn) x += 1.0f; - std::vector wd((size_t) LR * D), wu((size_t) D * LR), wi((size_t) HC * D); - for (auto& x : wd) x = bf16(0.02f * nd(rng)); - for (auto& x : wu) x = bf16(0.05f * nd(rng)); - for (auto& x : wi) x = bf16(0.02f * nd(rng)); - float *dR, *dbo, *dinj, *dwn, *dxn, *dlo, *drs, *dio, *dmix; - uint16_t *dwd, *dwu, *dwi; - cudaMalloc((void**) &dR, R.size() * 4); - cudaMalloc((void**) &dbo, bo.size() * 4); - cudaMalloc((void**) &dinj, inj.size() * 4); - cudaMalloc((void**) &dwn, wn.size() * 4); - cudaMalloc((void**) &dxn, (size_t) TM * D * 4); - cudaMalloc((void**) &dlo, (size_t) TM * LR * 4); - cudaMalloc((void**) &drs, (size_t) TM * HC * 4); - cudaMalloc((void**) &dio, (size_t) TM * HC * 4); - cudaMalloc((void**) &dmix, (size_t) TM * N * 4); - cudaMalloc((void**) &dwd, wd.size() * 2); - cudaMalloc((void**) &dwu, wu.size() * 2); - cudaMalloc((void**) &dwi, wi.size() * 2); - cudaMemcpy(dbo, bo.data(), bo.size() * 4, cudaMemcpyHostToDevice); - cudaMemcpy(dinj, inj.data(), inj.size() * 4, cudaMemcpyHostToDevice); - cudaMemcpy(dwn, wn.data(), wn.size() * 4, cudaMemcpyHostToDevice); - cudaMemcpy(dwd, wd.data(), wd.size() * 2, cudaMemcpyHostToDevice); - cudaMemcpy(dwu, wu.data(), wu.size() * 2, cudaMemcpyHostToDevice); - cudaMemcpy(dwi, wi.data(), wi.size() * 2, cudaMemcpyHostToDevice); - cudaStream_t s; - cudaStreamCreate(&s); - cudaEvent_t e0, e1; - cudaEventCreate(&e0); - cudaEventCreate(&e1); - int failures = 0; - for (int T = t_lo; T <= t_hi; ++T) - for (int apply = 0; apply < 2; ++apply) - for (int inject = 0; inject < 2; ++inject) { - K::FusedGrArgs a[TM]; - for (int t = 0; t < T; ++t) { - a[t].R = dR + (size_t) t * D; a[t].R_out = dR + (size_t) t * D; a[t].apply = apply; - a[t].bo_prev = dbo + (size_t) t * N; a[t].inj_prev = dinj + (size_t) t * HC; - a[t].w_norm = dwn; a[t].w_down = dwd; a[t].w_up = dwu; a[t].w_inject = inject ? dwi : nullptr; - a[t].lo = dlo + (size_t) t * LR; a[t].rs = drs + (size_t) t * HC; - a[t].inject_out = dio + (size_t) t * HC; a[t].mixed = dmix + (size_t) t * N; - } - std::vector out[2]; - for (int f = 0; f < 2; ++f) { - cudaMemcpy(dR, R.data(), R.size() * 4, cudaMemcpyHostToDevice); - cudaMemset(dlo, 0xff, (size_t) TM * LR * 4); - cudaMemset(drs, 0xff, (size_t) TM * HC * 4); - cudaMemset(dio, 0xff, (size_t) TM * HC * 4); - cudaMemset(dmix, 0xff, (size_t) TM * N * 4); - K::fused_gr_set_fast(f); - K::fused_gr_read_multi(a, T, dxn, s); - cudaStreamSynchronize(s); - auto& o = out[f]; - o.resize((size_t) TM * (D + LR + HC + HC + N)); - float* p = o.data(); - cudaMemcpy(p, dR, (size_t) TM * D * 4, cudaMemcpyDeviceToHost); p += (size_t) TM * D; - cudaMemcpy(p, dlo, (size_t) TM * LR * 4, cudaMemcpyDeviceToHost); p += (size_t) TM * LR; - cudaMemcpy(p, drs, (size_t) TM * HC * 4, cudaMemcpyDeviceToHost); p += (size_t) TM * HC; - cudaMemcpy(p, dio, (size_t) TM * HC * 4, cudaMemcpyDeviceToHost); p += (size_t) TM * HC; - cudaMemcpy(p, dmix, (size_t) TM * N * 4, cudaMemcpyDeviceToHost); - } - const bool same = std::memcmp(out[0].data(), out[1].data(), out[0].size() * 4) == 0; - double us[2] = {1e30, 1e30}; - for (int round = 0; round < 3; ++round) - for (int f = 0; f < 2; ++f) { - K::fused_gr_set_fast(f); - for (int i = 0; i < 20; ++i) K::fused_gr_read_multi(a, T, dxn, s); - cudaEventRecord(e0, s); - for (int i = 0; i < iters; ++i) K::fused_gr_read_multi(a, T, dxn, s); - cudaEventRecord(e1, s); - cudaEventSynchronize(e1); - float ms = 0; - cudaEventElapsedTime(&ms, e0, e1); - us[f] = std::fmin(us[f], 1e3 * ms / iters); - } - std::printf("T %d apply %d inject %d | old %6.1f us fast %6.1f us | %s\n", T, apply, inject, us[0], us[1], - same ? "bitwise equal" : "DIFFERS"); - if (!same) ++failures; - } - std::printf("fused_gr_bench: %d differing\n", failures); - return failures ? 1 : 0; -} diff --git a/src/kernels/gdn_parity.cpp b/src/kernels/gdn_parity.cpp deleted file mode 100644 index dc30b41..0000000 --- a/src/kernels/gdn_parity.cpp +++ /dev/null @@ -1,532 +0,0 @@ -// 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 -// asserted OBSERVABLE against a deliberately-wrong computation before the kernel is judged: -// -// 1. MODULO head pairing, h % h_k, not INTERLEAVE. With H_k=2 and H_v=4 the two give [0,1,0,1] and -// [0,0,1,1]: they differ at h=1 and h=2. Both produce a full-rank state of the right shape. -// 2. Decay applied BEFORE the rank-1 update. Applying it after is a one-line move that keeps every shape -// and every magnitude. -// 3. The conv's SLIDE DIRECTION. `kernel[0]` must read the OLDEST state row and the new input must land in -// the LAST state row; reversing either is invisible on a symmetric state, so the state rows here are -// labelled so each position is identifiable. -// 4. `l2_norm`'s `+ eps` is an absolute floor on the SQUARED NORM, not on the mean. The mean reading -// 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 - -#include -#include -#include -#include -#include -#include -#include - -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)); - std::exit(1); - } -} - -float sigmoid_f(float x) { return 1.0f / (1.0f + std::exp(-x)); } -float silu_f(float x) { return x / (1.0f + std::exp(-x)); } -float gate_act(GdnGate g, float x) { return g == GdnGate::Silu ? silu_f(x) : sigmoid_f(x); } -const char* gate_name(GdnGate g) { return strata::kernels::gdn_gate_name(g); } -GdnGate other(GdnGate g) { return g == GdnGate::Silu ? GdnGate::Sigmoid : GdnGate::Silu; } - -/// The reference's `gdn_step`, with switches for the rival readings. -/// -/// `state` is passed in the REFERENCE layout (S, S, h_v) - i.e. (i, j, h) - so that this function is a -/// transcription of `ref/gdn.py` and not of the kernel. `q` is taken AS GIVEN: the legacy kernel wants it -/// pre-scaled by 1/sqrt(S), the native and fused kernels scale the readout themselves, so the caller passes the -/// scaled q here and the unscaled q to those kernels. -void ref_step(std::vector& state, const std::vector& q, const std::vector& k, - const std::vector& v, const std::vector& gate, const std::vector& beta, - int S, int h_k, int h_v, std::vector& o, bool modulo_heads, bool decay_first) { - auto at = [&](int i, int j, int h) -> double& { return state[(size_t) (i * S + j) * h_v + h]; }; - std::vector oo((size_t) h_v * S, 0.0f); - for (int h = 0; h < h_v; ++h) { - const int src = modulo_heads ? (h % h_k) : (h / (h_v / h_k)); - const double dec = std::exp((double) gate[(size_t) h]); - const double b = (double) beta[(size_t) h]; - for (int j = 0; j < S; ++j) { - if (decay_first) for (int i = 0; i < S; ++i) at(i, j, h) *= dec; - double sk = 0; - for (int i = 0; i < S; ++i) sk += at(i, j, h) * (double) k[(size_t) (src * S + i)]; - const double d = ((double) v[(size_t) (h * S + j)] - sk) * b; - for (int i = 0; i < S; ++i) at(i, j, h) += (double) k[(size_t) (src * S + i)] * d; - if (!decay_first) for (int i = 0; i < S; ++i) at(i, j, h) *= dec; - double dot = 0; - for (int i = 0; i < S; ++i) dot += at(i, j, h) * (double) q[(size_t) (src * S + i)]; - oo[(size_t) (h * S + j)] = (float) dot; - } - } - 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& o, const std::vector& z, const std::vector& sn, int h_v, - int S, float eps, GdnGate act, std::vector& 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& cs, const std::vector& x, const std::vector& kern, int C, - int dc, std::vector& out) { - out.assign((size_t) C, 0.0f); - for (int c = 0; c < C; ++c) { - double acc = 0; - for (int i = 0; i < dc - 1; ++i) acc += (double) cs[(size_t) (i * C + c)] * (double) kern[(size_t) (i * C + c)]; - acc += (double) x[(size_t) c] * (double) kern[(size_t) ((dc - 1) * C + c)]; - out[(size_t) c] = (float) acc; - for (int i = 0; i < dc - 2; ++i) cs[(size_t) (i * C + c)] = cs[(size_t) ((i + 1) * C + c)]; - cs[(size_t) ((dc - 2) * C + c)] = x[(size_t) c]; - } -} - -double rel_l1(const std::vector& a, const std::vector& 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); -} - -/// The device state (S, h_v, S), j fastest, read back into the reference layout and compared. -double state_rel(const std::vector& want, const std::vector& 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 -T* dev(const std::vector& 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 -std::vector host(const T* d, size_t n, const char* what) { - std::vector 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 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 st_ref((size_t) S * S * h_v); - std::vector 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 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 q_scaled = q; // the legacy kernel's contract: q pre-scaled - for (auto& x : q_scaled) x *= rs; - - std::vector want_o; // o = (S q) / sqrt(S) - what every implementation emits - std::vector 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 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 a = st_ref; - std::vector 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 a = st_ref; - std::vector 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 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 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 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 vy = host(d_y, want_y.size(), "y"); - const std::vector 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 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 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 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) { - bool selftest = false; - for (int i = 1; i < argc; ++i) { - if (std::string(argv[i]) == "--selftest") selftest = true; - else { std::fprintf(stderr, "usage: gdn_parity [--selftest]\n"); return 2; } - } - - std::mt19937 rng(2024); - std::normal_distribution gauss(0.0f, 1.0f); - cudaStream_t stream = nullptr; - // A BLOCKING stream, deliberately: the fixtures are reset with pageable `cudaMemcpy`, which may return before the - // DMA lands, and a non-blocking stream does not order after the legacy stream - the first version of this test - // raced its own resets and reported the native kernels 7.5x off at one geometry and exact at the other. - check(cudaStreamCreate(&stream), "stream"); - - // ================= 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 ================= - { - const int C = 24, dc = 4; // small, so the host reference is a plain loop - // TWO DIFFERENT LAYOUTS MEET HERE, and this is where the first version of this test failed at 0.136. - // `ref/gdn.py` carries the conv state as (d_conv-1, C) ROW-MAJOR - (i, c) at i*C + c - because it is - // numpy. The kernel carries it as (C, d_conv-1) with c fastest - c*(dc-1) + i - because that is - // ggml's `ne = {d_conv-1, C}` with ne0 fast, and it is a runtime buffer so either is legal. The - // mapping between them is written out below rather than assumed, in both directions. - std::vector cs_ref((size_t) (dc - 1) * C), x((size_t) C), kern((size_t) dc * C); - for (int i = 0; i < dc - 1; ++i) - for (int c = 0; c < C; ++c) cs_ref[(size_t) (i * C + c)] = (float) (10 * (i + 1) + c); // labelled - for (int c = 0; c < C; ++c) x[(size_t) c] = (float) (100 + c); - for (size_t i = 0; i < kern.size(); ++i) kern[i] = gauss(rng); - - auto to_dev_layout = [&](const std::vector& r) { - std::vector d(r.size()); - for (int i = 0; i < dc - 1; ++i) - for (int c = 0; c < C; ++c) d[(size_t) (c * (dc - 1) + i)] = r[(size_t) (i * C + c)]; - return d; - }; - - std::vector cs = to_dev_layout(cs_ref); - std::vector want; - std::vector cs_want_ref = cs_ref; - ref_conv(cs_want_ref, x, kern, C, dc, want); - const std::vector cs_want = to_dev_layout(cs_want_ref); - - // THE LAYOUT: the manifest's `ssm_conv1d.weight` has ne = [d_conv, C], so ne0 = d_conv is fast. - // The kernel takes `kW[c*dc + i]`; the reference's `kern` is (dc, C) row-major. The transcription - // below is the ONLY place the two meet. - std::vector kW((size_t) C * dc); - for (int c = 0; c < C; ++c) - for (int i = 0; i < dc; ++i) kW[(size_t) (c * dc + i)] = kern[(size_t) (i * C + c)]; - // and the rival reading, which must differ or the fixture cannot see a transposed weight - std::vector kW_wrong((size_t) C * dc); - for (size_t i = 0; i < kern.size(); ++i) kW_wrong[i] = kern[i]; - { - // apply the WRONG layout by hand: tap i of channel c is kW[c*dc+i] read as kW[i*C+c] - std::vector cs2 = cs; - std::vector out_bad((size_t) C, 0.0f); - for (int c = 0; c < C; ++c) { - double a = 0; - for (int i = 0; i < dc - 1; ++i) a += (double) cs2[(size_t) (i * C + c)] * (double) kW_wrong[(size_t) (c * dc + i)]; - a += (double) x[(size_t) c] * (double) kW_wrong[(size_t) (c * dc + dc - 1)]; - out_bad[(size_t) c] = (float) a; - } - std::printf("\n== the conv\n"); - observable("conv weight layout is observable", rel_l1(want, out_bad)); - } - - 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"); - strata::kernels::gdn_conv_step(d_cs, d_x, d_w, d_o, C, dc, nullptr); - within("conv out vs reference", rel_l1(want, host(d_o, (size_t) C, "cgo")), 1e-6); - within("conv state slide (mapped) vs reference", rel_l1(cs_want, host(d_cs, cs.size(), "cgs")), 1e-6); - cudaFree(d_cs); cudaFree(d_x); cudaFree(d_w); cudaFree(d_o); - } - - // ================= 3. l2_norm ================= - { - const int rows = 16, cols = 128; - std::vector x((size_t) rows * cols), x_ref; - for (auto& val : x) val = gauss(rng) * 3.0f; - x_ref = x; - const float eps = 1e-6f; - for (int r = 0; r < rows; ++r) { - double acc = 0; - for (int i = 0; i < cols; ++i) acc += (double) x_ref[(size_t) (r * cols + i)] * (double) x_ref[(size_t) (r * cols + i)]; - const float inv = (float) (1.0 / std::sqrt(acc + (double) eps)); - for (int i = 0; i < cols; ++i) x_ref[(size_t) (r * cols + i)] *= inv; - } - // The rival reading puts THE SAME eps on the MEAN instead of on the squared norm, which at - // ||x||^2 ~ 1152 and cols = 128 changes the divisor from sqrt(1152) to sqrt(9) - a factor of 11.3, so - // the trap is large here. It would be a much smaller correction on a near-zero row, where the floor - // is the whole answer; that regime is not what this fixture exercises. - std::vector x_mean = x; - for (int r = 0; r < rows; ++r) { - double acc = 0; - for (int i = 0; i < cols; ++i) acc += (double) x_mean[(size_t) (r * cols + i)] * (double) x_mean[(size_t) (r * cols + i)]; - const float inv = (float) (1.0 / std::sqrt(acc / cols + (double) eps)); - for (int i = 0; i < cols; ++i) x_mean[(size_t) (r * cols + i)] *= inv; - } - std::printf("\n== l2_norm\n"); - observable("eps on sum vs on mean is observable", rel_l1(x_ref, x_mean)); - - float* d_x = dev(x, "lx"); - strata::kernels::gdn_l2_norm(d_x, rows, cols, eps, nullptr); - within("l2_norm vs reference", rel_l1(x_ref, host(d_x, x.size(), "lcg")), 1e-6); - cudaFree(d_x); - } - - // ================= 4. the closing norm on its own, both gates through both single-purpose kernels ================= - { - const int S2 = 128, hv2 = 8; - std::vector 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; - std::vector 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& want = gt == GdnGate::Silu ? y_silu : y_sig; - const std::vector& 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 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); - } - 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; -} diff --git a/src/kernels/gr_parity.cpp b/src/kernels/gr_parity.cpp deleted file mode 100644 index b5ceb76..0000000 --- a/src/kernels/gr_parity.cpp +++ /dev/null @@ -1,770 +0,0 @@ -// src/kernels/gr_parity.cpp - P2.S2's test for the gated residual / hyper-connection. -// -// `ref/gr.py` opens by listing the details "a prose reading gets wrong", and every one of them is a reading -// that has the RIGHT SHAPES and produces a PLAUSIBLE number. So each is computed here the wrong way round and -// required to differ materially BEFORE the kernel is judged against the right one. A test that only does the -// second half passes against either reading: -// -// 1. PER-STREAM RMSNorm. The source comment reads ambiguously; the code reduces over ne[0] = n_embd, i.e. -// one RMS per stream. The rival reading is one RMS over the whole hc*n_embd stack. -// 2. `/ hc` INSIDE the silu: `lo = silu(proj / hc)`. Moving it outside is a one-line change that keeps -// every shape. -// 3. SiLU on `lo` and SIGMOID on the gate, a few lines apart in the same function. Swapping them is the -// obvious slip, and both are monotone saturating functions so the magnitudes stay comparable. -// 4. `mean` over the stream axis, not `sum`. A factor of hc = 4, which is exactly the kind of error that -// looks like a scale problem rather than a structural one. -// 5. ACTIVATION PRECISION. The historical BF16-rounded CPU contract and the pinned CUDA single-token -// FP32-activation contract must be distinguishable. Both are tested against explicit references; -// neither is selected merely because the weight is BF16. The scalar fixture isolates xn and lo -// rounding from reduction order, and graph replay must preserve the precision chosen at capture. -// 6. `gr_write`'s `2*sigmoid`, which centres the gate on 1 so a ZERO injection is a plain residual add. -// Asserted as a property, not as a value, because that is what the source comment claims. -#include "strata/kernels/gr.hpp" -#include "strata/kernels/fused_gr.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { - -void check(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -/// The same rule the kernel uses, on the host - `ref/quant.py::bf16`. -float to_bf16(float f) { - uint32_t i; - std::memcpy(&i, &f, 4); - i = (i + ((i >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u; - float o; - std::memcpy(&o, &i, 4); - return o; -} - -uint16_t bf16_bits(float f) { - uint32_t i; - std::memcpy(&i, &f, 4); - return (uint16_t) (i >> 16); -} - -struct Opts { - bool per_stream_norm = true; ///< false: one RMS over the whole stack (WRONG) - bool scale_inside_silu = true; ///< false: silu(proj)/hc instead of silu(proj/hc) (WRONG) - bool sigmoid_on_gate = true; ///< false: silu on the gate and sigmoid on lo (WRONG) - bool mean_over_streams = true; ///< false: sum over streams instead of mean (WRONG) - bool round_activation = true; ///< false: pinned CUDA single-token BF16 MMVF contract -}; - -/// `ref/gr.py::gr_read`, transcribed with switches for the rival readings. -void reference(const std::vector& R, const std::vector& w_norm, - const std::vector& w_down, const std::vector& w_up, - const std::vector& w_inject, float eps, long long n_embd, long long hc, long long hc_lr, - const Opts& o, std::vector& mixed, std::vector& inject) { - const long long hc_dim = hc * n_embd; - std::vector xn((size_t) hc_dim); - if (o.per_stream_norm) { - for (long long c = 0; c < hc; ++c) { - double ms = 0; - for (long long d = 0; d < n_embd; ++d) ms += (double) R[(size_t) (c * n_embd + d)] * R[(size_t) (c * n_embd + d)]; - ms /= (double) n_embd; - const float rs = (float) (1.0 / std::sqrt(ms + (double) eps)); - for (long long d = 0; d < n_embd; ++d) { - const size_t i = (size_t) (c * n_embd + d); - xn[i] = R[i] * rs * w_norm[i]; - } - } - } else { - double ms = 0; - for (long long i = 0; i < hc_dim; ++i) ms += (double) R[(size_t) i] * R[(size_t) i]; - ms /= (double) hc_dim; - const float rs = (float) (1.0 / std::sqrt(ms + (double) eps)); - for (long long i = 0; i < hc_dim; ++i) xn[(size_t) i] = R[(size_t) i] * rs * w_norm[(size_t) i]; - } - - std::vector act((size_t) hc_dim); - for (long long i = 0; i < hc_dim; ++i) act[(size_t) i] = o.round_activation ? to_bf16(xn[(size_t) i]) : xn[(size_t) i]; - - // lo - std::vector lo((size_t) hc_lr); - for (long long k = 0; k < hc_lr; ++k) { - double a = 0; - for (long long i = 0; i < hc_dim; ++i) a += (double) act[(size_t) i] * (double) w_down[(size_t) (k * hc_dim + i)]; - const float p = (float) a; - if (o.sigmoid_on_gate) lo[(size_t) k] = o.scale_inside_silu ? (p / (float) hc) / (1.0f + std::exp(-(p / (float) hc))) - : (p / (1.0f + std::exp(-p))) / (float) hc; - else lo[(size_t) k] = o.scale_inside_silu ? 1.0f / (1.0f + std::exp(-(p / (float) hc))) - : (1.0f / (1.0f + std::exp(-p))) / (float) hc; - } - std::vector lq((size_t) hc_lr); - for (long long k = 0; k < hc_lr; ++k) - lq[(size_t) k] = o.round_activation ? to_bf16(lo[(size_t) k]) : lo[(size_t) k]; - - // gate and the gated mean - mixed.assign((size_t) n_embd, 0.0f); - for (long long d = 0; d < n_embd; ++d) { - float m = 0.0f; - for (long long c = 0; c < hc; ++c) { - const long long i = c * n_embd + d; - double a = 0; - for (long long k = 0; k < hc_lr; ++k) a += (double) lq[(size_t) k] * (double) w_up[(size_t) (i * hc_lr + k)]; - const float g = (float) a; - const float s = o.sigmoid_on_gate ? 1.0f / (1.0f + std::exp(-g)) : g / (1.0f + std::exp(-g)); - m += xn[(size_t) i] * s; - } - mixed[(size_t) d] = o.mean_over_streams ? m / (float) hc : m; - } - - inject.assign((size_t) hc, 0.0f); - for (long long c = 0; c < hc; ++c) { - double a = 0; - for (long long i = 0; i < hc_dim; ++i) a += (double) act[(size_t) i] * (double) w_inject[(size_t) (c * hc_dim + i)]; - inject[(size_t) c] = (float) a; - } -} - -/// Normalised L1 difference. `mag_out` returns the mean |a|, for reporting. -double rel_diff(const std::vector& a, const std::vector& b, double* mag_out = nullptr) { - double d = 0, mag = 0; - for (size_t i = 0; i < a.size(); ++i) { - d += std::fabs((double) a[i] - (double) b[i]); - mag += std::fabs((double) a[i]); - } - if (mag_out) *mag_out = mag / (double) (a.empty() ? 1 : a.size()); - return d / (mag > 1e-30 ? mag : 1e-30); -} - -/// Relative error against the magnitude of the TERMS, not of the result. -/// -/// `R + block_out * w` cancels wherever block_out*w is close to -R, and a plain |want-got|/|want| then -/// reports the CONDITION NUMBER instead of the arithmetic. This is the same metric mistake the project has -/// now made four times: rounds 169 (Q4_K), 189 (RoPE), 194 (shared_expert) and this one. For a sum, the -/// denominator is the sum of the term magnitudes. -double rel_terms(double want, double got, double term_a, double term_b) { - const double den = std::fabs(term_a) + std::fabs(term_b); - return std::fabs(want - got) / (den > 1e-30 ? den : 1e-30); -} - -const char* activation_mode_name(int mode) { - return mode == 2 ? "native pinned GR" : (mode == 1 ? "FP32" : "BF16"); -} -void select_activation_mode(int mode) { - strata::kernels::gr_set_native_mmvf(mode == 2); - // In mode 2 the precision-only switch is deliberately false: native MMVF must imply FP32 by itself. - strata::kernels::gr_set_fp32_activations(mode == 1); -} - -// A diagonal GR fixture makes activation precision observable without summation-order ambiguity. -// Two-wide matrices satisfy native MMVF's pair ABI, while each nonzero dot has only one nonzero product. -// At R=1 and eps=0, xn=gamma exactly; any rounding in xn or lo comes from the selected activation contract. -int scalar_activation_contract() { - using namespace strata::kernels; - const GrShapes sh{2, 1, 2}; - float *d_R = nullptr, *d_norm = nullptr, *d_mixed = nullptr, *d_inject = nullptr; - uint16_t* d_weights = nullptr; - void* d_scratch = nullptr; - check(cudaMalloc(&d_R, 2 * sizeof(float)), "scalar R"); - check(cudaMalloc(&d_norm, 2 * sizeof(float)), "scalar norm"); - check(cudaMalloc(&d_mixed, 2 * sizeof(float)), "scalar mixed"); - check(cudaMalloc(&d_inject, sizeof(float)), "scalar inject"); - check(cudaMalloc(&d_weights, 10 * sizeof(uint16_t)), "scalar weights"); - check(cudaMalloc(&d_scratch, gr_workspace_bytes(sh)), "scalar scratch"); - GrWorkspace ws; - gr_workspace_init(sh, d_scratch, ws); - const float ones[] = {1.0f, 1.0f}; - const uint16_t weights[] = { - bf16_bits(0.5f), 0, 0, 0, // down: lo[0]=silu(xn[0]/2), lo[1]=0 - bf16_bits(1.5f), 0, bf16_bits(1.5f), 0, // both gate rows consume lo[0] - bf16_bits(2.0f), 0 // injection: 2*xn[0] - }; - check(cudaMemcpy(d_R, ones, sizeof(ones), cudaMemcpyHostToDevice), "scalar upload R"); - check(cudaMemcpy(d_weights, weights, sizeof(weights), cudaMemcpyHostToDevice), "scalar upload weights"); - cudaStream_t stream; - check(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), "scalar stream"); - int bad = 0; - for (float gamma : {1.0f, 1.00390625f}) { - const float gammas[] = {gamma, gamma}; - check(cudaMemcpy(d_norm, gammas, sizeof(gammas), cudaMemcpyHostToDevice), "scalar upload norm"); - float mixed_by_mode[3][2] = {}, inject_by_mode[3] = {}; - for (int mode = 0; mode < 3; ++mode) { - select_activation_mode(mode); - gr_read(d_R, d_norm, d_weights, d_weights + 4, d_weights + 8, 0.0f, - sh, ws, d_mixed, d_inject, stream); - check(cudaStreamSynchronize(stream), "scalar warmup"); - cudaGraph_t graph; - cudaGraphExec_t executable; - check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "scalar capture begin"); - gr_read(d_R, d_norm, d_weights, d_weights + 4, d_weights + 8, 0.0f, - sh, ws, d_mixed, d_inject, stream); - check(cudaStreamEndCapture(stream, &graph), "scalar capture end"); - check(cudaGraphInstantiate(&executable, graph, nullptr, nullptr, 0), "scalar instantiate"); - // Changing both host options after capture cannot change the graph's selected kernels. - select_activation_mode((mode + 1) % 3); - // Warmup results must not make a missing/no-op captured launch pass. - // Poison the outputs and intermediate workspace before replay. - check(cudaMemsetAsync(d_mixed, 0xa5, 2 * sizeof(float), stream), "scalar poison mixed"); - check(cudaMemsetAsync(d_inject, 0xa5, sizeof(float), stream), "scalar poison inject"); - check(cudaMemsetAsync(d_scratch, 0xa5, ws.bytes, stream), "scalar poison workspace"); - check(cudaGraphLaunch(executable, stream), "scalar replay"); - check(cudaStreamSynchronize(stream), "scalar replay sync"); - check(cudaMemcpy(mixed_by_mode[mode], d_mixed, 2 * sizeof(float), cudaMemcpyDeviceToHost), "scalar mixed copy"); - check(cudaMemcpy(&inject_by_mode[mode], d_inject, sizeof(float), cudaMemcpyDeviceToHost), "scalar inject copy"); - const float activation = mode ? gamma : to_bf16(gamma); - const float projection = activation * 0.5f; - const float lo = projection / (1.0f + std::exp(-projection)); - const float gate = (mode ? lo : to_bf16(lo)) * 1.5f; - const float expected_mixed = gamma / (1.0f + std::exp(-gate)); - const float expected_inject = activation * 2.0f; - // Each mode has its own activation contract and bounded scalar-formula - // check. Native fast exp/div need not match ordinary FP32 postops bit - // for bit: native_gr_postops_parity establishes that arithmetic with - // actual pinned CUDA graphs. The nonzero projection/injection here - // has only one exactly representable product and remains exact. - const bool ok = std::fabs(mixed_by_mode[mode][0] - expected_mixed) <= 2e-7f && - mixed_by_mode[mode][0] == mixed_by_mode[mode][1] && - inject_by_mode[mode] == expected_inject; - std::printf(" scalar gamma %.8f %s activation/capture %s (mixed %.9f, ref %.9f)\n", - gamma, activation_mode_name(mode), ok ? "pass" : "FAIL", - mixed_by_mode[mode][0], expected_mixed); - if (!ok) ++bad; - check(cudaGraphExecDestroy(executable), "scalar graph exec destroy"); - check(cudaGraphDestroy(graph), "scalar graph destroy"); - - const float sentinel = -73.25f; - check(cudaMemcpy(d_inject, &sentinel, sizeof(float), cudaMemcpyHostToDevice), "scalar sentinel"); - select_activation_mode(mode); - gr_read(d_R, d_norm, d_weights, d_weights + 4, nullptr, 0.0f, - sh, ws, d_mixed, d_inject, stream); - check(cudaStreamSynchronize(stream), "scalar final mixer sync"); - float final_mixed[2] = {}, untouched = 0.0f; - check(cudaMemcpy(final_mixed, d_mixed, sizeof(final_mixed), cudaMemcpyDeviceToHost), "scalar final mixed"); - check(cudaMemcpy(&untouched, d_inject, sizeof(float), cudaMemcpyDeviceToHost), "scalar sentinel copy"); - const bool final_ok = std::memcmp(final_mixed, mixed_by_mode[mode], sizeof(final_mixed)) == 0 && untouched == sentinel; - std::printf(" scalar final mixer %s %s\n", activation_mode_name(mode), final_ok ? "pass" : "FAIL"); - if (!final_ok) ++bad; - } - if (std::fabs(mixed_by_mode[1][0] - mixed_by_mode[0][0]) <= 1e-5f || - (gamma != 1.0f && inject_by_mode[0] == inject_by_mode[1])) { - std::printf(" scalar precision fixture is not observable\n"); - ++bad; - } - if (inject_by_mode[1] != inject_by_mode[2]) { - std::printf(" native MMVF changed the exact scalar FP32 injection projection\n"); - ++bad; - } - } - select_activation_mode(0); - check(cudaStreamDestroy(stream), "scalar stream destroy"); - cudaFree(d_R); cudaFree(d_norm); cudaFree(d_mixed); cudaFree(d_inject); - cudaFree(d_weights); cudaFree(d_scratch); - return bad; -} - -int fused_multi_lds_parity(const float* d_norm, const uint16_t* d_down, const uint16_t* d_up, - const uint16_t* d_inject, float eps) { - using namespace strata::kernels; - constexpr int N = 2560, HC = 4, LR = 320, D = N * HC, T = kFusedGrMaxT; - std::mt19937 rng(0x6f8a); - std::normal_distribution normal(0.0f, 0.3f); - std::vector r((size_t) T * D), bo((size_t) T * N), inj((size_t) T * HC); - for (auto& x : r) x = normal(rng); - for (auto& x : bo) x = normal(rng); - for (auto& x : inj) x = normal(rng); - - float *d_r = nullptr, *d_r_out = nullptr, *d_bo = nullptr, *d_inj = nullptr; - float *d_lo = nullptr, *d_rs = nullptr, *d_inj_out = nullptr, *d_mixed = nullptr, *d_xn = nullptr; - check(cudaMalloc(&d_r, r.size() * sizeof(float)), "multi R"); - check(cudaMalloc(&d_r_out, r.size() * sizeof(float)), "multi R_out"); - check(cudaMalloc(&d_bo, bo.size() * sizeof(float)), "multi bo"); - check(cudaMalloc(&d_inj, inj.size() * sizeof(float)), "multi inj"); - check(cudaMalloc(&d_lo, (size_t) T * LR * sizeof(float)), "multi lo"); - check(cudaMalloc(&d_rs, (size_t) T * HC * sizeof(float)), "multi rs"); - check(cudaMalloc(&d_inj_out, (size_t) T * HC * sizeof(float)), "multi injection"); - check(cudaMalloc(&d_mixed, (size_t) T * N * sizeof(float)), "multi mixed"); - check(cudaMalloc(&d_xn, (size_t) T * D * sizeof(float)), "multi xn"); - check(cudaMemcpy(d_r, r.data(), r.size() * sizeof(float), cudaMemcpyHostToDevice), "multi copy R"); - check(cudaMemcpy(d_bo, bo.data(), bo.size() * sizeof(float), cudaMemcpyHostToDevice), "multi copy bo"); - check(cudaMemcpy(d_inj, inj.data(), inj.size() * sizeof(float), cudaMemcpyHostToDevice), "multi copy inj"); - - std::vector args(T); - for (int t = 0; t < T; ++t) { - auto& a = args[t]; - a.R = d_r + (size_t) t * D; - a.R_out = d_r_out + (size_t) t * D; - a.apply = true; - a.bo_prev = d_bo + (size_t) t * N; - a.inj_prev = d_inj + (size_t) t * HC; - a.w_norm = d_norm; - a.w_down = d_down; - a.w_up = d_up; - a.w_inject = d_inject; - a.eps = eps; - a.lo = d_lo + (size_t) t * LR; - a.rs = d_rs + (size_t) t * HC; - a.inject_out = d_inj_out + (size_t) t * HC; - a.mixed = d_mixed + (size_t) t * N; - } - - struct Snapshot { - std::vector r_out, lo, rs, inject, mixed; - }; - auto snapshot = [&]() { - Snapshot s; - s.r_out.resize((size_t) T * D); - s.lo.resize((size_t) T * LR); - s.rs.resize((size_t) T * HC); - s.inject.resize((size_t) T * HC); - s.mixed.resize((size_t) T * N); - check(cudaMemcpy(s.r_out.data(), d_r_out, s.r_out.size() * sizeof(float), cudaMemcpyDeviceToHost), "multi read R_out"); - check(cudaMemcpy(s.lo.data(), d_lo, s.lo.size() * sizeof(float), cudaMemcpyDeviceToHost), "multi read lo"); - check(cudaMemcpy(s.rs.data(), d_rs, s.rs.size() * sizeof(float), cudaMemcpyDeviceToHost), "multi read rs"); - check(cudaMemcpy(s.inject.data(), d_inj_out, s.inject.size() * sizeof(float), cudaMemcpyDeviceToHost), "multi read inject"); - check(cudaMemcpy(s.mixed.data(), d_mixed, s.mixed.size() * sizeof(float), cudaMemcpyDeviceToHost), "multi read mixed"); - return s; - }; - // the split read (STRATA_GR_V3=1) sums in another order than the single-token kernel: equal within float - // rounding, not to the bit, so it is compared with a relative tolerance; the default kernels bit for bit - static const bool v3 = [] { const char* v = std::getenv("STRATA_GR_V3"); return v != nullptr && std::atoi(v) != 0; }(); - auto close = [](const std::vector& x, const std::vector& y) { - double worst = 0.0, mag = 1e-30; - for (size_t i = 0; i < x.size(); ++i) { - worst = std::max(worst, (double) std::fabs(x[i] - y[i])); - mag = std::max(mag, (double) std::fabs(y[i])); - } - if (worst > 2e-6 * mag) - std::printf(" tolerance: worst %.3e of max |ref| %.3e (rel %.3e), n %zu\n", worst, mag, worst / mag, x.size()); - return worst <= 2e-6 * mag; - }; - auto same = [&](const Snapshot& a, const Snapshot& b) { - if (v3) // `lo` is the default kernels' workspace between down and up; the split read keeps it in shared memory - return close(a.r_out, b.r_out) && close(a.rs, b.rs) && close(a.inject, b.inject) && close(a.mixed, b.mixed); - return std::memcmp(a.r_out.data(), b.r_out.data(), a.r_out.size() * sizeof(float)) == 0 && - std::memcmp(a.lo.data(), b.lo.data(), a.lo.size() * sizeof(float)) == 0 && - std::memcmp(a.rs.data(), b.rs.data(), a.rs.size() * sizeof(float)) == 0 && - std::memcmp(a.inject.data(), b.inject.data(), a.inject.size() * sizeof(float)) == 0 && - std::memcmp(a.mixed.data(), b.mixed.data(), a.mixed.size() * sizeof(float)) == 0; - }; - - cudaStream_t stream = nullptr; - check(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), "multi stream"); - // Max T forces the HIP kernel's full dynamic-LDS request: 8 * 1280 * sizeof(float) = 40 KiB. - fused_gr_read_multi(args.data(), T, d_xn, stream); - check(cudaStreamSynchronize(stream), "multi max-T sync"); - const Snapshot multi = snapshot(); - for (int t = 0; t < T; ++t) fused_gr_read(args[t], stream); - check(cudaStreamSynchronize(stream), "single reference sync"); - const Snapshot single = snapshot(); - int bad = 0; - if (!same(multi, single)) { - std::printf(" fused GR multi max-T differs from single-token calls\n"); - ++bad; - } - - cudaGraph_t graph = nullptr; - cudaGraphExec_t graph_exec = nullptr; - check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "multi graph begin"); - fused_gr_read_multi(args.data(), T, d_xn, stream); - check(cudaStreamEndCapture(stream, &graph), "multi graph end"); - check(cudaGraphInstantiate(&graph_exec, graph, nullptr, nullptr, 0), "multi graph instantiate"); - check(cudaGraphLaunch(graph_exec, stream), "multi graph initial replay"); - check(cudaStreamSynchronize(stream), "multi graph initial sync"); - const Snapshot captured = snapshot(); - if (!same(multi, captured)) { - std::printf(" fused GR multi captured graph differs from direct max-T call\n"); - ++bad; - } - - // Reuse the same captured pointers with new payloads; then independently run the single-token path again. - for (size_t i = 0; i < r.size(); ++i) r[i] = -0.7f * r[i] + 0.001f * (float) (i % 17); - for (size_t i = 0; i < bo.size(); ++i) bo[i] = -0.4f * bo[i] + 0.02f; - for (size_t i = 0; i < inj.size(); ++i) inj[i] += 0.3f; - check(cudaMemcpyAsync(d_r, r.data(), r.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "multi replay R"); - check(cudaMemcpyAsync(d_bo, bo.data(), bo.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "multi replay bo"); - check(cudaMemcpyAsync(d_inj, inj.data(), inj.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "multi replay inj"); - check(cudaGraphLaunch(graph_exec, stream), "multi graph changed replay"); - check(cudaStreamSynchronize(stream), "multi graph changed sync"); - const Snapshot replay = snapshot(); - if (std::memcmp(multi.mixed.data(), replay.mixed.data(), multi.mixed.size() * sizeof(float)) == 0) { - std::printf(" fused GR graph replay ignored changed inputs\n"); - ++bad; - } - for (int t = 0; t < T; ++t) fused_gr_read(args[t], stream); - check(cudaStreamSynchronize(stream), "changed single reference sync"); - if (!same(replay, snapshot())) { - std::printf(" fused GR changed graph replay differs from single-token calls\n"); - ++bad; - } - - std::printf(" fused GR multi max-T=8 LDS launch and changing graph replay %s\n", - bad == 0 ? "pass" : "FAIL"); - check(cudaGraphExecDestroy(graph_exec), "multi graph exec destroy"); - check(cudaGraphDestroy(graph), "multi graph destroy"); - check(cudaStreamDestroy(stream), "multi stream destroy"); - check(cudaFree(d_xn), "free multi xn"); - check(cudaFree(d_mixed), "free multi mixed"); - check(cudaFree(d_inj_out), "free multi injection"); - check(cudaFree(d_rs), "free multi rs"); - check(cudaFree(d_lo), "free multi lo"); - check(cudaFree(d_inj), "free multi inj"); - check(cudaFree(d_bo), "free multi bo"); - check(cudaFree(d_r_out), "free multi R_out"); - check(cudaFree(d_r), "free multi R"); - return bad; -} - -} // namespace - -int main(int argc, char** argv) { - bool selftest = false; - for (int i = 1; i < argc; ++i) { - if (std::string(argv[i]) == "--selftest") selftest = true; - else { std::fprintf(stderr, "usage: gr_parity [--selftest]\n"); return 2; } - } - - const long long n_embd = 256, hc = 4, hc_lr = 32; - const long long hc_dim = hc * n_embd; - const float eps = 1e-6f; - std::mt19937 rng(1234); - std::normal_distribution gauss(0.0f, 1.0f); - - // Weights are BF16-VALUED f32, which is what the pack holds for a BF16 source type. Generating plain f32 - // weights would make the kernel (which stores 16 bits) differ from the reference by the rounding itself, - // and the test would then be measuring the fixture. - auto bf16_weight = [&](size_t n, float sigma) { - std::vector v(n); - for (auto& x : v) x = to_bf16(gauss(rng) * sigma); - return v; - }; - std::vector R((size_t) hc_dim); - for (auto& x : R) x = gauss(rng); - // STREAM SCALES 1, 4, 16, 64. Without them trap 1 is only ~5% observable, because four streams of i.i.d. - // normal noise have nearly the same RMS by accident - so a whole-stack RMS and a per-stream RMS agree to - // within the noise, and the fixture would be asserting a distinction it cannot see. Giving the streams - // different magnitudes is what makes "per-stream" a claim with content. - for (long long c = 0; c < hc; ++c) - for (long long d = 0; d < n_embd; ++d) R[(size_t) (c * n_embd + d)] *= std::pow(4.0f, (float) c); - // gamma stored as (1 + w), so values near 1 - a reader expecting a plain scale is the one this catches - std::vector w_norm((size_t) hc_dim); - for (auto& x : w_norm) x = 1.0f + 0.1f * gauss(rng); - std::vector w_down = bf16_weight((size_t) (hc_lr * hc_dim), 0.2f); - std::vector w_up = bf16_weight((size_t) (hc_dim * hc_lr), 0.2f); - std::vector w_inject = bf16_weight((size_t) (hc * hc_dim), 0.05f); - - // NO PERMUTATION: the kernel takes both matrices exactly as the manifest (and `ref/gr.py`) store them. - // `w_down` is (hc_lr, hc_dim) row-major and `w_up` is (hc_dim, hc_lr) row-major, so the bit-copy below is - // the whole conversion. An earlier version of this kernel wanted both TRANSPOSED - the test built them - // that way and asserted the orientation observable - and that is gone because the warp-per-row mapping - // makes it unnecessary. What replaces it is the general orientation trap further down: a weight array - // read with the wrong index expression must still produce a visibly different answer. - std::vector q_down(w_down.size()), q_up(w_up.size()), q_inject(w_inject.size()); - for (size_t i = 0; i < w_down.size(); ++i) q_down[i] = bf16_bits(w_down[i]); - for (size_t i = 0; i < w_up.size(); ++i) q_up[i] = bf16_bits(w_up[i]); - for (size_t i = 0; i < w_inject.size(); ++i) q_inject[i] = bf16_bits(w_inject[i]); - - // ---- device side - float *d_R = nullptr, *d_norm = nullptr, *d_mixed = nullptr, *d_inject = nullptr; - uint16_t *d_down = nullptr, *d_up = nullptr, *d_inj = nullptr; - check(cudaMalloc(&d_R, R.size() * sizeof(float)), "m R"); - check(cudaMalloc(&d_norm, w_norm.size() * sizeof(float)), "m norm"); - check(cudaMalloc(&d_down, q_down.size() * sizeof(uint16_t)), "m down"); - check(cudaMalloc(&d_up, q_up.size() * sizeof(uint16_t)), "m up"); - check(cudaMalloc(&d_inj, q_inject.size() * sizeof(uint16_t)), "m inj"); - check(cudaMalloc(&d_mixed, (size_t) n_embd * sizeof(float)), "m mixed"); - check(cudaMalloc(&d_inject, (size_t) hc * sizeof(float)), "m inject"); - check(cudaMemcpy(d_R, R.data(), R.size() * sizeof(float), cudaMemcpyHostToDevice), "c R"); - check(cudaMemcpy(d_norm, w_norm.data(), w_norm.size() * sizeof(float), cudaMemcpyHostToDevice), "c norm"); - check(cudaMemcpy(d_down, q_down.data(), q_down.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "c down"); - check(cudaMemcpy(d_up, q_up.data(), q_up.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "c up"); - check(cudaMemcpy(d_inj, q_inject.data(), q_inject.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "c inj"); - - const strata::kernels::GrShapes sh{n_embd, hc, hc_lr}; - // DEVICE memory: the workspace is written by the kernel. - void* d_ws_raw = nullptr; - check(cudaMalloc(&d_ws_raw, strata::kernels::gr_workspace_bytes(sh)), "m ws"); - strata::kernels::GrWorkspace ws; - strata::kernels::gr_workspace_init(sh, d_ws_raw, ws); - strata::kernels::gr_read(d_R, d_norm, d_down, d_up, d_inj, eps, sh, ws, d_mixed, d_inject, nullptr); - std::vector got_mixed((size_t) n_embd), got_inject((size_t) hc); - check(cudaMemcpy(got_mixed.data(), d_mixed, got_mixed.size() * sizeof(float), cudaMemcpyDeviceToHost), "c mixed"); - check(cudaMemcpy(got_inject.data(), d_inject, got_inject.size() * sizeof(float), cudaMemcpyDeviceToHost), "c inject"); - - int bad = 0; - - // ---- the traps, asserted OBSERVABLE before the kernel is judged against the right reading - Opts right; - std::vector want_mixed, want_inject; - reference(R, w_norm, w_down, w_up, w_inject, eps, n_embd, hc, hc_lr, right, want_mixed, want_inject); - - struct Trap { const char* name; Opts o; double floor; }; - const Trap traps[] = { - {"per-stream RMSNorm vs whole-stack", {false, true, true, true, true}, 0.05}, - {"/hc inside the silu vs outside", {true, false, true, true, true}, 0.05}, - {"SiLU on lo / sigmoid on gate, swapped", {true, true, false, true, true}, 0.05}, - {"mean over streams vs sum", {true, true, true, false, true}, 0.50}, - {"BF16 vs FP32 activation contracts", {true, true, true, true, false}, 1e-4}, - }; - for (const Trap& t : traps) { - std::vector m, i; - reference(R, w_norm, w_down, w_up, w_inject, eps, n_embd, hc, hc_lr, t.o, m, i); - const double rel = rel_diff(want_mixed, m); - const bool observable = rel > t.floor; - std::printf(" %-40s %-4s (%.4f%% apart, floor %.3f%%)\n", t.name, observable ? "yes" : "*** NO ***", - rel * 100, t.floor * 100); - if (!observable) { - std::printf(" *** the fixture cannot see this trap, so passing proves nothing about it ***\n"); - ++bad; - } - } - - // ---- the kernel against the correct reference - double mag = 0; - const double rel_mixed = rel_diff(want_mixed, got_mixed, &mag); - std::printf("\n %-40s worst %.3e (mean |ref| %.4f)\n", "mixed vs reference", rel_mixed, mag); - - // The tolerance is set by SUMMATION ORDER, not by the structure: both sides round the activation to bf16 - // and both weights are bf16-valued, so every product is exact in f32 and only the order differs. A - // structural error is several orders of magnitude larger - the trap floors above say so. - if (!(rel_mixed <= 1e-4)) { - std::printf(" *** over 1e-4, which summation order does not explain - look for a structural bug ***\n"); - ++bad; - } - - const double rel_inject = rel_diff(want_inject, got_inject); - std::printf(" %-40s rel %.3e\n", "inject vs reference", rel_inject); - if (!(rel_inject <= 1e-4)) { - // Say WHICH elements and by how much: a whole-array L1 hides whether this is one stream wrong (an - // indexing bug) or all of them slightly wrong (a precision bug), and those need different responses. - std::printf(" want:"); - for (long long c = 0; c < hc; ++c) std::printf(" %12.6f", (double) want_inject[(size_t) c]); - std::printf("\n got :"); - for (long long c = 0; c < hc; ++c) std::printf(" %12.6f", (double) got_inject[(size_t) c]); - std::printf("\n"); - ++bad; - } - - // Same geometry and weights with the CUDA single-token activation contract. The scalar fixture - // below is the independent precision check; this case exercises multi-stream reductions and indexing. - { - Opts fp32; - fp32.round_activation = false; - std::vector wm, wi, gm((size_t) n_embd), gi((size_t) hc); - reference(R, w_norm, w_down, w_up, w_inject, eps, n_embd, hc, hc_lr, fp32, wm, wi); - strata::kernels::gr_set_fp32_activations(true); - strata::kernels::gr_read(d_R, d_norm, d_down, d_up, d_inj, eps, sh, ws, d_mixed, d_inject, nullptr); - check(cudaMemcpy(gm.data(), d_mixed, gm.size() * sizeof(float), cudaMemcpyDeviceToHost), "FP32 mixed"); - check(cudaMemcpy(gi.data(), d_inject, gi.size() * sizeof(float), cudaMemcpyDeviceToHost), "FP32 inject"); - strata::kernels::gr_set_fp32_activations(false); - const double rm = rel_diff(wm, gm), ri = rel_diff(wi, gi); - const bool ok = rm <= 1e-4 && ri <= 1e-4; - std::printf(" FP32 activations vs reference: %s (mixed %.3e, inject %.3e)\n", - ok ? "pass" : "FAIL", rm, ri); - if (!ok) ++bad; - strata::kernels::gr_read(d_R, d_norm, d_down, d_up, d_inj, eps, sh, ws, d_mixed, d_inject, nullptr); - check(cudaMemcpy(gm.data(), d_mixed, gm.size() * sizeof(float), cudaMemcpyDeviceToHost), "restored mixed"); - check(cudaMemcpy(gi.data(), d_inject, gi.size() * sizeof(float), cudaMemcpyDeviceToHost), "restored inject"); - const bool restored = std::memcmp(gm.data(), got_mixed.data(), gm.size() * sizeof(float)) == 0 && - std::memcmp(gi.data(), got_inject.data(), gi.size() * sizeof(float)) == 0; - std::printf(" restoring default activation contract: %s\n", restored ? "byte-identical" : "FAIL"); - if (!restored) ++bad; - } - - // ---- THE WEIGHT ORIENTATION MUST BE OBSERVABLE. The kernel now takes both matrices exactly as the - // manifest stores them, so there is no permutation for a loader to forget - but the INDEX EXPRESSIONS - // inside the kernel are still a place to be wrong, and a wrong one gives right-shaped, wrong-valued - // output. Feed transposed copies through the same code path and require the answer to differ. - { - uint16_t *d_down_bad = nullptr, *d_up_bad = nullptr; - check(cudaMalloc(&d_down_bad, q_down.size() * sizeof(uint16_t)), "m down_bad"); - check(cudaMalloc(&d_up_bad, q_up.size() * sizeof(uint16_t)), "m up_bad"); - std::vector tr_down(q_down.size()), tr_up(q_up.size()); - for (long long k = 0; k < hc_lr; ++k) - for (long long i = 0; i < hc_dim; ++i) - tr_down[(size_t) (i * hc_lr + k)] = q_down[(size_t) (k * hc_dim + i)]; - for (long long i = 0; i < hc_dim; ++i) - for (long long k = 0; k < hc_lr; ++k) - tr_up[(size_t) (k * hc_dim + i)] = q_up[(size_t) (i * hc_lr + k)]; - check(cudaMemcpy(d_down_bad, tr_down.data(), tr_down.size() * 2, cudaMemcpyHostToDevice), "cb d"); - check(cudaMemcpy(d_up_bad, tr_up.data(), tr_up.size() * 2, cudaMemcpyHostToDevice), "cb u"); - std::vector bad_mixed((size_t) n_embd); - float* d_bad = nullptr; - check(cudaMalloc(&d_bad, bad_mixed.size() * sizeof(float)), "m bad"); - strata::kernels::gr_read(d_R, d_norm, d_down_bad, d_up_bad, d_inj, eps, sh, ws, d_bad, d_inject, - nullptr); - check(cudaMemcpy(bad_mixed.data(), d_bad, bad_mixed.size() * sizeof(float), cudaMemcpyDeviceToHost), "cb b"); - const double rel = rel_diff(want_mixed, bad_mixed); - const bool visible = rel > 0.05; - std::printf(" %-40s %s (%.1f%% apart)\n", "weight orientation is observable", - visible ? "yes" : "*** NO ***", rel * 100); - if (!visible) ++bad; - cudaFree(d_down_bad); cudaFree(d_up_bad); cudaFree(d_bad); - } - - // ---- the FINAL mixer passes w_inject = nullptr, and then nothing may be written - float sentinel = -12345.0f; - check(cudaMemcpy(d_inject, &sentinel, sizeof(float), cudaMemcpyHostToDevice), "c sentinel"); - strata::kernels::gr_read(d_R, d_norm, d_down, d_up, nullptr, eps, sh, ws, d_mixed, d_inject, nullptr); - float after = 0.0f; - check(cudaMemcpy(&after, d_inject, sizeof(float), cudaMemcpyDeviceToHost), "c after"); - const bool untouched = (after == sentinel); - std::printf(" %-40s %s\n", "null w_inject writes nothing", untouched ? "yes" : "*** NO ***"); - if (!untouched) ++bad; - - // ---- gr_write: the `2*sigmoid` centring, asserted as the PROPERTY the source comment claims - std::vector block_out((size_t) n_embd); - for (auto& x : block_out) x = gauss(rng); - std::vector zero_inj((size_t) hc, 0.0f); - float *d_Rw = nullptr, *d_bo = nullptr, *d_zi = nullptr, *d_outw = nullptr; - check(cudaMalloc(&d_Rw, R.size() * sizeof(float)), "m Rw"); - check(cudaMalloc(&d_bo, block_out.size() * sizeof(float)), "m bo"); - check(cudaMalloc(&d_zi, zero_inj.size() * sizeof(float)), "m zi"); - check(cudaMalloc(&d_outw, R.size() * sizeof(float)), "m outw"); - check(cudaMemcpy(d_Rw, R.data(), R.size() * sizeof(float), cudaMemcpyHostToDevice), "c Rw"); - check(cudaMemcpy(d_bo, block_out.data(), block_out.size() * sizeof(float), cudaMemcpyHostToDevice), "c bo"); - check(cudaMemcpy(d_zi, zero_inj.data(), zero_inj.size() * sizeof(float), cudaMemcpyHostToDevice), "c zi"); - - strata::kernels::gr_write(d_Rw, d_bo, d_zi, sh, d_outw, nullptr); - std::vector got_write((size_t) hc_dim); - check(cudaMemcpy(got_write.data(), d_outw, got_write.size() * sizeof(float), cudaMemcpyDeviceToHost), "c outw"); - - double worst_plain = 0; - for (long long c = 0; c < hc; ++c) - for (long long d = 0; d < n_embd; ++d) { - const size_t i = (size_t) (c * n_embd + d); - const double want = (double) R[i] + (double) block_out[(size_t) d]; - worst_plain = std::fmax(worst_plain, rel_terms(want, (double) got_write[i], (double) R[i], - (double) block_out[(size_t) d])); - } - const bool plain = worst_plain < 1e-6; - std::printf(" %-40s %s (worst rel %.3e)\n", "zero injection -> plain residual add", - plain ? "yes" : "*** NO ***", worst_plain); - if (!plain) ++bad; - - // the rival reading: sigmoid without the 2 halves the update, and must be visible. - // - // The comparison is on the DELTA `out - R`, not on `out`. The claim is about the gate WEIGHT, and `R` - // now reaches 64 in the last stream, so measuring `R + block_out*w` against the wrong reading dilutes a - // 100% error in `w` down to 2.27% - which is how this check first passed as "not observable" while being - // perfectly observable. Measure the quantity the claim is about. - { - std::vector got_delta((size_t) hc_dim), want_delta((size_t) hc_dim), wrong_delta((size_t) hc_dim); - for (long long c = 0; c < hc; ++c) - for (long long d = 0; d < n_embd; ++d) { - const size_t i = (size_t) (c * n_embd + d); - got_delta[i] = (float) ((double) got_write[i] - (double) R[i]); - want_delta[i] = block_out[(size_t) d]; // 2*sigmoid(0) = 1.0 - wrong_delta[i] = block_out[(size_t) d] * 0.5f; // 1*sigmoid(0) = 0.5 - } - const double rel = rel_diff(want_delta, wrong_delta); - const double rel_got = rel_diff(want_delta, got_delta); - const bool visible = rel > 0.05 && rel_got < 0.05; - std::printf(" %-40s %s (readings %.0f%% apart, kernel within %.2e)\n", - "1*sigmoid vs 2*sigmoid is observable", visible ? "yes" : "*** NO ***", rel * 100, rel_got); - if (!visible) ++bad; - } - - // a non-zero injection: every stream receives the SAME block output, differing only by weight - std::vector inj((size_t) hc); - for (auto& x : inj) x = gauss(rng) * 3.0f; - check(cudaMemcpy(d_zi, inj.data(), inj.size() * sizeof(float), cudaMemcpyHostToDevice), "c inj2"); - strata::kernels::gr_write(d_Rw, d_bo, d_zi, sh, d_outw, nullptr); - check(cudaMemcpy(got_write.data(), d_outw, got_write.size() * sizeof(float), cudaMemcpyDeviceToHost), "c outw2"); - double worst_stream = 0; - for (long long c = 0; c < hc; ++c) { - const double w = 2.0 / (1.0 + std::exp(-(double) inj[(size_t) c] / (double) hc)); - for (long long d = 0; d < n_embd; ++d) { - const size_t i = (size_t) (c * n_embd + d); - const double want = (double) R[i] + (double) block_out[(size_t) d] * w; - worst_stream = std::fmax(worst_stream, rel_terms(want, (double) got_write[i], (double) R[i], - (double) block_out[(size_t) d] * w)); - } - } - const bool streams_ok = worst_stream < 1e-6; - std::printf(" %-40s %s (worst rel %.3e)\n", "every stream adds the same block output", - streams_ok ? "yes" : "*** NO ***", worst_stream); - if (!streams_ok) ++bad; - - // ---- THE REAL DIMENSIONS. Exercise all activation/projection variants at n_embd=2560, hc=4, hc_lr=320. - // Workspace sizing and every full weight row must agree with the model geometry. - { - const long long rn = 2560, rhc = 4, rlr = 320, rdim = rhc * rn; - std::mt19937 rrng(99); - std::normal_distribution rg(0.0f, 1.0f); - auto rbf16 = [&](size_t n, float sigma) { - std::vector v(n); - for (auto& x : v) x = to_bf16(rg(rrng) * sigma); - return v; - }; - std::vector rR((size_t) rdim); - for (auto& x : rR) x = rg(rrng); - for (long long c = 0; c < rhc; ++c) - for (long long d = 0; d < rn; ++d) rR[(size_t) (c * rn + d)] *= std::pow(4.0f, (float) c); - std::vector rnorm((size_t) rdim); - for (auto& x : rnorm) x = 1.0f + 0.1f * rg(rrng); - std::vector rdown = rbf16((size_t) (rlr * rdim), 0.2f); - std::vector rup = rbf16((size_t) (rdim * rlr), 0.2f); - std::vector rinj = rbf16((size_t) (rhc * rdim), 0.05f); - - std::vector qd(rdown.size()), qu(rup.size()), qi(rinj.size()); - for (size_t i = 0; i < rdown.size(); ++i) qd[i] = bf16_bits(rdown[i]); - for (size_t i = 0; i < rup.size(); ++i) qu[i] = bf16_bits(rup[i]); - for (size_t i = 0; i < rinj.size(); ++i) qi[i] = bf16_bits(rinj[i]); - - float *dR = nullptr, *dN = nullptr, *dM = nullptr, *dI = nullptr; - uint16_t *dD = nullptr, *dU = nullptr, *dJ = nullptr; - check(cudaMalloc(&dR, rR.size() * 4), "rR"); - check(cudaMalloc(&dN, rnorm.size() * 4), "rN"); - check(cudaMalloc(&dD, qd.size() * 2), "rD"); - check(cudaMalloc(&dU, qu.size() * 2), "rU"); - check(cudaMalloc(&dJ, qi.size() * 2), "rJ"); - check(cudaMalloc(&dM, (size_t) rn * 4), "rM"); - check(cudaMalloc(&dI, (size_t) rhc * 4), "rI"); - check(cudaMemcpy(dR, rR.data(), rR.size() * 4, cudaMemcpyHostToDevice), "crR"); - check(cudaMemcpy(dN, rnorm.data(), rnorm.size() * 4, cudaMemcpyHostToDevice), "crN"); - check(cudaMemcpy(dD, qd.data(), qd.size() * 2, cudaMemcpyHostToDevice), "crD"); - check(cudaMemcpy(dU, qu.data(), qu.size() * 2, cudaMemcpyHostToDevice), "crU"); - check(cudaMemcpy(dJ, qi.data(), qi.size() * 2, cudaMemcpyHostToDevice), "crJ"); - - const strata::kernels::GrShapes rsh{rn, rhc, rlr}; - void* rws_raw = nullptr; - check(cudaMalloc(&rws_raw, strata::kernels::gr_workspace_bytes(rsh)), "m rws"); - strata::kernels::GrWorkspace rws; - strata::kernels::gr_workspace_init(rsh, rws_raw, rws); - for (int mode = 0; mode < 3; ++mode) { - select_activation_mode(mode); - strata::kernels::gr_read(dR, dN, dD, dU, dJ, eps, rsh, rws, dM, dI, nullptr); - std::vector gm((size_t) rn), gi((size_t) rhc); - check(cudaMemcpy(gm.data(), dM, gm.size() * 4, cudaMemcpyDeviceToHost), "cgm"); - check(cudaMemcpy(gi.data(), dI, gi.size() * 4, cudaMemcpyDeviceToHost), "cgi"); - - Opts precision; - precision.round_activation = mode == 0; - std::vector wm, wi; - reference(rR, rnorm, rdown, rup, rinj, eps, rn, rhc, rlr, precision, wm, wi); - const double rm = rel_diff(wm, gm), ri = rel_diff(wi, gi); - const bool ok = rm <= 1e-4 && ri <= 1e-4; - std::printf("\n real dims 2560/4/320 %s %s (mixed %.3e, inject %.3e)\n", - activation_mode_name(mode), ok ? "pass" : "*** FAIL ***", rm, ri); - if (!ok) ++bad; - } - bad += fused_multi_lds_parity(dN, dD, dU, dJ, eps); - select_activation_mode(0); - cudaFree(rws_raw); - cudaFree(dR); cudaFree(dN); cudaFree(dD); cudaFree(dU); cudaFree(dJ); cudaFree(dM); cudaFree(dI); - } - - bad += scalar_activation_contract(); - std::printf("\ngr_read/gr_write: %d failures\n", bad); - if (bad) return 1; - if (selftest) std::printf("gr_parity OK\n"); - return 0; -} diff --git a/src/kernels/iq_multi_parity.cpp b/src/kernels/iq_multi_parity.cpp deleted file mode 100644 index a2b8049..0000000 --- a/src/kernels/iq_multi_parity.cpp +++ /dev/null @@ -1,415 +0,0 @@ -// src/kernels/iq_multi_parity.cpp - the IQ kernels that decode each weight part once for every -// column / entry, against the older kernels that decode it again per column. Synthetic blocks, no model. -// -// build/iq_multi_parity the checks (a ctest; needs the GPU) -// build/iq_multi_parity --bench the checks, then old/new timings of both paths -// -// (1) iq_mmvq, every format it takes, ncols 1..8 and 11 (the > 8 split): the new output must be BITWISE equal to -// the old one (iq_set_old_kernels), and within float rounding of a double reference built from the GPU's own -// dequantizer (validated against gguf-py by iq_parity) and the dequantized q8_1 activations - a gross-error -// guard, not the contract. -// (2) native_expert_grouped, every gate/up format with the down formats: groups of 0..11 entries (more than a pass -// of GRP_NC), unused grid rows (cap_groups > groups), scattered destinations; bitwise, new vs old, the rows it -// must not write included. -// -// Random bytes are valid codes for every format here (all grid indices are in range); only the fp16 block scales -// are set, small enough that the grouped path's SwiGLU output keeps a finite fp16 q8_1 scale. -#include "strata/kernels/f16_bits.hpp" -#include "strata/kernels/iq_kernels.hpp" -#include "strata/kernels/native_mmvq.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace k = strata::kernels; - -namespace { - -int g_fail = 0; - -void ck(cudaError_t e, const char* w) { - if (e != cudaSuccess) { - std::fprintf(stderr, "CUDA error in %s: %s\n", w, cudaGetErrorString(e)); - std::exit(2); - } -} - -template -T* dalloc(size_t n) { - T* p = nullptr; - ck(cudaMalloc(&p, n * sizeof(T) + 256), "malloc"); - ck(cudaMemset(p, 0, n * sizeof(T) + 256), "memset"); - return p; -} - -const char* name_of(int t) { - switch (t) { - case 16: return "IQ2_XXS"; - case 17: return "IQ2_XS"; - case 18: return "IQ3_XXS"; - case 20: return "IQ4_NL"; - case 21: return "IQ3_S"; - case 22: return "IQ2_S"; - case 23: return "IQ4_XS"; - case 29: return "IQ1_M"; - case 42: return "Q2_0"; - default: return "?"; - } -} -int block_values(int t) { return t == 20 ? 32 : t == 42 ? 64 : 256; } - -// `rows` rows of `n` values of format t: random bytes, then a finite fp16 scale in every block -std::vector random_rows(int t, int64_t rows, int64_t n, std::mt19937& rng) { - const size_t rb = k::iq_row_bytes(t, n), bs = k::iq_row_bytes(t, block_values(t)); - std::vector w((size_t) rows * rb); - std::uniform_int_distribution byte(0, 255), ex(2, 8), man(0, 1023), sgn(0, 3); - for (auto& b : w) b = (uint8_t) byte(rng); - for (size_t o = 0; o < w.size(); o += bs) { - if (t == 29) { - // IQ1_M: the fp16 scale is the top nibbles of the four scale words (bytes 48..55); nibble 3 carries the - // sign and the exponent's top bits: 0x1 / 0x2 (or 0x9 / 0xA) keeps it in 2^-11 .. 2^-3 - const uint8_t nib = (uint8_t) ((sgn(rng) == 0 ? 0x8 : 0x0) | (1 + (byte(rng) & 1))); - w[o + 55] = (uint8_t) ((w[o + 55] & 0x0F) | (nib << 4)); - } else { - const uint16_t h = (uint16_t) ((sgn(rng) == 0 ? 0x8000 : 0) | (ex(rng) << 10) | man(rng)); // 2^-13 .. 2^-6 - std::memcpy(&w[o], &h, 2); - } - } - return w; -} - -std::vector random_x(size_t n, std::mt19937& rng) { - std::normal_distribution nd(0.f, 1.f); - std::vector x(n); - for (auto& v : x) v = nd(rng); - return x; -} - -// q8_1 blocks (fp16 scale, fp16 sum, 32 int8) back to floats -std::vector dequant_q8_1(const std::vector& q, size_t n) { - std::vector v(n); - for (size_t b = 0; b < n / 32; ++b) { - uint16_t dh; - std::memcpy(&dh, &q[b * 36], 2); - const double d = k::f32_from_f16(dh); - for (int i = 0; i < 32; ++i) v[b * 32 + i] = d * (int8_t) q[b * 36 + 4 + i]; - } - return v; -} - -// ------------------------------------------------------------------------------------------------ (1) iq_mmvq -void check_mmvq(int t, int n_in, int n_out, cudaStream_t s, std::mt19937& rng) { - const auto w = random_rows(t, n_out, n_in, rng); - uint8_t* dw = dalloc(w.size()); - ck(cudaMemcpy(dw, w.data(), w.size(), cudaMemcpyHostToDevice), "w"); - // the double reference's weights: the GPU dequantizer (iq_parity checks it against gguf-py) - float* dwf = dalloc((size_t) n_out * n_in); - k::iq_dequant_f32(t, dw, (int64_t) n_out * n_in, dwf, s); - std::vector wf((size_t) n_out * n_in); - ck(cudaMemcpy(wf.data(), dwf, wf.size() * 4, cudaMemcpyDeviceToHost), "wf"); - const int max_cols = 11; - const auto x = random_x((size_t) max_cols * n_in, rng); - float* dx = dalloc(x.size()); - ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); - const size_t xq_bytes = (size_t) max_cols * (n_in / 32) * 36; - uint8_t* dxq = dalloc(xq_bytes); - k::quantize_q8_1_rows(dx, max_cols, n_in, dxq, s); - std::vector xq(xq_bytes); - ck(cudaMemcpy(xq.data(), dxq, xq_bytes, cudaMemcpyDeviceToHost), "xq"); - const auto xd = dequant_q8_1(xq, (size_t) max_cols * n_in); - float* dy_old = dalloc((size_t) max_cols * n_out); - float* dy_new = dalloc((size_t) max_cols * n_out); - std::vector y_old((size_t) max_cols * n_out), y_new(y_old.size()); - const int cols[] = {1, 2, 3, 4, 5, 6, 7, 8, 11}; - int bad = 0; - double worst = 0.0; - for (int nc : cols) { - ck(cudaMemset(dy_old, 0xFF, y_old.size() * 4), "memset"); - ck(cudaMemset(dy_new, 0xFF, y_new.size() * 4), "memset"); - k::iq_set_old_kernels(true); - k::iq_mmvq(t, dw, dxq, dy_old, n_in, n_out, nc, s); - k::iq_set_old_kernels(false); - k::iq_mmvq(t, dw, dxq, dy_new, n_in, n_out, nc, s); - ck(cudaStreamSynchronize(s), "sync"); - ck(cudaMemcpy(y_old.data(), dy_old, y_old.size() * 4, cudaMemcpyDeviceToHost), "y_old"); - ck(cudaMemcpy(y_new.data(), dy_new, y_new.size() * 4, cudaMemcpyDeviceToHost), "y_new"); - size_t diff = 0; - for (size_t i = 0; i < y_old.size(); ++i) diff += std::memcmp(&y_old[i], &y_new[i], 4) != 0; - double num = 0, den = 0; - bool finite = true; - for (int c = 0; c < nc; ++c) - for (int r = 0; r < n_out; ++r) { - double acc = 0; - for (int i = 0; i < n_in; ++i) acc += (double) wf[(size_t) r * n_in + i] * xd[(size_t) c * n_in + i]; - const float g = y_new[(size_t) c * n_out + r]; - finite = finite && std::isfinite(g); - num += std::fabs(g - acc); - den += std::fabs(acc); - } - const double rel = num / (den + 1e-30); - worst = std::max(worst, rel); - if (diff != 0 || !finite || !(rel < 1e-2)) { - std::printf(" %-8s %5d x %5d ncols %2d: %zu outputs differ from the old kernel, ref rel %.2e%s FAIL\n", - name_of(t), n_out, n_in, nc, diff, rel, finite ? "" : ", non-finite"); - ++bad; - } - } - std::printf("%-8s type %2d %5d x %5d iq_mmvq ncols 1..8, 11: %s (ref rel <= %.2e)\n", name_of(t), t, n_out, n_in, - bad ? "FAIL" : "bitwise equal to the old kernel", worst); - g_fail += bad; - cudaFree(dw); cudaFree(dwf); cudaFree(dx); cudaFree(dxq); cudaFree(dy_old); cudaFree(dy_new); -} - -// ---------------------------------------------------------------------------------- (2) native_expert_grouped -struct Grouped { - k::NativeExpertLayout L; - int n_groups = 0, n_ent = 0, cap_groups = 0, cap_ent = 0, n_tok = 0; - std::vector blobs; - unsigned long long* dptr = nullptr; - int32_t *dstart = nullptr, *dn = nullptr, *ddst = nullptr, *dtok = nullptr; - float* dx = nullptr; - uint8_t *dxq = nullptr, *dscr = nullptr; - float* dout = nullptr; - size_t out_floats = 0; - - Grouped(int gu, int dt, int64_t H, int64_t FF, const std::vector& counts, int tokens, std::mt19937& rng) { - L = k::native_expert_layout(gu, dt, H, FF); - n_groups = (int) counts.size(); - cap_groups = n_groups + 2; // the extra grid rows must exit - n_tok = tokens; - std::vector start(1, 0), tok, dst; - for (int c : counts) start.push_back(start.back() + c); - n_ent = start.back(); - cap_ent = n_ent + 3; - std::uniform_int_distribution tk(0, tokens - 1); - for (int e = 0; e < n_ent; ++e) tok.push_back(tk(rng)); - dst.resize(n_ent); - std::iota(dst.begin(), dst.end(), 0); - std::shuffle(dst.begin(), dst.end(), rng); - std::vector ptr; - for (int g = 0; g < n_groups; ++g) { - // one blob per group: gate rows | up rows (format gu, H values) | down rows (format dt, FF values) - auto b = random_rows(gu, 2 * FF, H, rng); - const auto d = random_rows(dt, H, FF, rng); - b.insert(b.end(), d.begin(), d.end()); - if (b.size() != L.bytes) { std::fprintf(stderr, "blob size %zu != %zu\n", b.size(), L.bytes); std::exit(2); } - uint8_t* db = dalloc(b.size()); - ck(cudaMemcpy(db, b.data(), b.size(), cudaMemcpyHostToDevice), "blob"); - blobs.push_back(db); - ptr.push_back((unsigned long long) db); - } - dptr = dalloc(cap_groups); - dstart = dalloc(cap_groups + 1); - dn = dalloc(1); - ddst = dalloc(cap_ent); - dtok = dalloc(cap_ent); - ck(cudaMemcpy(dptr, ptr.data(), ptr.size() * 8, cudaMemcpyHostToDevice), "ptr"); - ck(cudaMemcpy(dstart, start.data(), start.size() * 4, cudaMemcpyHostToDevice), "start"); - ck(cudaMemcpy(dn, &n_groups, 4, cudaMemcpyHostToDevice), "n"); - if (n_ent) { - ck(cudaMemcpy(ddst, dst.data(), dst.size() * 4, cudaMemcpyHostToDevice), "dst"); - ck(cudaMemcpy(dtok, tok.data(), tok.size() * 4, cudaMemcpyHostToDevice), "tok"); - } - const auto x = random_x((size_t) tokens * H, rng); - dx = dalloc(x.size()); - ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); - dxq = dalloc((size_t) tokens * (H / 32) * 36); - dscr = dalloc(k::native_expert_scratch_bytes(cap_ent, FF)); - out_floats = (size_t) cap_ent * H; - dout = dalloc(out_floats); - } - ~Grouped() { - for (auto* b : blobs) cudaFree(b); - cudaFree(dptr); cudaFree(dstart); cudaFree(dn); cudaFree(ddst); cudaFree(dtok); - cudaFree(dx); cudaFree(dxq); cudaFree(dscr); cudaFree(dout); - } - void run(bool old, cudaStream_t s) { - k::iq_set_old_kernels(old); - k::quantize_q8_1_rows(dx, n_tok, L.n_embd, dxq, s); - k::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, cap_groups, cap_ent, dxq, dscr, dout, s); - k::iq_set_old_kernels(false); - } - std::vector result(bool old, cudaStream_t s) { - ck(cudaMemset(dout, 0xFF, out_floats * 4), "memset"); // NaN rows: must stay NaN where nothing writes - ck(cudaMemset(dscr, 0, k::native_expert_scratch_bytes(cap_ent, L.n_ff)), "memset"); - run(old, s); - ck(cudaStreamSynchronize(s), "sync"); - std::vector o(out_floats); - ck(cudaMemcpy(o.data(), dout, o.size() * 4, cudaMemcpyDeviceToHost), "out"); - return o; - } -}; - -void check_grouped(int gu, int dt, int64_t H, int64_t FF, cudaStream_t s, std::mt19937& rng) { - // 0..11 entries per group: one pass, a partial pass, two passes and three passes of GRP_NC = 4 - Grouped G(gu, dt, H, FF, {1, 3, 4, 5, 0, 8, 2, 11, 1}, 8, rng); - const auto a = G.result(true, s), b = G.result(false, s); - size_t diff = 0, written = 0; - bool finite = true; - for (size_t i = 0; i < a.size(); ++i) { - diff += std::memcmp(&a[i], &b[i], 4) != 0; - if (i < (size_t) G.n_ent * H) { ++written; finite = finite && std::isfinite(b[i]); } - } - const bool ok = diff == 0 && finite; - std::printf("%-8s/%-7s %5lld x %4lld native_expert_grouped, %d groups, %d entries: %s\n", name_of(gu), - name_of(dt), (long long) H, (long long) FF, G.n_groups, G.n_ent, - ok ? "bitwise equal to the old kernels" : "FAIL"); - if (!ok) { - std::printf(" %zu of %zu floats differ%s\n", diff, a.size(), finite ? "" : ", non-finite outputs"); - ++g_fail; - } -} - -// ------------------------------------------------------------------------------------------------ --bench -float time_ms(cudaStream_t s, int it, const auto& fn) { - cudaEvent_t e0, e1; - cudaEventCreate(&e0); - cudaEventCreate(&e1); - fn(); - cudaEventRecord(e0, s); - for (int i = 0; i < it; ++i) fn(); - cudaEventRecord(e1, s); - ck(cudaEventSynchronize(e1), "bench"); - float ms = 0; - cudaEventElapsedTime(&ms, e0, e1); - cudaEventDestroy(e0); - cudaEventDestroy(e1); - return ms / it; -} - -void bench(cudaStream_t s, std::mt19937& rng) { - std::printf("\n--bench: microseconds per call, old (per-column decode) / new (decode once), idle GPU assumed\n"); - const int n_in = 2560, n_out = 8192, it = 200; - for (int t : {16, 17, 18, 21, 22, 29}) { - const auto w = random_rows(t, n_out, n_in, rng); - uint8_t* dw = dalloc(w.size()); - ck(cudaMemcpy(dw, w.data(), w.size(), cudaMemcpyHostToDevice), "w"); - const auto x = random_x((size_t) 8 * n_in, rng); - float* dx = dalloc(x.size()); - ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); - uint8_t* dxq = dalloc((size_t) 8 * (n_in / 32) * 36); - k::quantize_q8_1_rows(dx, 8, n_in, dxq, s); - float* dy = dalloc((size_t) 8 * n_out); - std::printf("%-8s iq_mmvq %d x %d:", name_of(t), n_out, n_in); - for (int nc = 1; nc <= 8; ++nc) { - float us[2]; - for (int old = 1; old >= 0; --old) { - k::iq_set_old_kernels(old != 0); - us[old] = 1e3f * time_ms(s, it, [&] { k::iq_mmvq(t, dw, dxq, dy, n_in, n_out, nc, s); }); - } - std::printf(" %d: %.1f/%.1f", nc, us[1], us[0]); - } - std::printf("\n"); - k::iq_set_old_kernels(false); - cudaFree(dw); cudaFree(dx); cudaFree(dxq); cudaFree(dy); - } - // the verify window's shape: 2560 x 640 experts, 16 groups of m entries each - for (int gu : {16, 17, 18, 21, 22, 29}) { - std::printf("%-8s/Q2_0 grouped, 16 groups of m entries:", name_of(gu)); - for (int m : {1, 2, 3, 4, 8}) { - Grouped G(gu, 42, 2560, 640, std::vector(16, m), 8, rng); - float us[2]; - for (int old = 1; old >= 0; --old) - us[old] = 1e3f * time_ms(s, 50, [&] { G.run(old != 0, s); }); - std::printf(" m=%d: %.1f/%.1f", m, us[1], us[0]); - } - std::printf("\n"); - } -} - -// #606: both q8_1 activation quantizers (quantize_q8_1_rows and native_quantize_q8_1) against a host transcription -// of the 0.1.38 formula: every finite block bit for bit; a block whose sum (or scale) overflowed fp16 is now stored -// finite (the largest half, its sign), with its values in the int8 range. -void check_q8_1_finite(cudaStream_t s, std::mt19937& rng) { - const int n = 2560, rows = 3, nb = n / 32; - std::vector x = random_x((size_t) rows * n, rng); - for (int i = 0; i < 32; ++i) x[(size_t) 5 * 32 + i] = 3000.0f; // sum 96,000: overflowed - for (int i = 0; i < 32; ++i) x[(size_t) 9 * 32 + i] = i == 3 ? -70000.0f : 0.5f; // sum -69,984.5 - for (int i = 0; i < 32; ++i) x[(size_t) 13 * 32 + i] = 2000.0f + i; // sum 64,496: finite, kept - x[(size_t) n + 40] = 2.0e7f; // amax / 127 overflowed too - float* dx = dalloc(x.size()); - ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); - uint8_t* dq = dalloc((size_t) rows * nb * 36); - for (int path = 0; path < 2; ++path) { - if (path == 0) k::quantize_q8_1_rows(dx, rows, n, dq, s); - else k::native_quantize_q8_1(dx, dq, n, rows, s); - ck(cudaStreamSynchronize(s), "quantize"); - std::vector got((size_t) rows * nb * 36); - ck(cudaMemcpy(got.data(), dq, got.size(), cudaMemcpyDeviceToHost), "q"); - int same = 0, clamped = 0, bad = 0; - for (int b = 0; b < rows * nb; ++b) { - const float* v = x.data() + (size_t) b * 32; - float lane[32], amax = 0.0f; - for (int i = 0; i < 32; ++i) { lane[i] = v[i]; amax = std::max(amax, std::fabs(v[i])); } - for (int o = 16; o > 0; o >>= 1) { // the warp's butterfly: every lane ends with the same sum - float nx[32]; - for (int i = 0; i < 32; ++i) nx[i] = lane[i] + lane[i ^ o]; - std::memcpy(lane, nx, sizeof lane); - } - const float d = amax / 127.0f, sum = lane[0]; - const uint8_t* g = got.data() + (size_t) b * 36; - uint16_t gd, gs; - std::memcpy(&gd, g, 2); - std::memcpy(&gs, g + 2, 2); - const uint16_t od = k::f16_from_f32(d), os = k::f16_from_f32(sum); - const bool finite_before = (od & 0x7c00) != 0x7c00 && (os & 0x7c00) != 0x7c00; - if (finite_before) { - uint8_t want[36]; - std::memcpy(want, &od, 2); - std::memcpy(want + 2, &os, 2); - for (int i = 0; i < 32; ++i) // CUDA's roundf: half away from zero, as std::round - want[4 + i] = (uint8_t) (int8_t) (amax == 0.0f ? 0.0f : std::round(v[i] / d)); - // native_mmvq.cu is built with --use_fast_math (its divisions are approximate): there the sum must be - // the same bits, the scale within one fp16 step and each value within one step - bool near = path == 1 && gs == os && std::abs((int) gd - (int) od) <= 1; - for (int i = 0; near && i < 32; ++i) near = std::abs((int) (int8_t) g[4 + i] - (int) (int8_t) want[4 + i]) <= 1; - if (std::memcmp(want, g, 36) == 0 || near) ++same; - else { ++bad; std::printf(" q8_1 path %d block %d: changed although it was finite\n", path, b); } - } else { - const float fd = k::f32_from_f16(gd), fs = k::f32_from_f16(gs); - bool ok = std::isfinite(fd) && std::isfinite(fs) && fd > 0.0f && - ((os & 0x7c00) != 0x7c00 ? gs == os : std::fabs(fs) == 65504.0f && (fs < 0) == (sum < 0)); - for (int i = 0; i < 32; ++i) ok = ok && (int8_t) g[4 + i] >= -127 && (int8_t) g[4 + i] <= 127; - if (ok) ++clamped; - else { ++bad; std::printf(" q8_1 path %d block %d: d %g sum %g not finite and clamped\n", path, b, fd, fs); } - } - } - std::printf("q8_1 finite (%s): %d finite blocks as before, %d overflowed blocks clamped finite%s\n", - path == 0 ? "quantize_q8_1_rows" : "native_quantize_q8_1", same, clamped, bad ? " FAIL" : ""); - g_fail += bad + (clamped != 3); - } - cudaFree(dx); - cudaFree(dq); -} - -} // namespace - -int main(int argc, char** argv) { - const bool do_bench = argc > 1 && std::string(argv[1]) == "--bench"; - cudaStream_t s; - ck(cudaStreamCreate(&s), "stream"); - std::mt19937 rng(18); - for (int t : {16, 17, 18, 20, 21, 22, 23, 29, 42}) { - check_mmvq(t, 2560, 67, s, rng); // the model's n_embd; 67 rows: a partial block of 4 rows - check_mmvq(t, 1024, 5, s, rng); - } - 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); - std::printf("iq_multi_parity: %d failures\n", g_fail); - cudaStreamDestroy(s); - return g_fail ? 1 : 0; -} diff --git a/src/kernels/iq_parity.cpp b/src/kernels/iq_parity.cpp deleted file mode 100644 index 4bc74f6..0000000 --- a/src/kernels/iq_parity.cpp +++ /dev/null @@ -1,125 +0,0 @@ -// src/kernels/iq_parity.cpp - plan v0.3 P6: the i-quant kernels against gguf-py on generated rows. -// -// python tools/iq_fixture.py --out && build/iq_parity -// -// The fixtures are GENERATED (deterministic; TODO 24) - tools/iq_fixture.py writes each type's raw block -// bytes and the gguf-py dequantized reference (Q2_0, this repository's type 42, is dequantized by -// tools/gguf_writer.py's codec instead - gguf-py has no such type). Dependencies: python3 with numpy and -// the vendored gguf-py that setup downloads (the pinned llama.cpp zip; third_party/ is gitignored). -// -// What is compared, and how: the dequant parity is a MEASURED relative error (sum|got-ref| / sum|ref|) - -// bitwise equality is not claimed and not required; on the generated fixtures it measures 0.00e+00. The -// MMVQ dot (q8_1 activations) must match the float matrix-vector product over that reference within the -// activation rounding (a few 1e-3 relative), for 1 to 8 columns, every column of a multi-column call bitwise -// equal to a one-column call on it. -#include "strata/kernels/iq_kernels.hpp" -#include "strata/kernels/native_mmvq.hpp" - -#include - -#include -#include -#include -#include -#include -#include - -int main(int argc, char** argv) { - const std::string dir = argc > 1 ? argv[1] : "logs/iq_fixture"; - const char* names[] = {"IQ2_XXS", "IQ2_XS", "IQ2_S", "IQ3_XXS", "IQ3_S", "IQ1_M", "IQ4_NL", "IQ4_XS", "Q2_0", "Q3_K"}; - int failures = 0, missing = 0; - cudaStream_t s; - cudaStreamCreate(&s); - for (const char* nm : names) { - std::FILE* f = std::fopen((dir + "/" + nm + ".bin").c_str(), "rb"); - std::FILE* g = std::fopen((dir + "/" + nm + ".f32").c_str(), "rb"); - if (!f || !g) { - std::printf("%-8s missing fixture: %s/%s.bin or %s/%s.f32 - generate the fixtures first with " - "python tools/iq_fixture.py --out %s (deterministic; see the tool's --help)\n", - nm, dir.c_str(), nm, dir.c_str(), nm, dir.c_str()); - if (f) std::fclose(f); - if (g) std::fclose(g); - ++failures; - ++missing; - continue; - } - int hdr[3]; - std::fread(hdr, 4, 3, f); - const int type = hdr[0], rows = hdr[1], cols = hdr[2]; - std::vector raw; - { uint8_t buf[1 << 16]; size_t n; while ((n = std::fread(buf, 1, sizeof buf, f)) > 0) raw.insert(raw.end(), buf, buf + n); } - std::vector ref((size_t) rows * cols); - std::fread(ref.data(), 4, ref.size(), g); - std::fclose(f); - std::fclose(g); - void* dw = nullptr; - float* dq = nullptr; - cudaMalloc(&dw, raw.size()); - cudaMalloc(&dq, ref.size() * 4); - cudaMemcpy(dw, raw.data(), raw.size(), cudaMemcpyHostToDevice); - double dq_err = 0.0; - if (strata::kernels::iq_supported(type) && ((size_t) rows * cols) % 256 == 0) { - strata::kernels::iq_dequant_f32(type, dw, (int64_t) rows * cols, dq, s); - std::vector got(ref.size()); - cudaMemcpy(got.data(), dq, got.size() * 4, cudaMemcpyDeviceToHost); - double num = 0, den = 0; - for (size_t i = 0; i < ref.size(); ++i) { num += std::fabs(got[i] - ref[i]); den += std::fabs(ref[i]); } - dq_err = num / (den + 1e-30); - } - // the dot, ncols 1..8: each column of an ncols call bitwise equal to a one-column call on it (the - // exact multi-column layout, the default), all of them within the activation rounding of the float product - const int MC = 8; - std::mt19937 rng(7); - std::normal_distribution nd(0.f, 1.f); - std::vector x((size_t) MC * cols); - for (auto& v : x) v = nd(rng); - float* dx = nullptr; - void* xq = nullptr; - float* dy = nullptr; - cudaMalloc(&dx, x.size() * 4); - cudaMalloc(&xq, (size_t) MC * cols / 32 * 36); - cudaMalloc(&dy, (size_t) MC * rows * 4); - cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice); - strata::kernels::quantize_q8_1_rows(dx, MC, cols, xq, s); - std::vector y((size_t) MC * rows), yn(y.size()); - int multi_bad = 0; - try { - for (int c = 0; c < MC; ++c) - strata::kernels::native_mmvq(type, dw, (const uint8_t*) xq + (size_t) c * cols / 32 * 36, - dy + (size_t) c * rows, cols, rows, 1, s); - cudaStreamSynchronize(s); - cudaMemcpy(y.data(), dy, y.size() * 4, cudaMemcpyDeviceToHost); - for (int nc = 2; nc <= MC; ++nc) { - strata::kernels::native_mmvq(type, dw, xq, dy, cols, rows, nc, s); - cudaStreamSynchronize(s); - cudaMemcpy(yn.data(), dy, yn.size() * 4, cudaMemcpyDeviceToHost); - if (strata::kernels::native_mmvq_multi_exact() && - std::memcmp(yn.data(), y.data(), (size_t) nc * rows * 4) != 0) { - std::printf("%-8s mmvq ncols %d: not bitwise equal to the one-column calls\n", nm, nc); - ++multi_bad; - } - } - } catch (const std::exception& e) { std::printf("%-8s mmvq: %s\n", nm, e.what()); ++failures; continue; } - double num = 0, den = 0; - for (int c = 0; c < MC; ++c) - for (int r = 0; r < rows; ++r) { - double acc = 0; - for (int k = 0; k < cols; ++k) acc += (double) ref[(size_t) r * cols + k] * x[(size_t) c * cols + k]; - num += std::fabs(y[(size_t) c * rows + r] - acc); - den += std::fabs(acc); - } - const double mm_err = num / (den + 1e-30); - const bool ok = dq_err < 1e-6 && mm_err < 2e-2 && multi_bad == 0; - std::printf("%-8s type %2d %4d x %5d dequant rel %.2e mmvq rel %.2e (ncols 1..%d) %s\n", nm, type, rows, cols, - dq_err, mm_err, MC, ok ? "ok" : "FAIL"); - if (!ok) ++failures; - cudaFree(dw); cudaFree(dq); cudaFree(dx); cudaFree(xq); cudaFree(dy); - } - std::printf("iq_parity: %d failures\n", failures); - // no fixture at all: the generator was skipped (no numpy / vendored gguf-py) - a skip (3), not a failure - if (missing == (int) (sizeof names / sizeof names[0])) { - std::printf("iq_parity: no fixtures in %s - skipped\n", dir.c_str()); - return 3; - } - return failures ? 1 : 0; -} diff --git a/src/kernels/kv_hybrid_parity.cpp b/src/kernels/kv_hybrid_parity.cpp deleted file mode 100644 index a3c2ebc..0000000 --- a/src/kernels/kv_hybrid_parity.cpp +++ /dev/null @@ -1,371 +0,0 @@ -// src/kernels/kv_hybrid_parity.cpp - hybrid K8V4 KV against host references (GPU, no model). -// -// Exercises the EXACT composed calls the engine's hybrid path makes (layer.cpp / prefill.cpp): the q8/q4 -// append and gather kernels invoked with the unused half's pointers folded onto the used pool, and the -// fused decode attention's KV_MODE 3 (INT8 K, rotated Q4_0 V) followed by the output's inverse Hadamard. -// 1. K: INT8 codes + FP16 scales bitwise vs the host reference (kv_q8.hpp's rules); -// 2. V: after fwht256, Q4_0 blocks bitwise vs the host reference (kv_q4.hpp's rules, PR #21); -// 3. the composed gathers bitwise vs the host dequantization of those codes; -// 4. qsa_decode_attn<3> + output fwht vs a host attention over the SAME dequantized K/V (fp32 math), and -// bounded against the fp32-true attention from the unquantized K/V. -#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 - -#include -#include -#include -#include -#include -#include -#include - -namespace k = strata::kernels; - -namespace { -int g_fail = 0; -void ck(cudaError_t e, const char* w) { - if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } -} -template T* dalloc(size_t n) { - T* p = nullptr; - ck(cudaMalloc(&p, n * sizeof(T) + 64), "malloc"); - ck(cudaMemset(p, 0, n * sizeof(T) + 64), "memset"); - return p; -} - -// kv_q4_parity.cpp's exact CPU references. -void fwht256_host_reference(float* x) { - constexpr int n = 256; - for (int s = 1; s < n; s *= 2) { - for (int i = 0; i < n; i += 2 * s) { - for (int j = 0; j < s; ++j) { - const float u = x[i + j]; - const float v = x[i + j + s]; - x[i + j] = u + v; - x[i + j + s] = u - v; - } - } - } - const float scale = 1.0f / 16.0f; - for (int i = 0; i < n; ++i) x[i] *= scale; -} -void quantize_block_q4_0_host(const float* x, k::block_q4_0& blk) { - float amax = 0.0f, max_val = 0.0f; - for (int i = 0; i < 32; ++i) { - const float v = x[i]; - if (amax < std::fabs(v)) { amax = std::fabs(v); max_val = v; } - } - const float d = max_val / -8.0f; - const float id = d != 0.0f ? 1.0f / d : 0.0f; - blk.d = k::f16_from_f32(d); - for (int i = 0; i < 16; ++i) { - const int q0 = (int) (x[i] * id + 8.5f); - const int q1 = (int) (x[i + 16] * id + 8.5f); - const uint8_t xi0 = (uint8_t) std::min(15, std::max(0, q0)); - const uint8_t xi1 = (uint8_t) std::min(15, std::max(0, q1)); - blk.qs[i] = xi0 | (xi1 << 4); - } -} -} // namespace - -int main() { - std::printf("=== Running kv_hybrid_parity test ===\n"); - k::QsaShapes s = k::qsa_real_shapes(); - s.page_size = 64; - const int H = (int) s.n_head_kv, D = (int) s.head_dim, P = (int) s.page_size, G = D / k::KV_Q8_GROUP; - const int QH = (int) s.n_head, PER = QH / H; // query heads per KV head - const int pages = 24, cells = pages * P; // n_chunks >= n_head: the batched merge overlaps queries below that - std::mt19937 rng(17); - std::normal_distribution nd(0.0f, 1.0f); - - std::vector table(pages); - for (int i = 0; i < pages; ++i) table[i] = (i * 5 + 3) % pages; - int32_t* d_table = dalloc(pages); - ck(cudaMemcpy(d_table, table.data(), pages * 4, cudaMemcpyHostToDevice), "table"); - - std::vector K((size_t) cells * H * D), V((size_t) cells * H * D); - for (auto& x : K) x = nd(rng) * 0.5f; - for (auto& x : V) x = nd(rng) * 0.5f; - - // ---- host reference: K in INT8 (kv_q8.hpp), rotated V in Q4_0 (kv_q4.hpp) - std::vector rk((size_t) cells * H * D); - std::vector rk_s((size_t) cells * H * G); - for (int c = 0; c < cells; ++c) - for (int h = 0; h < H; ++h) - for (int g = 0; g < G; ++g) { - float amax = 0.0f; - for (int t = 0; t < k::KV_Q8_GROUP; ++t) - amax = std::max(amax, std::fabs(K[((size_t) c * H + h) * D + g * k::KV_Q8_GROUP + t])); - const uint16_t sb = k::f16_from_f32(amax / 127.0f); - const float sf = k::f32_from_f16(sb); - for (int t = 0; t < k::KV_Q8_GROUP; ++t) { - int q = 0; - if (sf > 0.0f) { - q = (int) std::nearbyint(K[((size_t) c * H + h) * D + g * k::KV_Q8_GROUP + t] / sf); // rn: ties to even, as the kernel - q = std::max(-127, std::min(127, q)); - } - rk[((size_t) c * H + h) * D + g * k::KV_Q8_GROUP + t] = (int8_t) q; - } - rk_s[((size_t) c * H + h) * G + g] = sb; - } - std::vector Vrot((size_t) cells * H * D); - std::memcpy(Vrot.data(), V.data(), V.size() * 4); - for (int c = 0; c < cells * H; ++c) fwht256_host_reference(Vrot.data() + (size_t) c * D); - std::vector rv4((size_t) cells * H * (D / 32)); - for (int c = 0; c < cells; ++c) - for (int h = 0; h < H; ++h) - for (int b = 0; b < D / 32; ++b) - quantize_block_q4_0_host(&Vrot[((size_t) c * H + h) * D + b * 32], - rv4[((size_t) c * H + h) * (D / 32) + b]); - - // ---- device: one cell appended through the COMPOSED hybrid calls, then gathered - const int64_t q4_row = (int64_t) k::kv_q4_bytes_per_head(D); - int8_t* d_kq = dalloc((size_t) cells * H * D); - uint16_t* d_ks = dalloc((size_t) cells * H * G); - uint8_t* d_v4 = dalloc((size_t) cells * H * q4_row); - float *d_kcur = dalloc((size_t) H * D), *d_vcur = dalloc((size_t) H * D); - int32_t* d_step = dalloc(k::kStepCount); - - int append_bad = 0, gather_bad = 0; - for (int c = 0; c < cells; ++c) { - ck(cudaMemcpy(d_kcur, &K[(size_t) c * H * D], (size_t) H * D * 4, cudaMemcpyHostToDevice), "kcur"); - ck(cudaMemcpy(d_vcur, &V[(size_t) c * H * D], (size_t) H * D * 4, cudaMemcpyHostToDevice), "vcur"); - int32_t step[k::kStepCount]; - k::qsa_step_fill(step, c, s); - ck(cudaMemcpy(d_step, step, sizeof step, cudaMemcpyHostToDevice), "step"); - // exactly what qsa_layer's hybrid branch does - k::fwht256_inplace_cuda(d_vcur, H, nullptr); - k::kv_append_q8_step(d_kq, d_kq, d_ks, d_ks, d_table, d_step, d_kcur, d_kcur, s, nullptr, nullptr); - k::kv_append_q4_step(d_v4, d_v4, d_table, d_step, d_vcur, d_vcur, s, nullptr, nullptr); - ck(cudaGetLastError() != cudaSuccess ? cudaGetLastError() : cudaSuccess, "append"); - } - ck(cudaDeviceSynchronize(), "append sync"); - - std::vector hk((size_t) cells * H * D); - std::vector hks((size_t) cells * H * G); - std::vector hv4((size_t) cells * H * q4_row); - ck(cudaMemcpy(hk.data(), d_kq, hk.size(), cudaMemcpyDeviceToHost), "kq"); - ck(cudaMemcpy(hks.data(), d_ks, hks.size() * 2, cudaMemcpyDeviceToHost), "ks"); - ck(cudaMemcpy(hv4.data(), d_v4, hv4.size(), cudaMemcpyDeviceToHost), "v4"); - // the pools are PHYSICAL (page, head, slot); the reference is by LOGICAL cell - compare through the table - const k::block_q4_0* hv4b = reinterpret_cast(hv4.data()); - for (int c = 0; c < cells; ++c) { - const long long row = ((long long) table[c / P] * H); - for (int h = 0; h < H; ++h) { - const long long r = (row + h) * P + c % P; - for (int d = 0; d < D; ++d) - if (hk[(size_t) r * D + d] != rk[((size_t) c * H + h) * D + d]) ++append_bad; - for (int g = 0; g < G; ++g) - if (hks[(size_t) r * G + g] != rk_s[((size_t) c * H + h) * G + g]) ++append_bad; - for (int b = 0; b < D / 32; ++b) { - const k::block_q4_0& got = hv4b[(size_t) r * (D / 32) + b]; - if (got.d != rv4[((size_t) c * H + h) * (D / 32) + b].d || - std::memcmp(got.qs, rv4[((size_t) c * H + h) * (D / 32) + b].qs, 16) != 0) ++append_bad; - } - } - } - std::printf("[1/3] composed appends: %s (%d bad values of %zu K / %zu V)\n", - append_bad == 0 ? "PASS" : "FAIL", append_bad, hk.size(), rv4.size()); - - // gather every cell (ids = all, ascending - the identity selection for width = cells) - std::vector ids(cells); - for (int i = 0; i < cells; ++i) ids[i] = i; - int32_t* d_ids = dalloc(cells); - ck(cudaMemcpy(d_ids, ids.data(), cells * 4, cudaMemcpyHostToDevice), "ids"); - int32_t step[k::kStepCount]; - k::qsa_step_fill(step, cells - 1, s); - step[k::kStepWidth] = cells; // select everything - ck(cudaMemcpy(d_step, step, sizeof step, cudaMemcpyHostToDevice), "step2"); - uint16_t *d_ksc = dalloc((size_t) cells * H * D), *d_vsc = dalloc((size_t) cells * H * D); - k::kv_gather_q8_step(d_kq, d_kq, d_ks, d_ks, d_table, d_ids, d_step, cells, s, d_ksc, d_ksc, nullptr); - k::kv_gather_q4_step(d_v4, d_v4, d_table, d_ids, d_step, cells, s, d_vsc, d_vsc, nullptr); - ck(cudaDeviceSynchronize(), "gather sync"); - std::vector h_ksc((size_t) cells * H * D), h_vsc((size_t) cells * H * D); - ck(cudaMemcpy(h_ksc.data(), d_ksc, h_ksc.size() * 2, cudaMemcpyDeviceToHost), "ksc"); - ck(cudaMemcpy(h_vsc.data(), d_vsc, h_vsc.size() * 2, cudaMemcpyDeviceToHost), "vsc"); - for (int c = 0; c < cells; ++c) - for (int h = 0; h < H; ++h) - for (int d = 0; d < D; ++d) { - const float kref = k::f32_from_f16(k::f16_from_f32( - (float) rk[((size_t) c * H + h) * D + d] * k::f32_from_f16(rk_s[((size_t) c * H + h) * G + d / k::KV_Q8_GROUP]))); - if (k::f32_from_f16(h_ksc[((size_t) c * H + h) * D + d]) != kref) ++gather_bad; - const k::block_q4_0& b = rv4[((size_t) c * H + h) * (D / 32) + d / 32]; - const int nib = d % 32 < 16 ? (b.qs[d % 32] & 0x0F) - 8 : ((b.qs[d % 32 - 16] >> 4) - 8); - const float vref = k::f32_from_f16(k::f16_from_f32((float) nib * k::f32_from_f16(b.d))); - if (k::f32_from_f16(h_vsc[((size_t) c * H + h) * D + d]) != vref) ++gather_bad; - } - std::printf("[2/3] composed gathers: %s (%d bad of %zu)\n", - gather_bad == 0 ? "PASS" : "FAIL", gather_bad, h_ksc.size()); - - // ---- attention: qsa_decode_attn KV_MODE 3 over the hybrid pools + output fwht, vs fp32 references - std::vector q((size_t) QH * D); - for (auto& x : q) x = nd(rng); - float* d_q = dalloc(q.size()); - ck(cudaMemcpy(d_q, q.data(), q.size() * 4, cudaMemcpyHostToDevice), "q"); - k::QsaAttnPools pools; - pools.k_q = d_kq; pools.k_scale = d_ks; pools.v_q4 = d_v4; pools.page_table = d_table; - float* d_scr = dalloc(k::qsa_decode_attn_scratch_floats(cells, s) + 16); - float* d_attn = dalloc((size_t) QH * D); - k::qsa_decode_attn_step(d_q, pools, d_ids, d_step, cells, s, d_scr, d_attn, nullptr); - k::fwht256_inplace_cuda(d_attn, QH, nullptr); // the engine's inverse rotation of the output - ck(cudaDeviceSynchronize(), "attn sync"); - std::vector h_attn((size_t) QH * D); - ck(cudaMemcpy(h_attn.data(), d_attn, h_attn.size() * 4, cudaMemcpyDeviceToHost), "attn"); - - // reference A: attention over the SAME dequantized K/V (isolates the kernel; fp32 host math) - // reference B: attention over the TRUE unquantized K/V (bounds the format's error) - auto host_attn = [&](const std::vector& Keq, const std::vector& Veq, std::vector& out) { - out.assign((size_t) QH * D, 0.0f); - for (int h = 0; h < QH; ++h) { - const int kvh = h / PER; - std::vector sc(cells); - float m = -1e30f; - for (int c = 0; c < cells; ++c) { - float d_ = 0.0f; - for (int t = 0; t < D; ++t) - d_ += q[(size_t) h * D + t] * Keq[((size_t) c * H + kvh) * D + t]; - sc[c] = d_ / std::sqrt((float) D); - m = std::max(m, sc[c]); - } - float l = 0.0f; - for (int c = 0; c < cells; ++c) { sc[c] = std::exp(sc[c] - m); l += sc[c]; } - for (int c = 0; c < cells; ++c) - for (int t = 0; t < D; ++t) out[(size_t) h * D + t] += sc[c] / l * Veq[((size_t) c * H + kvh) * D + t]; - } - }; - std::vector Kdq((size_t) cells * H * D), Vdq((size_t) cells * H * D); - for (int c = 0; c < cells; ++c) - for (int h = 0; h < H; ++h) - for (int d = 0; d < D; ++d) { - Kdq[((size_t) c * H + h) * D + d] = - (float) rk[((size_t) c * H + h) * D + d] * k::f32_from_f16(rk_s[((size_t) c * H + h) * G + d / k::KV_Q8_GROUP]); - const k::block_q4_0& b = rv4[((size_t) c * H + h) * (D / 32) + d / 32]; - const int nib = d % 32 < 16 ? (b.qs[d % 32] & 0x0F) - 8 : ((b.qs[d % 32 - 16] >> 4) - 8); - Vdq[((size_t) c * H + h) * D + d] = (float) nib * k::f32_from_f16(b.d); - } - // un-rotate the dequantized V (the kernel returns the output in the UNROTATED domain) - std::vector Vdq_un(Vdq.size()); - std::memcpy(Vdq_un.data(), Vdq.data(), Vdq.size() * 4); - for (int c = 0; c < cells * H; ++c) fwht256_host_reference(Vdq_un.data() + (size_t) c * D); - - // ---- batched form with TWO queries and per-query step arrays (the verify.cpp window's exact call) - { - const int nq = 2; - std::vector q2((size_t) nq * QH * D); - for (auto& x : q2) x = nd(rng); - float* d_q2 = dalloc(q2.size()); - ck(cudaMemcpy(d_q2, q2.data(), q2.size() * 4, cudaMemcpyHostToDevice), "q2"); - // the batched kernel indexes ids[z * cap + ...]: one FULL selection per query - std::vector ids2((size_t) nq * cells); - for (int i = 0; i < nq; ++i) for (int c = 0; c < cells; ++c) ids2[(size_t) i * cells + c] = c; - int32_t* d_ids2 = dalloc((size_t) nq * cells); - ck(cudaMemcpy(d_ids2, ids2.data(), ids2.size() * 4, cudaMemcpyHostToDevice), "ids2"); - int32_t* d_steps2 = dalloc(nq * k::kStepCount); - for (int i = 0; i < nq; ++i) { - int32_t st2[k::kStepCount]; - k::qsa_step_fill(st2, cells - 1 - i, s); - st2[k::kStepWidth] = cells - i; // slightly different widths, as verify's windows have - ck(cudaMemcpy(d_steps2 + i * k::kStepCount, st2, sizeof st2, cudaMemcpyHostToDevice), "steps2"); - } - float* d_scr2 = dalloc(k::qsa_decode_attn_scratch_floats(cells, s) * nq + 64); - float* d_at2 = dalloc((size_t) nq * QH * D); - k::qsa_decode_attn_batch(d_q2, pools, d_ids2, d_steps2, cells, s, d_scr2, d_at2, nq, nullptr); - k::fwht256_inplace_cuda(d_at2, (int64_t) nq * QH, nullptr); - ck(cudaDeviceSynchronize(), "attn2 sync"); - std::vector h_at2((size_t) nq * QH * D); - ck(cudaMemcpy(h_at2.data(), d_at2, h_at2.size() * 4, cudaMemcpyDeviceToHost), "at2"); - double max_b = 0.0; - double per_q[2] = {0.0, 0.0}; - for (int i = 0; i < nq; ++i) - for (int h = 0; h < QH; ++h) { - // reference over the cells this query's width selects (ids are ascending: the first width) - const int w = cells - i; - std::vector sc(w); - float m = -1e30f; - for (int c = 0; c < w; ++c) { - float d_ = 0.0f; - for (int t = 0; t < D; ++t) - d_ += q2[((size_t) i * QH + h) * D + t] * Kdq[((size_t) c * H + h / PER) * D + t]; - sc[c] = d_ / std::sqrt((float) D); - m = std::max(m, sc[c]); - } - float l = 0.0f; - for (int c = 0; c < w; ++c) { sc[c] = std::exp(sc[c] - m); l += sc[c]; } - for (int d = 0; d < D; ++d) { - float acc = 0.0f; - for (int c = 0; c < w; ++c) - acc += sc[c] / l * Vdq_un[((size_t) c * H + h / PER) * D + d]; // dim d only - const double e = (double) std::fabs(h_at2[((size_t) i * QH + h) * D + d] - acc); - max_b = std::max(max_b, e); - per_q[i] = std::max(per_q[i], e); - } - } - const bool bok = max_b < 5e-3; - std::printf(" (per-query max: q0 %.2e, q1 %.2e)\n", per_q[0], per_q[1]); - std::printf("[4/4] mode-3 BATCHED attention (verify's form): %s (vs dequant ref %.2e)\n", - bok ? "PASS" : "FAIL", max_b); - if (!bok) g_fail = 1; - } - - std::vector ref_deq, ref_true; - host_attn(Kdq, Vdq_un, ref_deq); - host_attn(K, V, ref_true); - double max_deq = 0.0, max_true = 0.0; - for (size_t i = 0; i < h_attn.size(); ++i) { - max_deq = std::max(max_deq, (double) std::fabs(h_attn[i] - ref_deq[i])); - max_true = std::max(max_true, (double) std::fabs(h_attn[i] - ref_true[i])); - } - // The tensor-core prompt path (qsa_prompt_attn, 0.1.22+) takes hybrid pools as KV_MODE 3: INT8 K, and V - // dequantized from its q4_0 blocks to fp16 at gather. Its summation order differs from the old kernel's - // (accuracy-level, not bitwise - qsa_prompt_attn.hpp says the same of its int8 mode), so: tolerance check - // against the SAME dequant reference, output un-rotated exactly as prefill.cpp does. - { - float* d_at4 = dalloc((size_t) QH * D); - const bool took = k::qsa_prompt_attn_batch(d_q, pools, d_ids, d_step, cells, s, d_at4, 1, nullptr); - if (!took) { -#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) - // AMD: the tensor-core prompt path is CUDA-only, so it refuses every pool and the old kernel runs - std::printf("[5/5] qsa_prompt_attn mode 3: PASS (refused on HIP - the old kernel runs)\n"); -#else - // below sm_70 the host refuses by design (no mma.sync) and prefill takes the batched decode kernel, - // which case [4/4] above holds to the same reference: the engine's own fallback, not a failure - int dev = 0, major = 0; - ck(cudaGetDevice(&dev), "device"); - ck(cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev), "cc"); - if (major < 7) { - std::printf("[5/5] qsa_prompt_attn mode 3: SKIP (sm_%d has no tensor-core prompt kernel; prefill runs the " - "batched decode kernel of [4/4] there)\n", major); - } else { - std::printf("[5/5] qsa_prompt_attn mode 3: FAIL (refused the hybrid pools)\n"); - g_fail = 1; - } -#endif - } else { - k::fwht256_inplace_cuda(d_at4, QH, nullptr); - ck(cudaDeviceSynchronize(), "at4 sync"); - std::vector h_at4((size_t) QH * D); - ck(cudaMemcpy(h_at4.data(), d_at4, h_at4.size() * 4, cudaMemcpyDeviceToHost), "at4"); - double max_p = 0.0; - for (size_t i = 0; i < h_at4.size(); ++i) - max_p = std::max(max_p, (double) std::fabs(h_at4[i] - ref_deq[i])); - const bool pok = max_p < 1e-2; - std::printf("[5/5] qsa_prompt_attn mode 3 (tensor cores): %s (vs dequant ref %.2e)\n", - pok ? "PASS" : "FAIL", max_p); - if (!pok) g_fail = 1; - } - } - - const bool attn_ok = max_deq < 5e-3; // fp32 kernel math vs fp64-ish host accumulation - std::printf("[3/3] mode-3 attention + output fwht: %s (vs dequant ref %.2e, vs true fp32 %.2e)\n", - attn_ok ? "PASS" : "FAIL", max_deq, max_true); - - const bool ok = append_bad == 0 && gather_bad == 0 && attn_ok && g_fail == 0; - std::printf("=== kv_hybrid_parity: %s ===\n", ok ? "ALL PASS" : "FAILED"); - return ok ? 0 : 1; -} diff --git a/src/kernels/kv_q4_parity.cpp b/src/kernels/kv_q4_parity.cpp deleted file mode 100644 index 5d6d9d3..0000000 --- a/src/kernels/kv_q4_parity.cpp +++ /dev/null @@ -1,346 +0,0 @@ -// src/kernels/kv_q4_parity.cpp - Parity test for Q4_0 KV cache with orthonormal Walsh-Hadamard rotation. -// Validates: -// 1. FWHT 256 CUDA kernel vs exact mathematical orthonormal Walsh-Hadamard transform. -// (H * H * x == x, H is symmetric and orthonormal with scale 1/sqrt(256) = 1/16). -// 2. Q4_0 quantization and packing (32 values per block, 18 bytes) bitwise vs host reference. -// 3. kv_append_q4_step and kv_gather_q4_step through paged pool against host reference. -// 4. Invariance of dot products under Walsh-Hadamard rotation: (H*q) . (H*k) == q . k. - -#include "strata/kernels/f16_bits.hpp" -#include "strata/kernels/kv_q4.hpp" -#include "strata/kernels/qsa.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace k = strata::kernels; - -namespace { - -int g_fail = 0; - -void ck(cudaError_t e, const char* w) { - if (e != cudaSuccess) { - std::fprintf(stderr, "CUDA error in %s: %s\n", w, cudaGetErrorString(e)); - std::exit(2); - } -} - -template -T* dalloc(size_t n) { - T* p = nullptr; - ck(cudaMalloc(&p, n * sizeof(T) + 64), "malloc"); - ck(cudaMemset(p, 0, n * sizeof(T) + 64), "memset"); - return p; -} - -// Exact CPU reference for Fast Walsh-Hadamard Transform (D = 256) -// Sylvester construction matching llama.cpp's ggml_gen_hadamard -void fwht256_host_reference(float* x) { - constexpr int n = 256; - for (int s = 1; s < n; s *= 2) { - for (int i = 0; i < n; i += 2 * s) { - for (int j = 0; j < s; ++j) { - const float u = x[i + j]; - const float v = x[i + j + s]; - x[i + j] = u + v; - x[i + j + s] = u - v; - } - } - } - const float scale = 1.0f / 16.0f; // 1 / sqrt(256) - for (int i = 0; i < n; ++i) { - x[i] *= scale; - } -} - -// Host reference for Q4_0 quantization of 32 elements (1 block) -void quantize_block_q4_0_host(const float* x, k::block_q4_0& blk) { - float amax = 0.0f; - float max_val = 0.0f; - for (int i = 0; i < 32; ++i) { - const float v = x[i]; - if (amax < std::fabs(v)) { - amax = std::fabs(v); - max_val = v; - } - } - const float d = max_val / -8.0f; - const float id = d != 0.0f ? 1.0f / d : 0.0f; - blk.d = k::f16_from_f32(d); - - for (int i = 0; i < 16; ++i) { - const float x0 = x[i] * id; - const float x1 = x[i + 16] * id; - const int q0 = (int) (x0 + 8.5f); - const int q1 = (int) (x1 + 8.5f); - const uint8_t xi0 = (uint8_t) std::min(15, std::max(0, q0)); - const uint8_t xi1 = (uint8_t) std::min(15, std::max(0, q1)); - blk.qs[i] = xi0 | (xi1 << 4); - } -} - -} // namespace - -int main() { - std::printf("=== Running kv_q4_parity test ===\n"); - std::mt19937 rng(42); - std::normal_distribution nd(0.0f, 1.0f); - - // ------------------------------------------------------------- - // Test 1: Orthonormal Fast Walsh-Hadamard Transform (D=256) - // ------------------------------------------------------------- - std::printf("[1/4] Verifying FWHT-256 CUDA kernel vs exact mathematical reference...\n"); - constexpr int n_vectors = 64; - std::vector h_in(n_vectors * 256); - std::vector h_ref(n_vectors * 256); - for (size_t i = 0; i < h_in.size(); ++i) { - h_in[i] = nd(rng); - } - h_ref = h_in; - - // Run CPU reference on each row - for (int r = 0; r < n_vectors; ++r) { - fwht256_host_reference(h_ref.data() + r * 256); - } - - // Run GPU kernel - float* d_src = dalloc(n_vectors * 256); - float* d_dst = dalloc(n_vectors * 256); - ck(cudaMemcpy(d_src, h_in.data(), h_in.size() * sizeof(float), cudaMemcpyHostToDevice), "memcpy H2D"); - - k::fwht256_cuda(d_src, d_dst, n_vectors, nullptr); - ck(cudaDeviceSynchronize(), "fwht256_cuda"); - - std::vector h_out(n_vectors * 256); - ck(cudaMemcpy(h_out.data(), d_dst, h_out.size() * sizeof(float), cudaMemcpyDeviceToHost), "memcpy D2H"); - - double max_fwht_diff = 0.0; - for (size_t i = 0; i < h_out.size(); ++i) { - double diff = std::fabs(h_out[i] - h_ref[i]); - if (diff > max_fwht_diff) max_fwht_diff = diff; - } - if (max_fwht_diff > 1e-5) { - std::fprintf(stderr, "FAIL: FWHT-256 GPU output differs from host reference (max diff = %e)\n", max_fwht_diff); - ++g_fail; - } else { - std::printf(" -> FWHT-256 bitwise match with host reference (max diff = %e, OK)\n", max_fwht_diff); - } - - // Self-inverse property: H * (H * x) == x - k::fwht256_inplace_cuda(d_dst, n_vectors, nullptr); - ck(cudaDeviceSynchronize(), "fwht256_inplace_cuda"); - ck(cudaMemcpy(h_out.data(), d_dst, h_out.size() * sizeof(float), cudaMemcpyDeviceToHost), "memcpy D2H"); - - double max_inv_diff = 0.0; - for (size_t i = 0; i < h_out.size(); ++i) { - double diff = std::fabs(h_out[i] - h_in[i]); - if (diff > max_inv_diff) max_inv_diff = diff; - } - if (max_inv_diff > 1e-5) { - std::fprintf(stderr, "FAIL: FWHT-256 self-inverse property failed (max diff = %e)\n", max_inv_diff); - ++g_fail; - } else { - std::printf(" -> FWHT-256 self-inverse property verified H*H*x == x (max diff = %e, OK)\n", max_inv_diff); - } - - // ------------------------------------------------------------- - // Test 2: Invariance of Attention Scores under Hadamard Rotation - // ------------------------------------------------------------- - std::printf("[2/4] Verifying Attention Score Invariance: == ...\n"); - double max_dot_diff = 0.0; - for (int r = 0; r < n_vectors; r += 2) { - const float* q = h_in.data() + r * 256; - const float* k_vec = h_in.data() + (r + 1) * 256; - const float* hq = h_ref.data() + r * 256; - const float* hk = h_ref.data() + (r + 1) * 256; - - double dot_raw = 0.0; - double dot_rot = 0.0; - for (int i = 0; i < 256; ++i) { - dot_raw += (double) q[i] * (double) k_vec[i]; - dot_rot += (double) hq[i] * (double) hk[i]; - } - double d = std::fabs(dot_raw - dot_rot); - if (d > max_dot_diff) max_dot_diff = d; - } - if (max_dot_diff > 1e-5) { - std::fprintf(stderr, "FAIL: Rotated dot product differs from original (max diff = %e)\n", max_dot_diff); - ++g_fail; - } else { - std::printf(" -> Dot product invariant under rotation: | - | = %e (OK)\n", max_dot_diff); - } - - // ------------------------------------------------------------- - // Test 3: Q4_0 Paged KV Append & Gather against Host Reference - // ------------------------------------------------------------- - std::printf("[3/4] Verifying Q4_0 KV append and gather against host reference...\n"); - k::QsaShapes s = k::qsa_real_shapes(); - s.page_size = 64; - const int H = (int) s.n_head_kv; // 2 - const int D = (int) s.head_dim; // 256 - const int P = (int) s.page_size; // 64 - const int pages = 8; - const int cells = pages * P; - - std::vector table(pages); - for (int i = 0; i < pages; ++i) table[i] = (i * 3 + 5) % pages; // permutation - int32_t* d_table = dalloc(pages); - ck(cudaMemcpy(d_table, table.data(), pages * sizeof(int32_t), cudaMemcpyHostToDevice), "memcpy table"); - - const size_t pool_bytes = (size_t) pages * H * P * k::kv_q4_bytes_per_head(D); - uint8_t* d_k_q4 = dalloc(pool_bytes); - uint8_t* d_v_q4 = dalloc(pool_bytes); - float* d_kcur = dalloc(H * D); - float* d_vcur = dalloc(H * D); - int32_t* d_step = dalloc(k::kStepCount); - - std::vector> host_k(cells), host_v(cells); - std::vector positions(cells); - for (int i = 0; i < cells; ++i) positions[i] = i; - std::shuffle(positions.begin(), positions.end(), rng); - - const int n_fill = cells - 25; // leave some cells empty - for (int n = 0; n < n_fill; ++n) { - const int pos = positions[n]; - std::vector kv(H * D), vv(H * D); - for (auto& x : kv) x = nd(rng) * 2.0f; - for (auto& x : vv) x = nd(rng) * 2.0f; - - // Apply FWHT before append - for (int h = 0; h < H; ++h) { - fwht256_host_reference(kv.data() + h * D); - fwht256_host_reference(vv.data() + h * D); - } - host_k[pos] = kv; - host_v[pos] = vv; - - int32_t hstep[k::kStepCount] = {pos, pos + 1, 0, 0}; - ck(cudaMemcpy(d_step, hstep, sizeof(hstep), cudaMemcpyHostToDevice), "memcpy step"); - ck(cudaMemcpy(d_kcur, kv.data(), kv.size() * sizeof(float), cudaMemcpyHostToDevice), "memcpy k"); - ck(cudaMemcpy(d_vcur, vv.data(), vv.size() * sizeof(float), cudaMemcpyHostToDevice), "memcpy v"); - - k::kv_append_q4_step(d_k_q4, d_v_q4, d_table, d_step, d_kcur, d_vcur, s, nullptr); - ck(cudaDeviceSynchronize(), "kv_append_q4_step"); - } - - // Verify written Q4_0 blocks bitwise against host quantizer - std::vector h_k_q4(pool_bytes), h_v_q4(pool_bytes); - ck(cudaMemcpy(h_k_q4.data(), d_k_q4, pool_bytes, cudaMemcpyDeviceToHost), "memcpy d2h k_q4"); - ck(cudaMemcpy(h_v_q4.data(), d_v_q4, pool_bytes, cudaMemcpyDeviceToHost), "memcpy d2h v_q4"); - - long bad_blocks = 0; - const int blocks_per_head = D / k::QK4_0; // 8 - const int bytes_per_head = blocks_per_head * sizeof(k::block_q4_0); // 144 - - for (int n = 0; n < n_fill; ++n) { - const int pos = positions[n]; - for (int is_v = 0; is_v < 2; ++is_v) { - for (int h = 0; h < H; ++h) { - const long long page = (long long) table[pos / P]; - const long long row = (page * H + h) * P + (pos % P); - const uint8_t* pool_ptr = (is_v ? h_v_q4.data() : h_k_q4.data()) + row * bytes_per_head; - const float* raw_vec = (is_v ? host_v[pos].data() : host_k[pos].data()) + h * D; - - for (int b = 0; b < blocks_per_head; ++b) { - k::block_q4_0 host_blk; - quantize_block_q4_0_host(raw_vec + b * 32, host_blk); - - const k::block_q4_0* gpu_blk = reinterpret_cast(pool_ptr) + b; - if (std::memcmp(&host_blk, gpu_blk, sizeof(k::block_q4_0)) != 0) { - if (bad_blocks == 0) { - std::printf("MISMATCH at n=%d, pos=%d, is_v=%d, h=%d, b=%d\n", n, pos, is_v, h, b); - std::printf(" host blk.d = 0x%04x (%f), gpu blk.d = 0x%04x (%f)\n", - host_blk.d, k::f32_from_f16(host_blk.d), - gpu_blk->d, k::f32_from_f16(gpu_blk->d)); - std::printf(" host qs: "); - for (int i = 0; i < 16; ++i) std::printf("%02x ", host_blk.qs[i]); - std::printf("\n gpu qs: "); - for (int i = 0; i < 16; ++i) std::printf("%02x ", gpu_blk->qs[i]); - std::printf("\n"); - } - ++bad_blocks; - } - } - } - } - } - if (bad_blocks > 0) { - std::fprintf(stderr, "FAIL: %ld Q4_0 blocks differ from host quantizer\n", bad_blocks); - ++g_fail; - } else { - std::printf(" -> All Q4_0 pool blocks bitwise equal to host quantizer (OK)\n"); - } - - // ------------------------------------------------------------- - // Test 4: Gather Q4_0 into FP16 Scratch and verify accuracy - // ------------------------------------------------------------- - std::printf("[4/4] Verifying Q4_0 gather unpacking and dequantization...\n"); - const int max_ids = 128; - int32_t* d_ids = dalloc(max_ids); - uint16_t* d_k_scratch = dalloc((size_t) max_ids * H * D); - uint16_t* d_v_scratch = dalloc((size_t) max_ids * H * D); - - std::vector ids(max_ids); - for (int i = 0; i < max_ids; ++i) { - ids[i] = positions[rng() % n_fill]; - } - ck(cudaMemcpy(d_ids, ids.data(), max_ids * sizeof(int32_t), cudaMemcpyHostToDevice), "memcpy ids"); - - int32_t hstep[k::kStepCount] = {0, 0, 0, max_ids}; - ck(cudaMemcpy(d_step, hstep, sizeof(hstep), cudaMemcpyHostToDevice), "memcpy step"); - - k::kv_gather_q4_step(d_k_q4, d_v_q4, d_table, d_ids, d_step, max_ids, s, d_k_scratch, d_v_scratch, nullptr); - ck(cudaDeviceSynchronize(), "kv_gather_q4_step"); - - std::vector h_k_scratch((size_t) max_ids * H * D); - std::vector h_v_scratch((size_t) max_ids * H * D); - ck(cudaMemcpy(h_k_scratch.data(), d_k_scratch, h_k_scratch.size() * sizeof(uint16_t), cudaMemcpyDeviceToHost), "memcpy d2h k_scratch"); - ck(cudaMemcpy(h_v_scratch.data(), d_v_scratch, h_v_scratch.size() * sizeof(uint16_t), cudaMemcpyDeviceToHost), "memcpy d2h v_scratch"); - - double worst_quant_err = 0.0; - for (int i = 0; i < max_ids; ++i) { - const int cell = ids[i]; - for (int is_v = 0; is_v < 2; ++is_v) { - for (int h = 0; h < H; ++h) { - const float* orig = (is_v ? host_v[cell].data() : host_k[cell].data()) + h * D; - const uint16_t* gathered = (is_v ? h_v_scratch.data() : h_k_scratch.data()) + (i * H + h) * D; - - for (int d = 0; d < D; ++d) { - float deq = k::f32_from_f16(gathered[d]); - float raw = orig[d]; - double err = std::fabs(deq - raw); - if (err > worst_quant_err) worst_quant_err = err; - } - } - } - } - std::printf(" -> Max reconstruction error after 4-bit quant + dequant: %.4f (OK)\n", worst_quant_err); - - cudaFree(d_src); - cudaFree(d_dst); - cudaFree(d_table); - cudaFree(d_k_q4); - cudaFree(d_v_q4); - cudaFree(d_kcur); - cudaFree(d_vcur); - cudaFree(d_step); - cudaFree(d_ids); - cudaFree(d_k_scratch); - cudaFree(d_v_scratch); - - if (g_fail == 0) { - std::printf("=== kv_q4_parity: ALL TESTS PASSED SUCCESSFULLY! ===\n"); - return 0; - } else { - std::fprintf(stderr, "=== kv_q4_parity: FAILED (%d failures) ===\n", g_fail); - return 1; - } -} diff --git a/src/kernels/kv_q8_parity.cpp b/src/kernels/kv_q8_parity.cpp deleted file mode 100644 index 733d7c7..0000000 --- a/src/kernels/kv_q8_parity.cpp +++ /dev/null @@ -1,141 +0,0 @@ -// src/kernels/kv_q8_parity.cpp - plan v0.3 P7: INT8 KV append/gather against a host reference (GPU, no model). -// -// Appends random K/V cells at scattered positions through a non-identity page table into both the INT8 pools -// (kv_append_q8_step) and the FP16 pools (kv_append_step), gathers random cell sets from both, and checks: -// 1. INT8 codes and FP16 scales are BITWISE equal to the host reference (same f16_from_f32 rounding); -// 2. the INT8 gather is BITWISE equal to the host dequantization of those codes; -// 3. against the FP16 path, the INT8 values differ by at most half a quantization step of their group plus the -// fp16 rounding of both sides (0.624 steps). -#include "strata/kernels/f16_bits.hpp" -#include "strata/kernels/kv_q8.hpp" -#include "strata/kernels/qsa.hpp" - -#include - -#include -#include -#include -#include -#include -#include - -namespace k = strata::kernels; - -namespace { -int g_fail = 0; -void ck(cudaError_t e, const char* w) { - if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } -} -template T* dalloc(size_t n) { T* p = nullptr; ck(cudaMalloc(&p, n * sizeof(T) + 64), "malloc"); ck(cudaMemset(p, 0, n * sizeof(T) + 64), "memset"); return p; } -} // namespace - -int main() { - k::QsaShapes s = k::qsa_real_shapes(); - s.page_size = 64; // several pages in a small pool - const int H = (int) s.n_head_kv, D = (int) s.head_dim, P = (int) s.page_size, G = D / k::KV_Q8_GROUP; - const int pages = 8, cells = pages * P; - std::mt19937 rng(17); - std::vector table(pages); - for (int i = 0; i < pages; ++i) table[i] = (i * 5 + 3) % pages; // a non-identity permutation - int32_t* d_table = dalloc(pages); - ck(cudaMemcpy(d_table, table.data(), pages * 4, cudaMemcpyHostToDevice), "table"); - int8_t *kq = dalloc((size_t) cells * H * D), *vq = dalloc((size_t) cells * H * D); - uint16_t *ks = dalloc((size_t) cells * H * G), *vs = dalloc((size_t) cells * H * G); - uint16_t *kp = dalloc((size_t) cells * H * D), *vp = dalloc((size_t) cells * H * D); - float *kcur = dalloc(H * D), *vcur = dalloc(H * D); - int32_t* step = dalloc(k::kStepCount); - std::vector> hk(cells), hv(cells); - std::normal_distribution nd(0.f, 1.f); - std::vector positions(cells); - for (int i = 0; i < cells; ++i) positions[i] = i; - std::shuffle(positions.begin(), positions.end(), rng); - const int n_fill = cells - 37; // leave some cells empty - for (int n = 0; n < n_fill; ++n) { - const int pos = positions[n]; - std::vector kv(H * D), vv(H * D); - const float scale = (n % 7 == 0) ? 1e-3f : (n % 11 == 0 ? 40.f : 1.f); // small and large groups - for (auto& x : kv) x = nd(rng) * scale; - for (auto& x : vv) x = nd(rng) * scale; - if (n % 13 == 0) std::fill(kv.begin(), kv.begin() + 64, 0.f); // an all-zero group - hk[pos] = kv; hv[pos] = vv; - int32_t hstep[k::kStepCount] = {pos, pos + 1, 0, 0}; - ck(cudaMemcpy(step, hstep, sizeof hstep, cudaMemcpyHostToDevice), "step"); - ck(cudaMemcpy(kcur, kv.data(), kv.size() * 4, cudaMemcpyHostToDevice), "k"); - ck(cudaMemcpy(vcur, vv.data(), vv.size() * 4, cudaMemcpyHostToDevice), "v"); - k::kv_append_q8_step(kq, vq, ks, vs, d_table, step, kcur, vcur, s, nullptr); - k::kv_append_step(kp, vp, d_table, step, kcur, vcur, s, nullptr); - ck(cudaDeviceSynchronize(), "append"); - } - // 1. codes and scales bitwise vs the host reference - std::vector hkq((size_t) cells * H * D), hvq(hkq.size()); - std::vector hks((size_t) cells * H * G), hvs(hks.size()); - ck(cudaMemcpy(hkq.data(), kq, hkq.size(), cudaMemcpyDeviceToHost), "d2h"); - ck(cudaMemcpy(hvq.data(), vq, hvq.size(), cudaMemcpyDeviceToHost), "d2h"); - ck(cudaMemcpy(hks.data(), ks, hks.size() * 2, cudaMemcpyDeviceToHost), "d2h"); - ck(cudaMemcpy(hvs.data(), vs, hvs.size() * 2, cudaMemcpyDeviceToHost), "d2h"); - long bad_codes = 0; - for (int n = 0; n < n_fill; ++n) { - const int pos = positions[n]; - for (int kvsel = 0; kvsel < 2; ++kvsel) - for (int h = 0; h < H; ++h) - for (int g = 0; g < G; ++g) { - const float* x = (kvsel ? hv[pos] : hk[pos]).data() + h * D + g * 64; - float amax = 0.f; - for (int t = 0; t < 64; ++t) amax = std::fmax(amax, std::fabs(x[t])); - const uint16_t sb = k::f16_from_f32(amax / 127.0f); - const float sf = k::f32_from_f16(sb); - const long long row = ((long long) table[pos / P] * H + h) * P + pos % P; - if ((kvsel ? hvs : hks)[row * G + g] != sb) ++bad_codes; - for (int t = 0; t < 64; ++t) { - int q = sf > 0.f ? (int) std::nearbyint(x[t] / sf) : 0; - q = std::clamp(q, -127, 127); - if ((kvsel ? hvq : hkq)[row * D + g * 64 + t] != (int8_t) q) ++bad_codes; - } - } - } - if (bad_codes) { std::fprintf(stderr, "FAIL: %ld codes/scales differ from the host reference\n", bad_codes); ++g_fail; } - // 2 + 3. gather random selections from both paths - const int max_ids = 200; - int32_t* d_ids = dalloc(max_ids); - uint16_t *k8 = dalloc((size_t) max_ids * H * D), *v8 = dalloc((size_t) max_ids * H * D); - uint16_t *k16 = dalloc((size_t) max_ids * H * D), *v16 = dalloc((size_t) max_ids * H * D); - double worst = 0.0; - for (int trial = 0; trial < 20; ++trial) { - const int n_ids = 1 + (int) (rng() % max_ids); - std::vector ids(n_ids); - for (auto& id : ids) id = positions[rng() % n_fill]; - ck(cudaMemcpy(d_ids, ids.data(), n_ids * 4, cudaMemcpyHostToDevice), "ids"); - int32_t hstep[k::kStepCount] = {0, 0, 0, n_ids}; - ck(cudaMemcpy(step, hstep, sizeof hstep, cudaMemcpyHostToDevice), "step"); - k::kv_gather_q8_step(kq, vq, ks, vs, d_table, d_ids, step, max_ids, s, k8, v8, nullptr); - k::kv_gather_step(kp, vp, d_table, d_ids, step, max_ids, s, k16, v16, nullptr); - ck(cudaDeviceSynchronize(), "gather"); - std::vector a8((size_t) n_ids * H * D), b8(a8.size()), a16(a8.size()), b16(a8.size()); - ck(cudaMemcpy(a8.data(), k8, a8.size() * 2, cudaMemcpyDeviceToHost), "d2h"); - ck(cudaMemcpy(b8.data(), v8, b8.size() * 2, cudaMemcpyDeviceToHost), "d2h"); - ck(cudaMemcpy(a16.data(), k16, a16.size() * 2, cudaMemcpyDeviceToHost), "d2h"); - ck(cudaMemcpy(b16.data(), v16, b16.size() * 2, cudaMemcpyDeviceToHost), "d2h"); - for (int j = 0; j < n_ids; ++j) - for (int h = 0; h < H; ++h) { - const long long row = ((long long) table[ids[j] / P] * H + h) * P + ids[j] % P; - for (int d = 0; d < D; ++d) { - const size_t o = ((size_t) j * H + h) * D + d; - for (int kvsel = 0; kvsel < 2; ++kvsel) { - const float sf = k::f32_from_f16((kvsel ? hvs : hks)[row * G + d / 64]); - const int8_t q = (kvsel ? hvq : hkq)[row * D + d]; - const uint16_t want = k::f16_from_f32((float) q * sf); - const uint16_t got = (kvsel ? b8 : a8)[o]; - if (got != want) { if (g_fail < 5) std::fprintf(stderr, "FAIL: gather id %d h %d d %d\n", j, h, d); ++g_fail; } - const float ref = k::f32_from_f16((kvsel ? b16 : a16)[o]); - const double err = std::fabs(k::f32_from_f16(got) - ref) / (sf > 0 ? sf : 1.0); - worst = std::max(worst, err); - } - } - } - } - // |x - q*sf| <= sf/2 (the stored scale keeps |x|/sf <= 127.06, so no clamping), plus the fp16 rounding of each - // side: at most 2^-11 relative of a value up to 127*sf, i.e. 127/2048 = 0.062 steps each -> 0.5 + 0.124 - if (!(worst <= 0.5 + 2.0 * 127.0 / 2048.0 + 1e-3)) { std::fprintf(stderr, "FAIL: INT8 vs FP16 error %.3f steps\n", worst); ++g_fail; } - std::printf("kv_q8_parity: %s (worst INT8-vs-FP16 error %.3f quantization steps)\n", g_fail ? "FAILED" : "OK", worst); - return g_fail ? 1 : 0; -} diff --git a/src/kernels/kv_stream_parity.cpp b/src/kernels/kv_stream_parity.cpp deleted file mode 100644 index 0755734..0000000 --- a/src/kernels/kv_stream_parity.cpp +++ /dev/null @@ -1,234 +0,0 @@ -// src/kernels/kv_stream_parity.cpp - KV streaming (kv_stream.hpp) against a fully resident pool (GPU, no model). -// -// Decodes a synthetic sequence twice: into a fully resident pool with the identity page table, and into a streamed -// layer (host copy + a small VRAM slot pool that must evict constantly). Every few cells a batch of 1-8 queries -// with selections shaped like the indexer's (whole 4-cell blocks, a partial threshold block, the tail block, half of -// them recent) is attended in both; `kv_stream_resolve` runs before the streamed attention. Checks: -// 1. the attention outputs are BITWISE equal (the streamed readers see exactly the resident values); -// 2. the residency map is consistent after every call (slot_block and page_table invert each other); -// 3. no call overflowed, and the hit/miss counters add up; -// 4. a ring (the MTP drafter's layout) restored from the host copy reads the same values as the resident pool. -// INT8, FP16 and Q4_0 (PR #21) pools. -#include "strata/kernels/kv_q4.hpp" -#include "strata/kernels/kv_q8.hpp" -#include "strata/kernels/kv_stream.hpp" -#include "strata/kernels/qsa.hpp" -#include "strata/kernels/qsa_decode_attn.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace k = strata::kernels; - -namespace { -int g_fail = 0; -void ck(cudaError_t e, const char* w) { - if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } -} -template T* dalloc(size_t n) { - T* p = nullptr; - ck(cudaMalloc(&p, n * sizeof(T) + 64), "malloc"); - ck(cudaMemset(p, 0, n * sizeof(T) + 64), "memset"); - return p; -} -template T* halloc(size_t n) { // pinned, mapped; returns the device pointer - void* h = nullptr; - void* d = nullptr; - ck(cudaHostAlloc(&h, n * sizeof(T) + 64, cudaHostAllocMapped), "hostalloc"); - std::memset(h, 0, n * sizeof(T) + 64); - ck(cudaHostGetDevicePointer(&d, h, 0), "devptr"); - return (T*) d; -} - -struct Pools { // one K/V pool set of `pages` pages - k::KvHostPools p; // reused as a plain pointer bundle - void alloc(int64_t pages, const k::QsaShapes& s, int fmt, bool host) { - const size_t rows = (size_t) pages * s.n_head_kv * s.page_size; - if (fmt == k::kKvQ4) { - const size_t b = rows * k::kv_q4_bytes_per_head((int) s.head_dim); - p.k_q4 = host ? halloc(b) : dalloc(b); - p.v_q4 = host ? halloc(b) : dalloc(b); - } else if (fmt == k::kKvInt8) { - p.k_q = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); - p.v_q = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); - p.k_scale = host ? halloc(rows * 4) : dalloc(rows * 4); - p.v_scale = host ? halloc(rows * 4) : dalloc(rows * 4); - } else { - p.k_pool = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); - p.v_pool = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); - } - } - k::QsaAttnPools attn(const int32_t* table) const { - k::QsaAttnPools a; - a.k_pool = p.k_pool; a.v_pool = p.v_pool; a.k_q = p.k_q; a.v_q = p.v_q; a.k_scale = p.k_scale; - a.v_scale = p.v_scale; a.k_q4 = p.k_q4; a.v_q4 = p.v_q4; a.page_table = table; - return a; - } -}; - -void append(const Pools& pl, const int32_t* table, const int32_t* step, const float* kc, const float* vc, - const k::QsaShapes& s, int fmt, const k::KvHostPools* host) { - if (fmt == k::kKvQ4) k::kv_append_q4_step(pl.p.k_q4, pl.p.v_q4, table, step, kc, vc, s, nullptr, host); - else if (fmt == k::kKvInt8) k::kv_append_q8_step(pl.p.k_q, pl.p.v_q, pl.p.k_scale, pl.p.v_scale, table, step, kc, vc, s, nullptr, host); - else k::kv_append_step(pl.p.k_pool, pl.p.v_pool, table, step, kc, vc, s, nullptr, host); -} - -// A selection like qsa_block_topk's: ascending cells, whole blocks, the tail block's cells, and one partial block. -std::vector selection(int64_t n_kv, int64_t width, std::mt19937& rng) { - std::vector ids; - if (n_kv <= width) { - for (int64_t c = 0; c < n_kv; ++c) ids.push_back((int32_t) c); - return ids; - } - const int64_t n_bid = n_kv / 4, tail = n_kv - n_bid * 4; - std::set blocks; - const int64_t want_full = (width - tail) / 4, part = (width - tail) % 4; - std::uniform_int_distribution any(0, n_bid - 1), recent(std::max(0, n_bid - 2048), n_bid - 1); - while ((int64_t) blocks.size() < want_full + (part ? 1 : 0)) blocks.insert(rng() % 2 ? recent(rng) : any(rng)); - int64_t partial_block = part ? *std::next(blocks.begin(), (long) (rng() % blocks.size())) : -1; - for (int64_t b : blocks) { - const int64_t take = b == partial_block ? part : 4; - for (int64_t i = 0; i < take; ++i) ids.push_back((int32_t) (b * 4 + i)); - } - for (int64_t c = n_bid * 4; c < n_kv; ++c) ids.push_back((int32_t) c); - std::sort(ids.begin(), ids.end()); - return ids; -} - -bool run(int fmt) { - const char* name = fmt == k::kKvQ4 ? "q4_0" : fmt == k::kKvInt8 ? "int8" : "fp16"; - k::QsaShapes s = k::qsa_real_shapes(); - const int64_t N = 40000, n_blocks = (N + 3) / 4, n_slots = 8 * 516 + 700; // must evict: slots < blocks - const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s), NQ = 8; - const int64_t H = s.n_head_kv, D = s.head_dim, NH = s.n_head; - std::mt19937 rng(7 + 4 * fmt); - std::normal_distribution nd(0.f, 1.f); - - Pools ref, slots, host; - ref.alloc(n_blocks, s, fmt, false); - slots.alloc(n_slots, s, fmt, false); - host.alloc(n_blocks, s, fmt, true); - int32_t* ident = dalloc(n_blocks); - { - std::vector t(n_blocks); - for (int64_t i = 0; i < n_blocks; ++i) t[i] = (int32_t) i; - ck(cudaMemcpy(ident, t.data(), n_blocks * 4, cudaMemcpyHostToDevice), "ident"); - } - k::KvStreamMap m; - m.page_table = dalloc(n_blocks); - m.slot_block = dalloc(n_slots); m.slot_stamp = dalloc(n_slots); m.slot_ref = dalloc(n_slots); - m.miss_block = dalloc(n_slots); m.miss_slot = dalloc(n_slots); - m.ctl = dalloc(k::kKvCtlInts); - m.n_blocks = n_blocks; m.n_slots = n_slots; - k::kv_stream_reset(m, nullptr); - - float* kc = dalloc(H * D); - float* vc = dalloc(H * D); - int32_t* step = dalloc(k::kStepCount); - int32_t* steps = dalloc(NQ * k::kStepCount); - int32_t* ids = dalloc(NQ * cap); - float* q = dalloc(NQ * NH * D); - const uint64_t scr = k::qsa_decode_attn_scratch_floats(cap, s); - float* scratch = dalloc(NQ * scr); - float* out_ref = dalloc(NQ * NH * D); - float* out_str = dalloc(NQ * NH * D); - std::vector hk(H * D), hv(H * D), hq(NQ * NH * D), a((size_t) NQ * NH * D), b2((size_t) NQ * NH * D); - std::vector pt(n_blocks), sb(n_slots); - - int batches = 0, bad = 0; - for (int64_t pos = 0; pos < N; ++pos) { - for (auto& x : hk) x = nd(rng) * ((pos % 17 == 0) ? 30.f : 1.f); - for (auto& x : hv) x = nd(rng); - const int32_t st[4] = {(int32_t) pos, (int32_t) (pos + 1), (int32_t) ((pos + 1) / 4), 0}; - ck(cudaMemcpy(kc, hk.data(), hk.size() * 4, cudaMemcpyHostToDevice), "k"); - ck(cudaMemcpy(vc, hv.data(), hv.size() * 4, cudaMemcpyHostToDevice), "v"); - ck(cudaMemcpy(step, st, sizeof(st), cudaMemcpyHostToDevice), "step"); - append(ref, ident, step, kc, vc, s, fmt, nullptr); - append(slots, m.page_table, step, kc, vc, s, fmt, &host.p); - if (pos % 131 != 130 && pos != N - 1) continue; - // a batch: n_q queries at the last n_q positions (as a verify window), each with its own selection - const int n_q = 1 + (int) (rng() % NQ); - std::vector hids((size_t) NQ * cap, 0), hst(NQ * 4, 0); - for (int t = 0; t < n_q; ++t) { - const int64_t p = std::max(0, pos - (n_q - 1 - t)), n_kv = p + 1; - const int64_t width = std::min(n_kv, cap); - const std::vector sel = selection(n_kv, width, rng); - if ((int64_t) sel.size() != width) { std::fprintf(stderr, "selection size %zu != %lld\n", sel.size(), (long long) width); return false; } - std::copy(sel.begin(), sel.end(), hids.begin() + (size_t) t * cap); - hst[t * 4 + 0] = (int32_t) p; hst[t * 4 + 1] = (int32_t) n_kv; hst[t * 4 + 2] = (int32_t) (n_kv / 4); - hst[t * 4 + 3] = (int32_t) width; - } - for (auto& x : hq) x = nd(rng); - ck(cudaMemcpy(ids, hids.data(), hids.size() * 4, cudaMemcpyHostToDevice), "ids"); - ck(cudaMemcpy(steps, hst.data(), hst.size() * 4, cudaMemcpyHostToDevice), "steps"); - ck(cudaMemcpy(q, hq.data(), hq.size() * 4, cudaMemcpyHostToDevice), "q"); - k::qsa_decode_attn_batch(q, ref.attn(ident), ids, steps, cap, s, scratch, out_ref, n_q, nullptr); - k::kv_stream_resolve(m, slots.attn(m.page_table), host.p, fmt, ids, steps, n_q, cap, s, nullptr); - k::qsa_decode_attn_batch(q, slots.attn(m.page_table), ids, steps, cap, s, scratch, out_str, n_q, nullptr); - ck(cudaDeviceSynchronize(), "batch"); - ck(cudaMemcpy(a.data(), out_ref, (size_t) n_q * NH * D * 4, cudaMemcpyDeviceToHost), "a"); - ck(cudaMemcpy(b2.data(), out_str, (size_t) n_q * NH * D * 4, cudaMemcpyDeviceToHost), "b"); - if (std::memcmp(a.data(), b2.data(), (size_t) n_q * NH * D * 4) != 0) { - if (bad++ < 5) std::fprintf(stderr, " %s pos %lld n_q %d: streamed attention differs\n", name, (long long) pos, n_q); - } - // the map inverts itself - ck(cudaMemcpy(pt.data(), m.page_table, n_blocks * 4, cudaMemcpyDeviceToHost), "pt"); - ck(cudaMemcpy(sb.data(), m.slot_block, n_slots * 4, cudaMemcpyDeviceToHost), "sb"); - int64_t resident = 0; - for (int64_t bk = 0; bk < n_blocks; ++bk) { - if (pt[bk] < -1 || pt[bk] >= n_slots || (pt[bk] >= 0 && sb[pt[bk]] != bk)) { - if (bad++ < 5) std::fprintf(stderr, " map broken at block %lld (table %d)\n", (long long) bk, pt[bk]); - break; - } - resident += pt[bk] >= 0; - } - for (int64_t sl = 0; sl < n_slots; ++sl) - if (sb[sl] >= 0 && pt[sb[sl]] != sl) { if (bad++ < 5) std::fprintf(stderr, " slot %lld not in the table\n", (long long) sl); break; } - ++batches; - } - const k::KvStreamCounters c = k::kv_stream_counters(m); - std::printf(" %s: %d batches, %llu block lookups, %llu misses (%.1f%% hit), overflow %d, %d failures\n", - name, batches, (unsigned long long) c.lookups, (unsigned long long) c.misses, - c.lookups ? 100.0 * (double) (c.lookups - c.misses) / (double) c.lookups : 0.0, (int) c.overflow, bad); - if (c.overflow || c.calls != (uint64_t) batches || c.misses == 0 || c.misses >= c.lookups) ++bad; - - // 4. a ring over the same host copy: blocks [b1 - R, b1) restored, read through `b % R` - { - const int64_t R = 1500, b1 = n_blocks, b0 = b1 - R; - Pools ring; - ring.alloc(R, s, fmt, false); - int32_t* rt = dalloc(n_blocks); - k::kv_ring_table(rt, n_blocks, R, nullptr); - k::kv_ring_restore(ring.attn(rt), host.p, fmt, b0, b1, R, s, nullptr); - const int64_t width = cap; - std::vector hids((size_t) cap), hst = {(int32_t) (N - 1), (int32_t) N, (int32_t) (N / 4), (int32_t) width}; - for (int64_t i = 0; i < width; ++i) hids[i] = (int32_t) (N - width + i); // the window's last cells - ck(cudaMemcpy(ids, hids.data(), hids.size() * 4, cudaMemcpyHostToDevice), "ids"); - ck(cudaMemcpy(steps, hst.data(), 16, cudaMemcpyHostToDevice), "steps"); - k::qsa_decode_attn_batch(q, ref.attn(ident), ids, steps, cap, s, scratch, out_ref, 1, nullptr); - k::qsa_decode_attn_batch(q, ring.attn(rt), ids, steps, cap, s, scratch, out_str, 1, nullptr); - ck(cudaDeviceSynchronize(), "ring"); - ck(cudaMemcpy(a.data(), out_ref, (size_t) NH * D * 4, cudaMemcpyDeviceToHost), "a"); - ck(cudaMemcpy(b2.data(), out_str, (size_t) NH * D * 4, cudaMemcpyDeviceToHost), "b"); - const bool ok = std::memcmp(a.data(), b2.data(), (size_t) NH * D * 4) == 0; - std::printf(" %s ring restore: %s\n", name, ok ? "identical" : "DIFFERS"); - if (!ok) ++bad; - } - return bad == 0; -} -} // namespace - -int main() { - std::printf("kv_stream_parity: streamed vs resident KV, bitwise\n"); - const bool a = run(k::kKvInt8), b = run(k::kKvF16), c = run(k::kKvQ4); - if (!a || !b || !c) ++g_fail; - std::printf(g_fail ? "FAIL\n" : "PASS\n"); - return g_fail ? 1 : 0; -} diff --git a/src/kernels/mmvq_multi_parity.cpp b/src/kernels/mmvq_multi_parity.cpp deleted file mode 100644 index fd921d3..0000000 --- a/src/kernels/mmvq_multi_parity.cpp +++ /dev/null @@ -1,263 +0,0 @@ -// src/kernels/mmvq_multi_parity.cpp - the multi_exact contract of native_mmvq, tested bitwise. -// -// build/mmvq_multi_parity -// -// WHY IT EXISTS. `include/strata/kernels/native_mmvq.hpp` says of `native_mmvq_set_multi_exact`: -// -// "true (default): the ncols == 1 layout, every column bitwise equal to a single-column call" -// -// and `include/strata/core/verify.hpp` counts "multi-column MMVQ in exact mode" among the reasons the verify window -// produces what greedy decode would, bit for bit. Nothing tested that sentence: `iq_parity` calls `native_mmvq` -// with two columns and compares against a float64 reference at 2e-2, which cannot see a difference between one -// column and T columns. -// -// WHAT IT COMPARES. The SAME Q8_1 bytes: one T-column call against T single-column calls, each reading column j -// from the same buffer (the header: "its Q8_1 blocks at j * n_in / 32"). The quantization is shared, so the only -// thing under test is how the columns are laid out. -// -// THE DATA. The weights are random bytes, except each block's fp16 scales (`d`, and `dmin` where the format has -// one), which are rewritten as normal fp16 values in +-[2^-10, 2^-5): random bytes there would put inf and NaN in -// the outputs, and on the GPU every NaN comes out as the same canonical bit pattern, so a NaN output compares equal -// whatever operations produced it and proves nothing. With finite scales and finite normal activations (the -// precondition the header puts on the input) every output is finite, and a non-finite one fails the test. -// -// THE NEGATIVE CONTROL. The same comparison with `multi_exact` off must find differences, or the test has no power -// and its pass means nothing. Where it has power depends on T: in `native_mmvq.cu` the generic layout uses -// `NW = NCOLS <= 4 ? 4 : 2` warps, and with `WARPS = 4` and `BPI = F::BPI * NW / WARPS` it coincides with the -// exact layout at T <= 4. So the control is ASSERTED on T > 4 for every case, and at T <= 4 its silence is -// reported as that coincidence rather than skipped. The control needs a row long enough for the two layouts to -// group blocks differently: IQ4_XS takes 16 blocks per iteration with 4 warps and 8 with 2, so at n_in = 2048 (8 -// blocks of 256) each thread holds at most one block in both layouts and they coincide; its case uses n_in = 4096. -#include "strata/kernels/iq_kernels.hpp" -#include "strata/kernels/native_mmvq.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { - -struct Case { - const char* name; - int type; // stable GGML type id, from the list in native_mmvq.hpp - int n_in; - int n_out; - int block_elems; // elements per weight block - int block_bytes; - int scale_at[2]; // byte offsets of the block's fp16 scales in native_mmvq.cu's block structs; -1 = none -}; - -// the types a head or a projection can have in this model -const Case CASES[] = { - {"Q4_0", 2, 2048, 512, 32, 18, {0, -1}}, // Q40Block: half d - {"Q8_0", 8, 2048, 512, 32, 34, {0, -1}}, // Q80Block: half d - {"Q4_K", 12, 2048, 512, 256, 144, {0, 2}}, // Q4KBlock: half2 dm - {"Q5_K", 13, 2048, 512, 256, 176, {0, 2}}, // Q5KBlock: half2 dm - {"Q6_K", 14, 2048, 512, 256, 210, {208, -1}}, // Q6KBlock: half d after ql, qh, scales - {"IQ4_XS", 23, 4096, 512, 256, 136, {0, -1}}, // IQ4XSBlock: half d; n_in 4096, see THE NEGATIVE CONTROL - {"Q5_K wide", 13, 4096, 2048, 256, 176, {0, 2}}, -}; - -// a normal fp16 in +-[2^-10, 2^-5): exponent field 5..9 (bias 15), any mantissa, either sign -uint16_t sane_half(std::mt19937& rng) { - const uint32_t r = rng(); - return (uint16_t) (((r >> 31) << 15) | ((5u + (r >> 10) % 5u) << 10) | (r & 0x3ffu)); -} - -// T = 4 is the last width where the two layouts coincide, T = 5 the first where they differ -const int WIDTHS[] = {1, 2, 3, 4, 5, 6, 8}; -constexpr int COINCIDE_MAX_T = 4; - -bool ck(cudaError_t e, const char* what) { - if (e == cudaSuccess) return true; - std::printf("CUDA: %s: %s\n", what, cudaGetErrorString(e)); - return false; -} - -// Returns the number of outputs that differ bit for bit; counts the non-finite outputs and the differences on -// outputs that are finite in both paths. -long long compare(const Case& c, int T, cudaStream_t s, long long& nonfinite, long long& diff_finite, bool& ran) { - ran = false; - if (!strata::kernels::native_mmvq_supported(c.type)) return -1; - - const std::size_t wbytes = strata::kernels::native_mmvq_weight_bytes(c.type, c.n_in, c.n_out); - const std::size_t qcol = strata::kernels::native_q8_1_bytes(c.n_in, 1); // Q8_1 bytes of ONE column - const std::size_t qall = strata::kernels::native_q8_1_bytes(c.n_in, T); - if (qall != qcol * (std::size_t) T) { - std::printf("%-12s T=%d: the Q8_1 bytes of T columns (%zu) are not T times those of one (%zu): the test " - "assumes contiguous columns and they are not\n", c.name, T, qall, qcol); - return -1; - } - - std::mt19937 rng(1234u + (unsigned) c.type * 97u + (unsigned) T); - std::vector w(wbytes); - for (auto& b : w) b = (uint8_t) (rng() & 0xff); - const std::size_t n_blocks = (std::size_t) c.n_out * (std::size_t) (c.n_in / c.block_elems); - if (n_blocks * (std::size_t) c.block_bytes != wbytes) { - std::printf("%-12s T=%d: %zu blocks of %d bytes are not the %zu weight bytes native_mmvq expects\n", c.name, - T, n_blocks, c.block_bytes, wbytes); - return -1; - } - for (std::size_t k = 0; k < n_blocks; ++k) - for (int at : c.scale_at) - if (at >= 0) { - const uint16_t h = sane_half(rng); - std::memcpy(&w[k * (std::size_t) c.block_bytes + (std::size_t) at], &h, 2); - } - std::vector x((std::size_t) T * c.n_in); - std::normal_distribution nd(0.f, 1.f); - for (auto& v : x) v = nd(rng); - - void* dw = nullptr; - void* xq = nullptr; - float* dx = nullptr; - float* dmulti = nullptr; - float* dsingle = nullptr; - const std::size_t ybytes = (std::size_t) T * c.n_out * 4; - if (!ck(cudaMalloc(&dw, wbytes), "malloc w") || !ck(cudaMalloc(&xq, qall), "malloc xq") || - !ck(cudaMalloc(&dx, x.size() * 4), "malloc x") || !ck(cudaMalloc(&dmulti, ybytes), "malloc multi") || - !ck(cudaMalloc(&dsingle, ybytes), "malloc single")) - return -1; - if (!ck(cudaMemcpy(dw, w.data(), wbytes, cudaMemcpyHostToDevice), "copy w") || - !ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "copy x")) - return -1; - - // ONE quantization, shared by both paths: the quantization is not under test - strata::kernels::quantize_q8_1_rows(dx, T, c.n_in, xq, s); - if (!ck(cudaStreamSynchronize(s), "quantize")) return -1; - - try { - strata::kernels::native_mmvq(c.type, dw, xq, dmulti, c.n_in, c.n_out, T, s); - for (int j = 0; j < T; ++j) - strata::kernels::native_mmvq(c.type, dw, (const uint8_t*) xq + (std::size_t) j * qcol, - dsingle + (std::size_t) j * c.n_out, c.n_in, c.n_out, 1, s); - } catch (const std::exception& e) { - std::printf("%-12s T=%d: %s\n", c.name, T, e.what()); - return -1; - } - if (!ck(cudaStreamSynchronize(s), "mmvq")) return -1; - - std::vector a((std::size_t) T * c.n_out), b(a.size()); - if (!ck(cudaMemcpy(a.data(), dmulti, ybytes, cudaMemcpyDeviceToHost), "read multi") || - !ck(cudaMemcpy(b.data(), dsingle, ybytes, cudaMemcpyDeviceToHost), "read single")) - return -1; - - long long diff = 0; - nonfinite = 0; - diff_finite = 0; - for (std::size_t i = 0; i < a.size(); ++i) { - float fa, fb; - std::memcpy(&fa, &a[i], 4); - std::memcpy(&fb, &b[i], 4); - const bool both_finite = std::isfinite(fa) && std::isfinite(fb); - if (!both_finite) ++nonfinite; - if (a[i] != b[i]) { - ++diff; - if (both_finite) ++diff_finite; - } - } - cudaFree(dw); cudaFree(xq); cudaFree(dx); cudaFree(dmulti); cudaFree(dsingle); - ran = true; - return diff; -} - -struct Totals { - long long checked = 0, diff = 0, diff_finite = 0, nonfinite = 0; // all widths - long long diff_finite_wide = 0; // T > COINCIDE_MAX_T only - int powerless_cases = 0; // cases where the control found no difference at any T > COINCIDE_MAX_T -}; - -int sweep(bool exact, cudaStream_t s, Totals& t) { - strata::kernels::native_mmvq_set_multi_exact(exact); - if (strata::kernels::native_mmvq_multi_exact() != exact) { - std::printf("native_mmvq_multi_exact() does not reflect what was set\n"); - return 1; - } - std::printf("\n=== multi_exact %s ===\n", exact ? "ON (the default)" : "off (negative control)"); - std::printf("%-12s %3s %10s %10s %14s %10s\n", "type", "T", "outputs", "bits diff", "finite diff", "nonfinite"); - int bad = 0; - for (const Case& c : CASES) { - long long case_wide = 0; - for (int T : WIDTHS) { - long long nf = 0, dfin = 0; - bool ran = false; - const long long diff = compare(c, T, s, nf, dfin, ran); - if (!ran) { ++bad; continue; } - const long long n = (long long) T * c.n_out; - t.checked += n; - t.diff += diff; - t.diff_finite += dfin; - t.nonfinite += nf; - if (T > COINCIDE_MAX_T) { t.diff_finite_wide += dfin; case_wide += dfin; } - const char* verdict; - if (exact) verdict = diff == 0 ? "ok" : "FAIL"; - else if (dfin > 0) verdict = "control sees it"; - else verdict = T <= COINCIDE_MAX_T ? "layouts coincide here (NW = 4)" : "no power at this T"; - std::printf("%-12s %3d %10lld %10lld %14lld %10lld %s\n", c.name, T, n, diff, dfin, nf, verdict); - if (exact && diff != 0) ++bad; - } - if (!exact && case_wide == 0) ++t.powerless_cases; - } - return bad; -} - -} // namespace - -int main() { - cudaStream_t s; - if (!ck(cudaStreamCreate(&s), "stream create")) return 1; - - Totals on, off; - const int bad = sweep(true, s, on); - const int bad_off = sweep(false, s, off); - strata::kernels::native_mmvq_set_multi_exact(true); // back to the default - - std::printf("\nmulti_exact on: %lld outputs compared, %lld differ bitwise, %lld non-finite\n", - on.checked, on.diff, on.nonfinite); - std::printf("multi_exact off: %lld outputs compared, %lld differ bitwise (%lld on finite outputs, %lld at T > %d)\n", - off.checked, off.diff, off.diff_finite, off.diff_finite_wide, COINCIDE_MAX_T); - - if (on.nonfinite != 0 || off.nonfinite != 0) { - std::printf("\nmmvq_multi_parity: FAILED. %lld non-finite outputs from finite scales and activations: the " - "bit comparison is only meaningful on finite outputs.\n", on.nonfinite + off.nonfinite); - return 1; - } - if (bad != 0 || bad_off != 0) { - std::printf("\nmmvq_multi_parity: FAILED. %d case(s) with multi_exact on differ from single-column calls " - "or did not run, %d case(s) did not run with it off. If they differ, the sentence in " - "native_mmvq.hpp does not hold, and neither does the bit-exactness verify.hpp claims.\n", - bad, bad_off); - return 1; - } - // THE NEGATIVE CONTROL, asserted where it can see something: past T = 4 the generic layout is a different one, - // so if it still finds no difference the comparison cannot tell the layouts apart and the pass proves nothing. -#if defined(STRATA_HIP_GFX906) - // gfx906: the wave64 layout (one wavefront per row) is the same kernel for every column count, so multi_exact - // has nothing to switch and the control cannot see a difference. The control with power is the CUDA layout: - // ctest's mmvq_multi_parity_cuda_layout runs this with STRATA_MMVQ_WAVE=0. - if (off.powerless_cases != 0 && !(std::getenv("STRATA_MMVQ_WAVE") && std::string(std::getenv("STRATA_MMVQ_WAVE")) == "0")) { - std::printf("\nmmvq_multi_parity: ok (gfx906 wave64 layout: every column count runs the same exact kernel, " - "so the negative control has no other layout to find; mmvq_multi_parity_cuda_layout checks it).\n"); - return 0; - } -#endif - if (off.powerless_cases != 0) { - std::printf("\nmmvq_multi_parity: FAILED (no power). In %d case(s) no output differs with multi_exact off at " - "any T > %d, where the generic layout is not the exact one: for those cases this comparison " - "cannot tell the two layouts apart, so their pass above proves nothing.\n", off.powerless_cases, - COINCIDE_MAX_T); - return 1; - } - std::printf("\nmmvq_multi_parity: ok. With multi_exact on every column is bitwise equal to a single-column " - "call; with it off the control finds differences at T > %d in every case, so the comparison has " - "power.\n", - COINCIDE_MAX_T); - return 0; -} diff --git a/src/kernels/native_expert_bench.cpp b/src/kernels/native_expert_bench.cpp deleted file mode 100644 index 7f16e22..0000000 --- a/src/kernels/native_expert_bench.cpp +++ /dev/null @@ -1,170 +0,0 @@ -// src/kernels/native_expert_bench.cpp - the grouped native experts on real GGUF rows: one AMD layout against -// another, bit for bit, and each one's time. -// -// build/native_expert_bench [iters] -// -// Modes are STRATA_EXP_MODE values. A group is one expert (distinct blobs, ~2 MB each, so G >= 8 does not fit -// in L2); its entries read distinct tokens of an 8-token window. The output must be bitwise equal to the -// reference mode's: the verify window's text depends on it. -#include "strata/artifact/gguf_reader.hpp" -#include "strata/kernels/cpu/native_expert.hpp" -#include "strata/kernels/iq_kernels.hpp" - -#include "ggml.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace cpu = strata::kernels::cpu; -namespace K = strata::kernels; - -int main(int argc, char** argv) { - setvbuf(stdout, nullptr, _IONBF, 0); - if (argc < 7) { - std::fprintf(stderr, "usage: native_expert_bench [iters]\n"); - return 2; - } - strata::GgufFile gguf(argv[1]); - std::vector layers; - { - std::stringstream ss(argv[2]); - std::string t; - while (std::getline(ss, t, ',')) layers.push_back(std::atoi(t.c_str())); - } - const int G = std::atoi(argv[3]), T = std::atoi(argv[4]), mref = std::atoi(argv[5]), mode = std::atoi(argv[6]); - const int iters = argc > 7 ? std::atoi(argv[7]) : 200; - const int NTOK = 8; - if (T < 1 || T > NTOK || G < 1) { std::fprintf(stderr, "tokens 1..8, groups >= 1\n"); return 2; } - const int64_t H = 2560, FF_FULL = 640, FF = FF_FULL; // Flash-Next's expert geometry - int failures = 0; - cudaStream_t s; - cudaStreamCreate(&s); - cudaEvent_t e0, e1; - cudaEventCreate(&e0); - cudaEventCreate(&e1); - for (int l : layers) { - const strata::TensorInfo* t[3] = {}; - const char* roles[3] = {"gate", "up", "down"}; - for (const auto& ti : gguf.tensors()) - for (int r = 0; r < 3; ++r) - if (ti.name == "blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight") t[r] = &ti; - if (!t[0] || !t[1] || !t[2]) { std::printf("layer %d: no expert tensors\n", l); ++failures; continue; } - cpu::NativeFmt f; - std::string err; - if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF, f, err)) { - std::printf("layer %d: %s\n", l, err.c_str()); ++failures; continue; - } - cpu::NativeFmt ff; // the full expert's geometry, for strides into the GGUF - if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF_FULL, ff, err)) { - std::printf("layer %d: %s\n", l, err.c_str()); ++failures; continue; - } - const size_t dsz = f.bytes - f.down_off, dsz_full = ff.bytes - ff.down_off; - const size_t drow = dsz / H, drow_full = dsz_full / H; - std::vector blobs((size_t) G * f.bytes); - for (int g = 0; g < G; ++g) { - const size_t E = (size_t) ((g * 37 + 5) % 256); - uint8_t* b = blobs.data() + (size_t) g * f.bytes; - std::memcpy(b, gguf.tensor_data(*t[0]) + E * ff.up_off, f.up_off); - std::memcpy(b + f.up_off, gguf.tensor_data(*t[1]) + E * ff.up_off, f.up_off); - for (int64_t r = 0; r < H; ++r) - std::memcpy(b + f.down_off + r * drow, gguf.tensor_data(*t[2]) + E * dsz_full + r * drow_full, drow); - } - std::mt19937 rng(17 + l); - std::normal_distribution nd(0.f, 1.f); - std::vector x((size_t) NTOK * H); - for (auto& v : x) v = nd(rng); - const int NE = G * T; - std::vector ptr(G); - std::vector start(G + 1), dst(NE), tok(NE); - const auto L = K::native_expert_layout(f.gu_type, f.d_type, H, FF); - uint8_t* dblob; - void *dx, *dxq, *dscr; - float* dout; - unsigned long long* dptr; - int32_t *dstart, *dn, *ddst, *dtok; - cudaMalloc((void**) &dblob, blobs.size()); - cudaMalloc(&dx, x.size() * 4); - cudaMalloc(&dxq, (size_t) NTOK * H / 32 * 36); - cudaMalloc(&dscr, K::native_expert_scratch_bytes(NE, FF)); - cudaMalloc((void**) &dout, (size_t) NE * H * 4); - cudaMalloc((void**) &dptr, (size_t) G * 8); - cudaMalloc((void**) &dstart, (size_t) (G + 1) * 4); - cudaMalloc((void**) &dn, 4); - cudaMalloc((void**) &ddst, (size_t) NE * 4); - cudaMalloc((void**) &dtok, (size_t) NE * 4); - for (int g = 0; g < G; ++g) { - ptr[g] = (unsigned long long) (dblob + (size_t) g * f.bytes); - start[g] = g * T; - for (int j = 0; j < T; ++j) { - dst[g * T + j] = g * T + j; - tok[g * T + j] = (g * 3 + j) % NTOK; - } - } - start[G] = NE; - cudaMemcpy(dblob, blobs.data(), blobs.size(), cudaMemcpyHostToDevice); - cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice); - cudaMemcpy(dptr, ptr.data(), (size_t) G * 8, cudaMemcpyHostToDevice); - cudaMemcpy(dstart, start.data(), (size_t) (G + 1) * 4, cudaMemcpyHostToDevice); - cudaMemcpy(dn, &G, 4, cudaMemcpyHostToDevice); - cudaMemcpy(ddst, dst.data(), (size_t) NE * 4, cudaMemcpyHostToDevice); - cudaMemcpy(dtok, tok.data(), (size_t) NE * 4, cudaMemcpyHostToDevice); - K::quantize_q8_1_rows((const float*) dx, NTOK, H, dxq, s); - auto run = [&](int m, int phase) { - K::native_expert_set_mode(m, phase); - K::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, G, NE, dxq, dscr, dout, s); - }; - std::vector ref((size_t) NE * H), got((size_t) NE * H); - cudaMemsetAsync(dout, 0xff, got.size() * 4, s); - run(mref, 0); - cudaMemcpyAsync(ref.data(), dout, ref.size() * 4, cudaMemcpyDeviceToHost, s); - cudaMemsetAsync(dout, 0xff, got.size() * 4, s); - run(mode, 0); - cudaMemcpyAsync(got.data(), dout, got.size() * 4, cudaMemcpyDeviceToHost, s); - if (cudaStreamSynchronize(s) != cudaSuccess) { std::printf("layer %d: CUDA error\n", l); return 1; } - size_t ndiff = 0; - double worst = 0; - for (size_t i = 0; i < ref.size(); ++i) - if (std::memcmp(&ref[i], &got[i], 4) != 0) { - ++ndiff; - worst = std::fmax(worst, std::fabs((double) ref[i] - got[i]) / (std::fabs((double) ref[i]) + 1e-6)); - } - auto time = [&](int m, int phase) { - for (int i = 0; i < 10; ++i) run(m, phase); - cudaEventRecord(e0, s); - for (int i = 0; i < iters; ++i) run(m, phase); - cudaEventRecord(e1, s); - cudaEventSynchronize(e1); - float ms = 0; - cudaEventElapsedTime(&ms, e0, e1); - return 1e3 * ms / iters; - }; - const double gu_b = (double) G * 2 * f.up_off, d_b = (double) G * dsz; - double us[2][3] = {{1e30, 1e30, 1e30}, {1e30, 1e30, 1e30}}; - for (int round = 0; round < 3; ++round) // interleaved, the minimum: the clocks wander between runs - for (int k = 0; k < 2; ++k) - for (int p = 0; p < 3; ++p) us[k][p] = std::fmin(us[k][p], time(k ? mode : mref, p)); - std::printf("layer %2d %-7s/%-6s G %d T %d | mode %d: all %7.1f us gu %7.1f us (%3.0f GB/s) down %6.1f us (%3.0f GB/s)" - " | mode %d: all %7.1f us gu %7.1f us (%3.0f GB/s) down %6.1f us (%3.0f GB/s) | %s\n", - l, ggml_type_name((ggml_type) f.gu_type), ggml_type_name((ggml_type) f.d_type), G, T, - mref, us[0][0], us[0][1], gu_b / us[0][1] / 1e3, us[0][2], d_b / us[0][2] / 1e3, - mode, us[1][0], us[1][1], gu_b / us[1][1] / 1e3, us[1][2], d_b / us[1][2] / 1e3, - ndiff ? "DIFFERS" : "bitwise equal"); - if (ndiff) { - std::printf(" %zu of %zu outputs differ, worst rel %.2e\n", ndiff, ref.size(), worst); - ++failures; - } - K::native_expert_set_mode(-1, 0); - cudaFree(dblob); cudaFree(dx); cudaFree(dxq); cudaFree(dscr); cudaFree(dout); cudaFree(dptr); - cudaFree(dstart); cudaFree(dn); cudaFree(ddst); cudaFree(dtok); - } - std::printf("native_expert_bench: %d differing\n", failures); - return failures ? 1 : 0; -} diff --git a/src/kernels/native_expert_parity.cpp b/src/kernels/native_expert_parity.cpp deleted file mode 100644 index 37af9c3..0000000 --- a/src/kernels/native_expert_parity.cpp +++ /dev/null @@ -1,670 +0,0 @@ -// src/kernels/native_expert_parity.cpp - plan v0.3 P6: one native expert three ways. -// -// build/native_expert_parity [--geom HxFF] [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" -#include "strata/kernels/cpu/expert.hpp" -#include "strata/kernels/cpu/iq_avx512.hpp" -#include "strata/kernels/cpu/iq_avx2.hpp" -#include "strata/kernels/cpu/kq_avx2.hpp" -#include "strata/kernels/cpu/expert_layout.hpp" -#include "ggml-cpu.h" -#include "strata/kernels/iq_kernels.hpp" - -#include "ggml.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace cpu = strata::kernels::cpu; - -static double rel(const std::vector& a, const std::vector& b) { - double n = 0, d = 0; - for (size_t i = 0; i < a.size(); ++i) { n += std::fabs((double) a[i] - b[i]); d += std::fabs((double) b[i]); } - return n / (d + 1e-30); -} - - -namespace { -constexpr int NT = 3, E = 7; -int64_t H = 2560, FF = 640; // --geom - -// byte offset of the block's fp16 scale `d` inside a block of this type (the negative control flips its high byte) -size_t scale_byte(int type) { - switch (type) { - case 14: return ggml_type_size(GGML_TYPE_Q6_K) - sizeof(ggml_fp16_t); // block_q6_K: ql, qh, scales, then d - case 29: return 55; // IQ1_M: the top nibble of the last scale word - default: return 0; // every other format starts with d (or dm: d is its low half) - } -} - -// the GPU path on one blob, one group of the NT entries (the activations already in `dxq`) -void gpu_expert(const strata::kernels::NativeExpertLayout& L, const std::vector& 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& 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& blob, int seed, const std::string& label, - cudaStream_t s) { - int failures = 0; - // (a) the float reference - const auto* tg = ggml_get_type_traits((ggml_type) f.gu_type); - const auto* td = ggml_get_type_traits((ggml_type) f.d_type); - std::vector G((size_t) FF * H), U((size_t) FF * H), D((size_t) H * FF); - for (int64_t r = 0; r < FF; ++r) { - tg->to_float(blob.data() + r * f.gu_row, G.data() + r * H, H); - tg->to_float(blob.data() + f.up_off + r * f.gu_row, U.data() + r * H, H); - } - for (int64_t r = 0; r < H; ++r) td->to_float(blob.data() + f.down_off + r * f.d_row, D.data() + r * FF, FF); - std::mt19937 rng(11 + seed); - std::normal_distribution nd(0.f, 1.f); - std::vector x((size_t) NT * H); - for (auto& v : x) v = nd(rng); - std::vector ref((size_t) NT * H), got_c((size_t) NT * H), got_g((size_t) NT * H); - for (int k = 0; k < NT; ++k) { - std::vector h(FF); - for (int64_t r = 0; r < FF; ++r) { - double g = 0, u = 0; - for (int64_t i = 0; i < H; ++i) { g += (double) G[r * H + i] * x[k * H + i]; u += (double) U[r * H + i] * x[k * H + i]; } - h[r] = (float) (g / (1.0 + std::exp(-g)) * u); - } - for (int64_t r = 0; r < H; ++r) { - double o = 0; - for (int64_t i = 0; i < FF; ++i) o += (double) D[r * FF + i] * h[i]; - ref[k * H + r] = (float) o; - } - } - // (b) the CPU - { - std::vector> act(NT, std::vector(cpu::kNativeActBytes)); - std::vector> hq(NT, std::vector(cpu::kNativeHBytes)); - std::vector> ff(NT, std::vector(FF)); - const void* a[NT]; - float* ffp[NT]; - const void* hp[NT]; - float* op[NT]; - for (int k = 0; k < NT; ++k) { - cpu::native_quant_act(f, x.data() + k * H, act[k].data()); - a[k] = act[k].data(); - ffp[k] = ff[k].data(); - } - cpu::native_gu_rows(f, blob.data(), a, NT, ffp, 0, (int) FF); - // either multi-token kernel: IQ4_XS has an AVX-2 one and no AVX-512 one, so the gate cannot be - // iq512_supported alone - that would leave the format untested on every CPU. - if (cpu::iq512_supported(f.gu_type) || cpu::iq256_supported(f.gu_type)) { - // ggml's own vec_dot, same Q8_K activations: the reference for both multi-token kernels - // (float-order differences only) - const auto* tc = ggml_get_type_traits_cpu((ggml_type) f.gu_type); - std::vector gref((size_t) NT * FF); - for (int k = 0; k < NT; ++k) - for (int64_t r = 0; r < FF; ++r) - tc->vec_dot((int) H, &gref[k * FF + r], 0, blob.data() + r * f.gu_row, 0, a[k], 0, 1); - double usg = 0.0; - { // ggml single-token throughput, the weights cache-resident (compute bound) - const int it = 50; - auto t0 = std::chrono::steady_clock::now(); - for (int i = 0; i < it; ++i) - for (int64_t r = 0; r < FF; ++r) { - float gg, uu; - tc->vec_dot((int) H, &gg, 0, blob.data() + r * f.gu_row, 0, a[0], 0, 1); - tc->vec_dot((int) H, &uu, 0, blob.data() + f.up_off + r * f.gu_row, 0, a[0], 0, 1); - } - auto t1 = std::chrono::steady_clock::now(); - usg = std::chrono::duration(t1 - t0).count() / it; - } - // one multi-token kernel: parity against ggml's vec_dot, then one-token and NT-token throughput - auto check = [&](const char* tag, bool is512) { - std::vector g((size_t) NT * FF); - float* gp[NT]; - for (int k = 0; k < NT; ++k) gp[k] = g.data() + k * FF; - (is512 ? cpu::iq512_rows : cpu::iq256_rows)(f.gu_type, blob.data(), f.gu_row, (int) H, a, NT, gp, 0, (int) FF); - const double rg = rel(g, gref); - std::printf(" %s %s gate rows vs ggml vec_dot: rel %.2e\n", - ggml_type_name((ggml_type) f.gu_type), tag, rg); - if (rg > 1e-5) { // ggml's own vec_dot is the reference: above 1e-5 it is a real mismatch, - std::printf(" %s %s gate rows MISMATCH (rel %.2e > 1e-5)\n", - ggml_type_name((ggml_type) f.gu_type), tag, rg); // not rounding (measured 3e-8) - ++failures; - } - float* f1[1] = {ffp[0]}; - const int it = 50; - const auto gu = is512 ? cpu::iq512_gu_rows : cpu::iq256_gu_rows; - auto t0 = std::chrono::steady_clock::now(); - for (int i = 0; i < it; ++i) gu(f.gu_type, blob.data(), f.gu_row, f.up_off, (int) H, a, 1, f1, 0, (int) FF); - auto t1 = std::chrono::steady_clock::now(); - for (int i = 0; i < it; ++i) gu(f.gu_type, blob.data(), f.gu_row, f.up_off, (int) H, a, NT, ffp, 0, (int) FF); - auto t2 = std::chrono::steady_clock::now(); - const double us1 = std::chrono::duration(t1 - t0).count() / it; - const double usn = std::chrono::duration(t2 - t1).count() / it; - std::printf(" gate+up one token one thread: %s %.0f us (%.2f GB/s), ggml %.0f us (%.2f GB/s)\n", - tag, us1, 2.0 * f.up_off / us1 / 1e3, usg, 2.0 * f.up_off / usg / 1e3); - std::printf(" gate+up %d tokens one thread: %s %.0f us vs ggml %d x %.0f us\n", NT, tag, usn, NT, usg); - }; - // guarded: the binary runs on AVX-2 CPUs too, and IQ4_XS has no AVX-512 kernel (an empty switch) - if (cpu::cpu_avx512_ok() && cpu::iq512_supported(f.gu_type)) check("avx512", true); - if (cpu::cpu_avx2_ok() && cpu::iq256_supported(f.gu_type)) check("avx2", false); // no AVX2: ggml-cpu only - } - for (int k = 0; k < NT; ++k) { - cpu::native_quant_h(f, ff[k].data(), hq[k].data()); - hp[k] = hq[k].data(); - op[k] = got_c.data() + k * H; - } - cpu::native_down_rows(f, blob.data(), hp, NT, op, 0, (int) H); - { // #152: a token's rows must not depend on how many tokens share the call - each token alone (nt = 1) - // against its row of the NT-token call above, bit for bit, gate/up and down - size_t gu_diff = 0, dn_diff = 0; - std::vector one_ff(FF), one_out(H); - // the NT-token gate/up rows again: the throughput loops above overwrote ff with other kernels' rows - for (int k = 0; k < NT; ++k) ffp[k] = ff[k].data(); - cpu::native_gu_rows(f, blob.data(), a, NT, ffp, 0, (int) FF); - for (int k = 0; k < NT; ++k) { - const void* a1[1] = {a[k]}; - float* f1[1] = {one_ff.data()}; - cpu::native_gu_rows(f, blob.data(), a1, 1, f1, 0, (int) FF); - for (int64_t r = 0; r < FF; ++r) gu_diff += std::memcmp(&one_ff[r], &ff[k][r], 4) != 0; - const void* h1[1] = {hp[k]}; - float* o1[1] = {one_out.data()}; - cpu::native_down_rows(f, blob.data(), h1, 1, o1, 0, (int) H); - for (int64_t r = 0; r < H; ++r) dn_diff += std::memcmp(&one_out[r], &got_c[k * H + r], 4) != 0; - } - std::printf(" width invariance (1 vs %d tokens): gate/up %zu, down %zu rows differ\n", NT, - gu_diff, dn_diff); - if (gu_diff || dn_diff) ++failures; - } - // UD-Q4_K_XL's formats: the multi-token AVX2 kernels (kq_avx2.cpp) against ggml-cpu's vec_dot per token, - // BIT FOR BIT, for 1..8 tokens; then the time of 4 tokens (a verify window) both ways - for (int role = 0; role < 2; ++role) { - const int type = role == 0 ? f.gu_type : f.d_type; - if (!cpu::cpu_avx2_ok() || !cpu::kq256_supported(type) || (role == 0 && type != 12)) continue; - const int n = role == 0 ? (int) H : (int) FF, rows = role == 0 ? (int) FF : (int) H; - const size_t rb = role == 0 ? f.gu_row : f.d_row; - const uint8_t* w = blob.data() + (role == 0 ? 0 : f.down_off); - const auto* tc = ggml_get_type_traits_cpu((ggml_type) type); - const ggml_type at = tc->vec_dot_type; - std::vector> acts(8, std::vector(ggml_row_size(at, n))); - std::mt19937 arng(77 + seed); - std::normal_distribution and_(0.f, 1.f); - std::vector xs((size_t) n); - const void* ap[8]; - for (int t = 0; t < 8; ++t) { - for (auto& v : xs) v = and_(arng); - ggml_get_type_traits_cpu(at)->from_float(xs.data(), acts[t].data(), n); - ap[t] = acts[t].data(); - } - std::vector ref((size_t) 8 * rows), got((size_t) 8 * rows); - for (int t = 0; t < 8; ++t) - for (int r = 0; r < rows; ++r) tc->vec_dot(n, &ref[(size_t) t * rows + r], 0, w + (size_t) r * rb, 0, ap[t], 0, 1); - size_t differ = 0; - for (int nt = 1; nt <= 8; ++nt) { - float* op[8]; - for (int t = 0; t < nt; ++t) op[t] = got.data() + (size_t) t * rows; - cpu::kq256_rows(type, w, rb, n, ap, nt, op, 0, rows); - for (int t = 0; t < nt; ++t) - differ += std::memcmp(op[t], ref.data() + (size_t) t * rows, (size_t) rows * 4) != 0; - } - const int it = 30; - float* op4[4] = {got.data(), got.data() + rows, got.data() + 2 * rows, got.data() + 3 * rows}; - auto t0 = std::chrono::steady_clock::now(); - for (int i = 0; i < it; ++i) cpu::kq256_rows(type, w, rb, n, ap, 4, op4, 0, rows); - auto t1 = std::chrono::steady_clock::now(); - for (int i = 0; i < it; ++i) - for (int r = 0; r < rows; ++r) - for (int t = 0; t < 4; ++t) tc->vec_dot(n, op4[t] + r, 0, w + (size_t) r * rb, 0, ap[t], 0, 1); - auto t2 = std::chrono::steady_clock::now(); - const double us_k = std::chrono::duration(t1 - t0).count() / it; - const double us_g = std::chrono::duration(t2 - t1).count() / it; - std::printf(" %s %s rows, AVX2 multi-token vs ggml vec_dot: %zu of 36 token-sets differ in any bit; " - "4 tokens one thread %.0f us vs ggml %.0f us (%.2fx)\n", ggml_type_name((ggml_type) type), - role == 0 ? "gate" : "down", differ, us_k, us_g, us_g / us_k); - if (differ) ++failures; - } - if (cpu::q2_native_kernels(f.d_type)) { - // (b2) the GGUF-layout Q2_0 kernel the pool uses for Q2_0 down projections - the AVX-512 one - // where the CPU has it, the AVX-2 one (q2_avx2.cpp) where it does not. Calling the AVX-512 - // kernel unconditionally faults on a Zen 2/3 CPU. - std::vector a2(NT); - const cpu::ActQ* ap[NT]; - std::vector alt((size_t) NT * H); - float* altp[NT]; - for (int k = 0; k < NT; ++k) { - cpu::act_quant_any(ff[k].data(), (int) FF, a2[k]); // gated: AVX-512 or AVX-2 per CPU - ap[k] = &a2[k]; - altp[k] = alt.data() + k * H; - } - cpu::q2_rows_any(blob.data() + f.down_off, f.d_row, (int) (FF / 64), ap, NT, altp, 0, (int) H); - std::printf(" q2_0 %s down vs ggml down: rel %.2e\n", - cpu::cpu_avx512_ok() ? "AVX-512" : "AVX-2", rel(alt, got_c)); - } - if (f.d_type == 20 && cpu::cpu_avx2_ok()) { - // (b3) the IQ4_NL multi-token AVX-2 kernel the pool now uses for IQ4_NL down projections, - // against ggml-cpu's single-token vec_dot on the SAME Q8_0 activations (h), plus timing. - std::vector alt((size_t) NT * H), refd((size_t) NT * H); - float* altp[NT]; - for (int k = 0; k < NT; ++k) altp[k] = alt.data() + k * H; - cpu::iq4nl256_down_rows(blob.data() + f.down_off, f.d_row, (int) FF, hp, NT, altp, 0, (int) H); - const auto* tdc = ggml_get_type_traits_cpu((ggml_type) f.d_type); - for (int k = 0; k < NT; ++k) - for (int64_t r = 0; r < H; ++r) - tdc->vec_dot((int) FF, refd.data() + k * H + r, 0, - blob.data() + f.down_off + (size_t) r * f.d_row, 0, hp[k], 0, 1); - const double rdn = rel(alt, refd); - std::printf(" iq4_nl AVX-2 multi-token down vs ggml down: rel %.2e\n", rdn); - if (rdn > 1e-5) { // measured 1e-7; same reasoning as the gate/up rows above - std::printf(" iq4_nl down MISMATCH (rel %.2e > 1e-5)\n", rdn); - ++failures; - } - const int it = 50; - const auto t0 = std::chrono::steady_clock::now(); - for (int i = 0; i < it; ++i) - cpu::iq4nl256_down_rows(blob.data() + f.down_off, f.d_row, (int) FF, hp, NT, altp, 0, (int) H); - const auto t1 = std::chrono::steady_clock::now(); - for (int i = 0; i < it; ++i) - for (int k = 0; k < NT; ++k) - for (int64_t r = 0; r < H; ++r) - tdc->vec_dot((int) FF, refd.data() + k * H + r, 0, - blob.data() + f.down_off + (size_t) r * f.d_row, 0, hp[k], 0, 1); - const auto t2 = std::chrono::steady_clock::now(); - const double usn = std::chrono::duration(t1 - t0).count() / it; - const double usg = std::chrono::duration(t2 - t1).count() / it; - std::printf(" down %d tokens one thread: avx2 %.0f us (%.2f GB/s) vs ggml %.0f us (%.2f GB/s)\n", - NT, usn, (double) (f.bytes - f.down_off) / usn / 1e3, usg, - (double) (f.bytes - f.down_off) / usg / 1e3); - } - } - // (c) the GPU: one group holding the NT entries - { - const auto L = strata::kernels::native_expert_layout(f.gu_type, f.d_type, H, FF); - void *dblob, *dx, *dxq, *dscr; - float* dout; - unsigned long long* dptr; - int32_t *dstart, *dn, *ddst, *dtok; - cudaMalloc(&dblob, blob.size()); - cudaMalloc(&dx, x.size() * 4); - cudaMalloc(&dxq, (size_t) NT * H / 32 * 36); - cudaMalloc(&dscr, strata::kernels::native_expert_scratch_bytes(NT, FF)); - cudaMalloc((void**) &dout, (size_t) NT * H * 4); - cudaMalloc((void**) &dptr, 8); - cudaMalloc((void**) &dstart, 8); - cudaMalloc((void**) &dn, 4); - cudaMalloc((void**) &ddst, NT * 4); - cudaMalloc((void**) &dtok, NT * 4); - cudaMemcpy(dblob, blob.data(), blob.size(), cudaMemcpyHostToDevice); - cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice); - const unsigned long long p = (unsigned long long) dblob; - const int32_t st[2] = {0, NT}, one = 1, idx[NT] = {0, 1, 2}; - cudaMemcpy(dptr, &p, 8, cudaMemcpyHostToDevice); - cudaMemcpy(dstart, st, 8, cudaMemcpyHostToDevice); - cudaMemcpy(dn, &one, 4, cudaMemcpyHostToDevice); - cudaMemcpy(ddst, idx, NT * 4, cudaMemcpyHostToDevice); - cudaMemcpy(dtok, idx, NT * 4, cudaMemcpyHostToDevice); - strata::kernels::quantize_q8_1_rows((const float*) dx, NT, H, dxq, s); - gpu_expert(L, blob, dblob, dxq, dscr, dout, dptr, dstart, dn, ddst, dtok, got_g, s); - { // (e) the negative control: a flipped scale byte in one down row, then in one gate row - const int64_t rd = 5 % H, rg = 3 % FF; // the corrupted rows - std::vector bad = blob; - bad[f.down_off + (size_t) rd * f.d_row + scale_byte(f.d_type)] ^= 0x80; - std::vector 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 old_g(got_g.size()); - const bool was = strata::kernels::iq_old_kernels(); - strata::kernels::iq_set_old_kernels(!was); - strata::kernels::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, 1, NT, dxq, dscr, dout, s); - strata::kernels::iq_set_old_kernels(was); - cudaStreamSynchronize(s); - cudaMemcpy(old_g.data(), dout, old_g.size() * 4, cudaMemcpyDeviceToHost); - const bool same = std::memcmp(old_g.data(), got_g.data(), got_g.size() * 4) == 0; - std::printf(" gpu decode-once vs per-entry kernels: %s\n", same ? "bitwise equal" : "MISMATCH"); - if (!same) ++failures; - } - { // (d) the GPU dequantizers (prompt path: iq_dequant_f32/_f16; embedding: iq_embed_rows) against to_float - float* dq = nullptr; - uint16_t* dh = nullptr; - int32_t* dtk = nullptr; - cudaMalloc((void**) &dq, (size_t) FF * H * 4); - cudaMalloc((void**) &dh, (size_t) FF * H * 2); - cudaMalloc((void**) &dtk, (size_t) FF * 4); - std::vector got_dq((size_t) FF * H); - std::vector got_h((size_t) FF * H); - std::vector tk((size_t) FF); - for (int64_t r = 0; r < FF; ++r) tk[(size_t) r] = (int32_t) (FF - 1 - r); // rows in reverse order - cudaMemcpy(dtk, tk.data(), tk.size() * 4, cudaMemcpyHostToDevice); - double dq_err = 0.0; - size_t differ = 0, h_differ = 0; - const struct { const uint8_t* src; int type; const std::vector* want; } mats[3] = { - {(const uint8_t*) dblob, f.gu_type, &G}, {(const uint8_t*) dblob + f.up_off, f.gu_type, &U}, - {(const uint8_t*) dblob + f.down_off, f.d_type, &D}}; - for (const auto& m : mats) { - strata::kernels::iq_dequant_f32(m.type, m.src, FF * H, dq, s); - strata::kernels::iq_dequant_f16(m.type, m.src, FF * H, dh, s); - cudaStreamSynchronize(s); - cudaMemcpy(got_dq.data(), dq, got_dq.size() * 4, cudaMemcpyDeviceToHost); - cudaMemcpy(got_h.data(), dh, got_h.size() * 2, cudaMemcpyDeviceToHost); - dq_err = (std::max)(dq_err, rel(got_dq, *m.want)); - for (size_t i = 0; i < got_dq.size(); ++i) { - differ += std::memcmp(&got_dq[i], &(*m.want)[i], 4) != 0; - h_differ += got_h[i] != ggml_fp32_to_fp16(got_dq[i]); - } - } - // the gate matrix as an embedding table of FF rows of H values - strata::kernels::iq_embed_rows(f.gu_type, dblob, f.gu_row, dtk, FF, H, dq, s); - cudaStreamSynchronize(s); - cudaMemcpy(got_dq.data(), dq, got_dq.size() * 4, cudaMemcpyDeviceToHost); - size_t emb_differ = 0; - for (int64_t r = 0; r < FF; ++r) - emb_differ += std::memcmp(got_dq.data() + r * H, G.data() + (FF - 1 - r) * H, (size_t) H * 4) != 0; - cudaFree(dq); cudaFree(dh); cudaFree(dtk); - std::printf(" GPU dequant vs ggml to_float: rel %.2e, %zu of %lld values differ in any bit; fp16 of " - "it: %zu differ; embedding rows: %zu of %lld differ\n", dq_err, differ, (long long) (3 * FF * H), - h_differ, emb_differ, (long long) FF); - // exact where there is one product (Q8_0), a rounding at most elsewhere (fused multiply-adds) - const bool exact = f.gu_type == 8 && f.d_type == 8; - if (!(dq_err < 1e-6) || h_differ || (exact && (differ || emb_differ))) ++failures; - } - cudaFree(dblob); cudaFree(dx); cudaFree(dxq); cudaFree(dscr); cudaFree(dout); cudaFree(dptr); - cudaFree(dstart); cudaFree(dn); cudaFree(ddst); cudaFree(dtok); - } - const double ec = rel(got_c, ref), eg = rel(got_g, ref), ecg = rel(got_c, got_g); - // GPU vs the float reference: the tolerance policy's bound for a Q8-activation path (oracle-crosscheck.md: the Q8 - // oracle's ffn_moe_out max 5.3e-3 x 4), measured 9.7e-3 to 1.3e-2 on Qwen3.6's five pairs; 3e-2 for a pair with a - // Q5_0 role (32-value blocks with no min on a 640-wide row: q4_K/q5_0 measured 2.7e-2; see the CMake note). CPU - // vs the reference: ggml-cpu rounds the activations to Q8_K (256-value blocks, one scale per 256 values, against - // the GPU's q8_1 per 32), measured up to 2.2e-2, so 3e-2. CPU vs GPU: both roundings, measured up to 2.4e-2, 4e-2. - const double gpu_bound = (f.gu_type == 6 || f.d_type == 6) ? 3e-2 : 2e-2; - const bool ok = ec < 3e-2 && eg < gpu_bound && ecg < 4e-2 && std::isfinite(ec) && std::isfinite(eg) && std::isfinite(ecg); - std::printf("%-9s %-8s/%-7s blob %8zu cpu rel %.2e (< 3e-2) gpu rel %.2e (< %.0e) cpu-gpu %.2e (< 4e-2) %s\n", - label.c_str(), ggml_type_name((ggml_type) f.gu_type), ggml_type_name((ggml_type) f.d_type), f.bytes, ec, - eg, gpu_bound, ecg, ok ? "ok" : "FAIL"); - return failures + (ok ? 0 : 1); -} - -int type_of(std::string name) { - for (auto& c : name) c = (char) std::tolower((unsigned char) c); - for (int t = 0; t < GGML_TYPE_COUNT; ++t) { - const char* n = ggml_type_name((ggml_type) t); - if (n == nullptr) continue; - std::string m(n); - for (auto& c : m) c = (char) std::tolower((unsigned char) c); - if (m == name) return t; - } - return -1; -} - -// Random weights (rows of different magnitudes) quantized by ggml into the blob layout. -std::vector synthetic_blob(const cpu::NativeFmt& f, int seed) { - std::vector blob(f.bytes); - std::mt19937 rng(seed); - std::normal_distribution nd(0.f, 1.f); - auto quant = [&](int type, int64_t rows, int64_t cols, uint8_t* dst) { - std::vector w((size_t) (rows * cols)); - for (int64_t r = 0; r < rows; ++r) { - const float scale = 0.02f * (0.5f + (float) (r % 7) / 7.0f); - for (int64_t c = 0; c < cols; ++c) w[(size_t) (r * cols + c)] = scale * nd(rng); - } - const std::vector imatrix((size_t) cols, 1.0f); - ggml_quantize_chunk((ggml_type) type, w.data(), dst, 0, rows, cols, - ggml_quantize_requires_imatrix((ggml_type) type) ? imatrix.data() : nullptr); - }; - quant(f.gu_type, FF, H, blob.data()); - quant(f.gu_type, FF, H, blob.data() + f.up_off); - quant(f.d_type, H, FF, blob.data() + f.down_off); - return blob; -} - -// The Q5_1 min term. Activations x = d * (q + 0.45) round to q, so each q8_1 block's sum of the ORIGINAL values -// (`ds.y`, what llama.cpp CUDA multiplies the min by) exceeds d * sum(q) by 0.45 * 32 * d. The GPU dot must take -// the quantized sum, as ggml-cpu's vec_dot does: equal to ggml-cpu on the same blocks with s = d * sum(q), and far -// from the ds.y variant. Weights with large mins make the difference visible. -int check_q5_1_min(cudaStream_t s) { - constexpr int n = 640, rows = 64; - ggml_cpu_init(); // the fp16 tables vec_dot uses (the other modes get this through native_fmt) - std::mt19937 rng(5); - std::uniform_int_distribution qd(-100, 100); - std::normal_distribution nd(0.f, 1.f); - std::vector w((size_t) rows * n), x(n); - for (auto& v : w) v = 0.3f + 0.05f * nd(rng); // positive weights: a large min per block - const float d = 0.01f; - for (auto& v : x) v = d * ((float) qd(rng) + 0.45f); - const size_t row_bytes = ggml_row_size(GGML_TYPE_Q5_1, n); - std::vector wq((size_t) rows * row_bytes); - ggml_quantize_chunk(GGML_TYPE_Q5_1, w.data(), wq.data(), 0, rows, n, nullptr); - // the GPU: its own q8_1 quantizer, then iq_mmvq on Q5_1 - void *dw, *dx, *dxq; - float* dy; - cudaMalloc(&dw, wq.size()); - cudaMalloc(&dx, n * 4); - cudaMalloc(&dxq, (size_t) n / 32 * 36); - cudaMalloc((void**) &dy, rows * 4); - cudaMemcpy(dw, wq.data(), wq.size(), cudaMemcpyHostToDevice); - cudaMemcpy(dx, x.data(), n * 4, cudaMemcpyHostToDevice); - strata::kernels::quantize_q8_1_rows((const float*) dx, 1, n, dxq, s); - strata::kernels::iq_mmvq(GGML_TYPE_Q5_1, dw, dxq, dy, n, rows, 1, s); - cudaStreamSynchronize(s); - std::vector gpu(rows); - std::vector xq((size_t) n / 32 * 36); - cudaMemcpy(gpu.data(), dy, rows * 4, cudaMemcpyDeviceToHost); - cudaMemcpy(xq.data(), dxq, xq.size(), cudaMemcpyDeviceToHost); - cudaFree(dw); cudaFree(dx); cudaFree(dxq); cudaFree(dy); - // ggml-cpu on the GPU's own blocks: once with s = d * sum(q) (the quantized sum), once with s = ds.y as stored - struct Q81 { ggml_fp16_t d, s; int8_t qs[32]; }; // ggml's block_q8_1: {d, s} halves, 32 codes - static_assert(sizeof(Q81) == 36, "block_q8_1 layout"); - auto* blocks = (Q81*) xq.data(); - std::vector qsum(blocks, blocks + n / 32); - double shift = 0.0; - for (auto& b : qsum) { - int sq = 0; - for (int i = 0; i < 32; ++i) sq += b.qs[i]; - const float dd = ggml_fp16_to_fp32(b.d); - shift = (std::max)(shift, (double) std::fabs(ggml_fp16_to_fp32(b.s) - dd * sq)); - b.s = ggml_fp32_to_fp16(dd * (float) sq); - } - const auto* tc = ggml_get_type_traits_cpu(GGML_TYPE_Q5_1); - std::vector want(rows), stored(rows); - for (int r = 0; r < rows; ++r) { - const uint8_t* row = wq.data() + (size_t) r * row_bytes; - tc->vec_dot(n, &want[r], 0, row, 0, qsum.data(), 0, 1); - tc->vec_dot(n, &stored[r], 0, row, 0, blocks, 0, 1); - } - const double e_q = rel(gpu, want), e_s = rel(gpu, stored); - // the quantized sum goes through fp16 in ggml-cpu's block (s is a half), so 1e-3 rather than bitwise - const bool ok = e_q < 1e-3 && e_s > 10 * e_q && shift > 0.0; - std::printf("q5_1 min row 0: GPU %.6g, ggml-cpu (quantized sum) %.6g, (stored sum) %.6g\n", gpu[0], want[0], - stored[0]); - std::printf("q5_1 min GPU vs ggml-cpu with s = d*sum(q): rel %.2e; vs s = sum(x) (llama.cpp CUDA's): rel %.2e " - "(largest per-block sum shift %.3g) %s\n", e_q, e_s, shift, ok ? "ok" : "FAIL"); - return ok ? 0 : 1; -} -// #290: the BF16 token embedding (--embd-gguf) - iq_embed_rows and iq_dequant_f32 on a random BF16 table against -// the exact widening (bits << 16), every bit; rows gathered out of order, with repeats -int check_bf16_embd(cudaStream_t s) { - constexpr int kBf16 = 30; - const int64_t H = 2560, V = 61, NT = 97; - int failures = 0; - if (!strata::kernels::embed_type_supported(kBf16) || strata::kernels::iq_supported(kBf16) || - strata::kernels::iq_row_bytes(kBf16, H) != (size_t) H * 2) { - std::printf("bf16 embedding: type support / row bytes wrong\n"); - return 1; - } - std::mt19937 rng(290); - std::vector table((size_t) (V * H)); - for (auto& v : table) { // any bit pattern but NaN (a NaN's payload is not what the test is about) - do v = (uint16_t) (rng() & 0xffff); while ((v & 0x7f80) == 0x7f80 && (v & 0x7f)); - } - std::vector tok((size_t) NT); - for (auto& t : tok) t = (int32_t) (rng() % V); - void* dt = nullptr; - int32_t* dtok = nullptr; - float* dout = nullptr; - cudaMalloc(&dt, table.size() * 2); - cudaMalloc((void**) &dtok, tok.size() * 4); - const int64_t out_rows = NT > V ? NT : V; // the gathered rows (NT) and the whole table (V) share the buffer - cudaMalloc((void**) &dout, (size_t) (out_rows * H) * 4); - cudaMemcpy(dt, table.data(), table.size() * 2, cudaMemcpyHostToDevice); - cudaMemcpy(dtok, tok.data(), tok.size() * 4, cudaMemcpyHostToDevice); - auto widen = [](uint16_t b) { const uint32_t u = (uint32_t) b << 16; float f; std::memcpy(&f, &u, 4); return f; }; - std::vector got((size_t) (out_rows * H)); - strata::kernels::iq_embed_rows(kBf16, dt, (size_t) H * 2, dtok, NT, H, dout, s); - cudaStreamSynchronize(s); - cudaMemcpy(got.data(), dout, (size_t) (NT * H) * 4, cudaMemcpyDeviceToHost); - size_t rows_differ = 0; - for (int64_t r = 0; r < NT; ++r) - for (int64_t d = 0; d < H; ++d) { - const float want = widen(table[(size_t) (tok[(size_t) r] * H + d)]); - if (std::memcmp(&got[(size_t) (r * H + d)], &want, 4) != 0) { ++rows_differ; break; } - } - strata::kernels::iq_dequant_f32(kBf16, dt, V * H, dout, s); - cudaStreamSynchronize(s); - cudaMemcpy(got.data(), dout, table.size() * 4, cudaMemcpyDeviceToHost); - size_t values_differ = 0; - for (size_t i = 0; i < table.size(); ++i) { - const float want = widen(table[i]); - values_differ += std::memcmp(&got[i], &want, 4) != 0; - } - cudaFree(dt); cudaFree(dtok); cudaFree(dout); - std::printf("bf16 embedding: %lld gathered rows, %zu differ; dequant of %lld values, %zu differ in any bit\n", - (long long) NT, rows_differ, (long long) (V * H), values_differ); - if (rows_differ || values_differ) ++failures; - return failures; -} - -} // namespace - -int main(int argc, char** argv) { - setvbuf(stdout, nullptr, _IONBF, 0); // keep the trail on a crash - if (argc < 2) { - std::fprintf(stderr, "usage: native_expert_parity [layer ...]\n" - " native_expert_parity --synthetic GU/DOWN ... (ggml type names, e.g. q4_K/q5_1)\n" - " native_expert_parity --q5_1-min\n" - " native_expert_parity --bf16-embd\n"); - return 2; - } - // #152's width check tests the opt-in rule (the multi-token kernels from one token on) - if (std::getenv("STRATA_IQ_MT_MIN") == nullptr) { -#ifdef _WIN32 - _putenv_s("STRATA_IQ_MT_MIN", "1"); -#else - setenv("STRATA_IQ_MT_MIN", "1", 1); -#endif - } - int failures = 0; - cudaStream_t s; - cudaStreamCreate(&s); - int ai = 1; - if (std::string(argv[ai]) == "--geom") { - if (argc < 4 || std::sscanf(argv[ai + 1], "%lldx%lld", (long long*) &H, (long long*) &FF) != 2 || H <= 0 || FF <= 0) { - std::fprintf(stderr, "--geom takes HxFF, e.g. 2048x512\n"); - return 2; - } - ai += 2; - } - const std::string mode = argv[ai]; - std::printf("geometry n_embd %lld x n_ff %lld\n", (long long) H, (long long) FF); - if (mode == "--q5_1-min") { - failures += check_q5_1_min(s); - } else if (mode == "--bf16-embd") { - failures += check_bf16_embd(s); - } else if (mode == "--synthetic") { - for (int i = ai + 1; i < argc; ++i) { - 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)); - const int dn = slash == std::string::npos ? -1 : type_of(arg.substr(slash + 1)); - cpu::NativeFmt f; - std::string err; - if (gu < 0 || dn < 0 || !cpu::native_fmt(gu, dn, H, FF, f, err) || - !strata::kernels::native_expert_supported(gu, dn, H, FF)) { - std::printf("%s: %s\n", arg.c_str(), err.empty() ? "not a pair the GPU expert kernels take" : err.c_str()); - ++failures; - continue; - } - failures += check_blob(f, synthetic_blob(f, i), i, "synthetic", s); - } - } else { - const strata::GgufModel model(strata::gguf_split_paths(argv[ai])); - std::vector layers; - 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] = {}; - const uint8_t* data[3] = {}; - const char* roles[3] = {"gate", "up", "down"}; - for (int r = 0; r < 3; ++r) { // each role from the shard that holds it - size_t at = 0; - t[r] = model.find("blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight", &at); - if (t[r]) data[r] = model.shard(at).tensor_data(*t[r]); - } - if (!t[0] || !t[1] || !t[2]) { std::printf("layer %d: no expert tensors\n", l); ++failures; continue; } - cpu::NativeFmt f; - std::string err; - if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF, f, err)) { - std::printf("layer %d: %s\n", l, err.c_str()); ++failures; continue; - } - std::vector blob(f.bytes); - std::memcpy(blob.data(), data[0] + (size_t) E * f.up_off, f.up_off); - std::memcpy(blob.data() + f.up_off, data[1] + (size_t) E * f.up_off, f.up_off); - std::memcpy(blob.data() + f.down_off, data[2] + (size_t) E * (f.bytes - f.down_off), - f.bytes - f.down_off); - failures += check_blob(f, blob, l, "layer " + std::to_string(l), s); - } - } - std::printf("native_expert_parity: %d failures\n", failures); - return failures ? 1 : 0; -} diff --git a/src/kernels/native_grouped_parity.cpp b/src/kernels/native_grouped_parity.cpp deleted file mode 100644 index 8d7338f..0000000 --- a/src/kernels/native_grouped_parity.cpp +++ /dev/null @@ -1,401 +0,0 @@ -// src/kernels/native_grouped_parity.cpp - native_expert_grouped's group stride (grid_groups) and its fused SwiGLU + -// q8_1 pass, against the launches before them (native_grouped_set_v1: a block row per possible group, SwiGLU and the -// q8_1 quantization as two kernels over all cap_entries). Synthetic blobs, no model. -// -// build/native_grouped_parity the checks (a ctest; needs the GPU) -// build/native_grouped_parity --bench the checks, then v1/new timings of 48 calls in a graph (a window's layers) -// build/native_grouped_parity --bench-down the checks, then the down kernel alone per expert, each down type at -// Qwen3.6's 2048 x 512 (the step-5 budget: Q5_1 is the comparator) -// -// 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), -// scattered destinations, stale scratch, grid_groups 0 (= cap), 1, 2, 3, 4 and above cap: the output must be BITWISE -// equal to v1's, the rows the call must not write included (both start from the same NaN pattern). -// -// Random bytes are valid codes for every format here (every grid index is in range); only the fp16 block scales are -// set, small enough that the SwiGLU outputs keep a finite fp16 q8_1 scale. -#include "strata/kernels/iq_kernels.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace k = strata::kernels; - -namespace { - -int g_fail = 0; - -void ck(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "CUDA error in %s: %s\n", what, cudaGetErrorString(e)); - std::exit(2); - } -} - -template -T* dalloc(size_t n) { - T* p = nullptr; - ck(cudaMalloc(&p, n * sizeof(T) + 256), "malloc"); - ck(cudaMemset(p, 0, n * sizeof(T) + 256), "memset"); - return p; -} - -const char* name_of(int t) { - switch (t) { - case 16: return "IQ2_XXS"; - case 17: return "IQ2_XS"; - case 18: return "IQ3_XXS"; - case 20: return "IQ4_NL"; - case 21: return "IQ3_S"; - case 22: return "IQ2_S"; - case 23: return "IQ4_XS"; - case 29: return "IQ1_M"; - 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 "?"; - } -} -int block_values(int t) { return t == 20 || t == 7 || t == 8 ? 32 : t == 42 ? 64 : 256; } - -// `rows` rows of `n` values of format t: random bytes, then a finite fp16 scale in every block -std::vector random_rows(int t, int64_t rows, int64_t n, std::mt19937& rng) { - const size_t rb = k::iq_row_bytes(t, n), bs = k::iq_row_bytes(t, block_values(t)); - std::vector w((size_t) rows * rb); - std::uniform_int_distribution byte(0, 255), ex(2, 8), man(0, 1023), sgn(0, 1); - for (auto& b : w) b = (uint8_t) byte(rng); - for (size_t o = 0; o < w.size(); o += bs) { - if (t == 29) { - // IQ1_M: the fp16 scale is the top nibbles of its four scale words (bytes 48..55), the sign and the - // exponent's top bits in the last: 0x1 / 0x2 there (0x9 / 0xA negative) keeps it in 2^-11 .. 2^-3 - const uint8_t nib = (uint8_t) ((sgn(rng) ? 0x8 : 0x0) | (1 + (byte(rng) & 1))); - w[o + 55] = (uint8_t) ((w[o + 55] & 0x0F) | (nib << 4)); - } else { // the other formats start their block with the fp16 scale: 2^-13 .. 2^-6 - // (Q4_K / Q5_K: 2^-14 .. 2^-11, their 6-bit sub-scales multiply it by up to 63; Q6_K: the same range, - // its int8 sub-scales up to 127, and its d is the block's LAST two bytes) - const int e = (t == 12 || t == 13 || t == 14) ? 1 + ex(rng) % 4 : ex(rng); - const uint16_t h = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (e << 10) | man(rng)); - std::memcpy(&w[o + (t == 14 ? bs - 2 : 0)], &h, 2); - 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)); - std::memcpy(&w[o + 2], &m, 2); - } - } - } - return w; -} - -// one window's worth of expert calls on one format pair: blobs, T tokens' q8_1 activations, cap = T * K entries -struct Setup { - k::NativeExpertLayout L; - int T = 0, K = 0, cap = 0, n_blobs = 0; - size_t slot = 0; - uint8_t* blobs = nullptr; - uint8_t* xq = nullptr; - uint8_t* scr = nullptr; - size_t scr_bytes = 0; - float* out = nullptr; - size_t out_floats = 0; - unsigned long long* ptr = nullptr; - int32_t *start = nullptr, *n = nullptr, *dst = nullptr, *tok = nullptr; - - Setup(int gu, int dt, int64_t H, int64_t FF, int tokens, int k_per_token, int blobs_n, std::mt19937& rng, - cudaStream_t s) { - L = k::native_expert_layout(gu, dt, H, FF); - T = tokens; K = k_per_token; cap = T * K; n_blobs = blobs_n; - slot = (L.bytes + 255) & ~(size_t) 255; - blobs = dalloc(slot * (size_t) n_blobs); - for (int b = 0; b < n_blobs; ++b) { - // gate rows | up rows (format gu, H values each) | down rows (format dt, FF values each) - auto blob = random_rows(gu, 2 * FF, H, rng); - const auto down = random_rows(dt, H, FF, rng); - blob.insert(blob.end(), down.begin(), down.end()); - if (blob.size() != L.bytes) { std::fprintf(stderr, "blob %zu != %zu bytes\n", blob.size(), L.bytes); std::exit(2); } - ck(cudaMemcpy(blobs + slot * (size_t) b, blob.data(), blob.size(), cudaMemcpyHostToDevice), "blob"); - } - std::normal_distribution nd(0.f, 1.f); - std::vector x((size_t) T * H); - for (auto& v : x) v = nd(rng); - float* dx = dalloc(x.size()); - ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); - xq = dalloc((size_t) T * (H / 32) * 36); - k::quantize_q8_1_rows(dx, T, H, xq, s); - ck(cudaStreamSynchronize(s), "quantize"); - cudaFree(dx); - scr_bytes = k::native_expert_scratch_bytes(cap, FF); - scr = dalloc(scr_bytes); - out_floats = (size_t) cap * H; - out = dalloc(out_floats); - ptr = dalloc(cap); - start = dalloc(cap + 1); - n = dalloc(1); - dst = dalloc(cap); - tok = dalloc(cap); - } - ~Setup() { - cudaFree(blobs); cudaFree(xq); cudaFree(scr); cudaFree(out); - cudaFree(ptr); cudaFree(start); cudaFree(n); cudaFree(dst); cudaFree(tok); - } - // a plan: `groups` groups of 1..T entries from entry `base` on (as many as fit in cap) - int plan(int groups, int base, std::mt19937& rng) { - std::uniform_int_distribution size(1, T); - std::vector sizes; - int used = base; - for (int g = 0; g < groups; ++g) { - const int m = std::min(size(rng), cap - used); - if (m <= 0) break; - sizes.push_back(m); - used += m; - } - return plan_sizes(sizes, base, rng); - } - // groups of these sizes from entry `base` on, each its own blob (as long as there are enough: a window's groups - // are different experts); scattered destinations, random tokens - int plan_sizes(const std::vector& sizes, int base, std::mt19937& rng) { - std::uniform_int_distribution tk(0, T - 1); - std::vector order(n_blobs); - std::iota(order.begin(), order.end(), 0); - std::shuffle(order.begin(), order.end(), rng); - std::vector p; - std::vector st(1, base), tk_v, ds(cap); - for (const int m : sizes) { - p.push_back((unsigned long long) (blobs + slot * (size_t) order[p.size() % order.size()])); - st.push_back(st.back() + m); - } - if (st.back() > cap) { std::fprintf(stderr, "plan: %d entries > cap %d\n", st.back(), cap); std::exit(2); } - const int ng = (int) p.size(); - std::iota(ds.begin(), ds.end(), 0); - std::shuffle(ds.begin(), ds.end(), rng); // scattered rows of `out` - for (int e = 0; e < cap; ++e) tk_v.push_back(tk(rng)); - if (ng) ck(cudaMemcpy(ptr, p.data(), p.size() * 8, cudaMemcpyHostToDevice), "ptr"); - ck(cudaMemcpy(start, st.data(), st.size() * 4, cudaMemcpyHostToDevice), "start"); - ck(cudaMemcpy(n, &ng, 4, cudaMemcpyHostToDevice), "n"); - ck(cudaMemcpy(dst, ds.data(), ds.size() * 4, cudaMemcpyHostToDevice), "dst"); - ck(cudaMemcpy(tok, tk_v.data(), tk_v.size() * 4, cudaMemcpyHostToDevice), "tok"); - return ng; - } - void call(int64_t grid_groups, cudaStream_t s) { - k::native_expert_grouped(L, ptr, start, n, dst, tok, cap, cap, xq, scr, out, s, grid_groups); - } - // `out` after one call from the NaN pattern, the scratch holding `junk` (what earlier calls left there) - std::vector result(bool v1, int64_t grid_groups, int junk, cudaStream_t s) { - ck(cudaMemset(out, 0xFF, out_floats * 4), "memset"); - ck(cudaMemset(scr, junk, scr_bytes), "memset"); - k::native_grouped_set_v1(v1); - call(grid_groups, s); - k::native_grouped_set_v1(false); - ck(cudaStreamSynchronize(s), "sync"); - std::vector o(out_floats); - ck(cudaMemcpy(o.data(), out, o.size() * 4, cudaMemcpyDeviceToHost), "out"); - return o; - } -}; - -void check(int gu, int dt, int64_t H, int64_t FF, cudaStream_t s, std::mt19937& rng) { - Setup S(gu, dt, H, FF, 6, 4, 9, rng, s); // 6 tokens x 4 experts: cap 24 entries - int calls = 0, bad = 0; - size_t written = 0; - for (const int base : {0, 7}) { - for (const int groups : {0, 1, 2, 3, 5, 8, 24}) { - const int ng = S.plan(groups, base, rng); - const auto ref = S.result(true, 0, 0x00, s); - size_t w = 0; - for (const uint32_t v : ref) w += v != 0xFFFFFFFFu; - written += w; - for (const int64_t gy : {(int64_t) 0, (int64_t) 1, (int64_t) 2, (int64_t) 3, (int64_t) 4, (int64_t) S.cap + 3}) { - const auto got = S.result(false, gy, (calls & 1) ? 0x7F : 0x00, s); - ++calls; - size_t diff = 0; - for (size_t i = 0; i < ref.size(); ++i) diff += ref[i] != got[i]; - if (diff) { - std::printf(" %-8s/%-7s base %d, %d groups, grid_groups %lld: %zu of %zu floats differ FAIL\n", - name_of(gu), name_of(dt), base, ng, (long long) gy, diff, ref.size()); - ++bad; - } - } - } - } - std::printf("%-8s/%-7s %5lld x %4lld %d calls: %s (%zu output floats written in all)\n", name_of(gu), name_of(dt), - (long long) H, (long long) FF, calls, bad ? "FAIL" : "bitwise equal to v1", written); - if (written == 0) { std::printf(" nothing was written: the check checked nothing FAIL\n"); ++bad; } - g_fail += bad; -} - -// ------------------------------------------------------------------------------------------------ --bench -// A window's 48 calls, one per layer, each with ITS OWN experts as the layers have: copies of the Setup's blobs in one -// arena, so the weights stream from DRAM as in the engine. (48 calls re-reading the same 28 experts - 73 MB, about an -// Ada L2 - would read part of them from L2; the engine's layers share none.) -struct Layers { - uint8_t* arena = nullptr; - std::vector ptr; // per layer: its groups' blobs (device) - Layers(Setup& S, int ng) { - const int per = std::max(ng, 1); - arena = dalloc(S.slot * (size_t) (48 * per)); - for (int l = 0; l < 48; ++l) { - std::vector p; - for (int j = 0; j < per; ++j) { - uint8_t* d = arena + S.slot * (size_t) (l * per + j); - ck(cudaMemcpy(d, S.blobs + S.slot * (size_t) ((l * per + j) % S.n_blobs), S.L.bytes, - cudaMemcpyDeviceToDevice), "blob copy"); - p.push_back((unsigned long long) d); - } - unsigned long long* dp = dalloc(p.size()); - ck(cudaMemcpy(dp, p.data(), p.size() * 8, cudaMemcpyHostToDevice), "ptr"); - ptr.push_back(dp); - } - } - Layers(const Layers&) = delete; - Layers& operator=(const Layers&) = delete; - ~Layers() { - for (auto* p : ptr) cudaFree(p); - cudaFree(arena); - } -}; - -// the 48 calls of one variant captured in one graph -cudaGraphExec_t make_graph(cudaStream_t s, Setup& S, const Layers& Ls, bool v1, int64_t gy) { - k::native_grouped_set_v1(v1); - cudaGraph_t g; - cudaGraphExec_t ge; - ck(cudaStreamBeginCapture(s, cudaStreamCaptureModeThreadLocal), "capture"); - for (int l = 0; l < 48; ++l) - k::native_expert_grouped(S.L, Ls.ptr[l], S.start, S.n, S.dst, S.tok, S.cap, S.cap, S.xq, S.scr, S.out, s, gy); - ck(cudaStreamEndCapture(s, &g), "capture"); - ck(cudaGraphInstantiate(&ge, g, 0), "instantiate"); - ck(cudaGraphDestroy(g), "graph"); - k::native_grouped_set_v1(false); - return ge; -} - -// one launch of the graph: microseconds per call -float launch_us(cudaStream_t s, cudaGraphExec_t ge, cudaEvent_t e0, cudaEvent_t e1) { - ck(cudaEventRecord(e0, s), "record"); - ck(cudaGraphLaunch(ge, s), "launch"); - ck(cudaEventRecord(e1, s), "record"); - ck(cudaEventSynchronize(e1), "bench"); - float ms = 0; - ck(cudaEventElapsedTime(&ms, e0, e1), "elapsed"); - return 1e3f * ms / 48.0f; -} - -float median(std::vector v) { - std::sort(v.begin(), v.end()); - return v[v.size() / 2]; -} - -// The two variants' launches ALTERNATE (v1-new, new-v1, ...) after a warm-up, and each reports its median: a card -// under sustained load steps its clock down after a fraction of a second (an RTX 4080 SUPER went from 80 to 89 us -// per gate/up call within one run), and whichever variant ran before the step would look faster. -constexpr int kWarmPairs = 20, kPairs = 40; - -void bench(cudaStream_t s, std::mt19937& rng) { - std::printf("\n--bench: microseconds per call, a window's 48 calls in a graph, each layer with its own experts (the\n" - "weights stream from DRAM as in the engine); v1 / new (grid_groups): medians of %d launches each,\n" - "alternating, after %d warm-up pairs - idle GPU assumed\n", kPairs, kWarmPairs); - // a verify window's shape: 4 tokens x 10 experts, 2560 x 768 IQ3_S / IQ4_XS experts - Setup S(21, 23, 2560, 768, 4, 10, 32, rng, s); - std::vector vram(16, 1); - vram.insert(vram.end(), 12, 2); // 28 groups, 40 entries - const struct { const char* what; std::vector sizes; int64_t gy; } rows[] = { - {"no group (the PCIe call at pcie_frac 0)", {}, 4}, - {"1 group of 2 entries (a PCIe call)", {2}, 4}, - {"28 groups, 40 entries (a VRAM call)", vram, 0}, - }; - cudaEvent_t e0, e1; - ck(cudaEventCreate(&e0), "event"); - ck(cudaEventCreate(&e1), "event"); - for (const auto& r : rows) { - const int ng = S.plan_sizes(r.sizes, 0, rng); - const Layers Ls(S, ng); // 48 x 28 experts: 3.7 GB for the VRAM call - cudaGraphExec_t ga = make_graph(s, S, Ls, true, 0), gb = make_graph(s, S, Ls, false, r.gy); - std::vector ta, tb; - for (int i = 0; i < kWarmPairs + kPairs; ++i) { - const bool a_first = i % 2 == 0; - const float x = launch_us(s, a_first ? ga : gb, e0, e1), y = launch_us(s, a_first ? gb : ga, e0, e1); - if (i < kWarmPairs) continue; - ta.push_back(a_first ? x : y); - tb.push_back(a_first ? y : x); - } - ck(cudaGraphExecDestroy(ga), "graph"); - ck(cudaGraphExecDestroy(gb), "graph"); - std::printf(" %-42s %8.2f / %8.2f us (grid_groups %lld)\n", r.what, median(ta), median(tb), (long long) r.gy); - } - cudaEventDestroy(e0); - 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 sizes; } rows[] = { - {"32 x 1 (4 tokens, own experts)", std::vector(32, 1)}, - {"8 x 4 (4 tokens, shared)", std::vector(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 t; - for (int i = 0; i < kWarmPairs + kPairs; ++i) { - const float x = launch_us(s, g, e0, e1); - if (i >= kWarmPairs) t.push_back(x); - } - k::native_expert_set_mode(-1, 0); - ck(cudaGraphExecDestroy(g), "graph"); - const float us = median(t); - std::printf(" %-8s %-26s %10.2f %12.3f %10.3f\n", name_of(dt), r.what, us, us / ng, - (double) (S.L.bytes - S.L.down_off) / 1e6); - } - } - cudaEventDestroy(e0); - cudaEventDestroy(e1); -} - -} // namespace - -int main(int argc, char** argv) { - const bool do_bench = argc > 1 && std::string(argv[1]) == "--bench"; - const bool do_bench_down = argc > 1 && std::string(argv[1]) == "--bench-down"; - cudaStream_t s; - ck(cudaStreamCreate(&s), "stream"); - std::mt19937 rng(316); - for (int gu : {16, 17, 18, 21, 22, 23, 29, 42, 12, 13, 14, 8}) // STRATA_GU_FMTS - for (int dt : {20, 23, 42, 7, 8, 18, 13, 14}) check(gu, dt, 512, 256, s, rng); // STRATA_D_FMTS (256-value - // down types: n_ff % 256) - check(21, 20, 2560, 640, s, rng); // Flash-Next's shapes - check(21, 23, 2560, 768, s, rng); - for (const auto& pr : {std::pair{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; -} diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp deleted file mode 100644 index d5d0fb4..0000000 --- a/src/kernels/ngram.cpp +++ /dev/null @@ -1,521 +0,0 @@ -// src/kernels/ngram.cpp - P2.S4: the PLE n-gram hash and the IQ4_NL table read. -// -// See include/strata/kernels/ngram.hpp for the semantics, the rival readings, and the note on MADV_RANDOM. -#include "strata/kernels/ngram.hpp" -#include "strata/artifact/gguf_reader.hpp" -#include "strata/artifact/dequant.hpp" -#include "strata/kernels/f16_bits.hpp" -#include "strata/ngram/ple_reader.hpp" -#include "strata/platform/robust_read.hpp" - -#include -#include -#include -#include -#if !defined(_WIN32) -#include -#endif -#include -#include - -#if defined(_WIN32) -// `PrefetchVirtualMemory` (memoryapi.h, Windows 8+) is the whole point of the change in `gather` below. -#define WIN32_LEAN_AND_MEAN -#define NOMINMAX -#include -#endif - -namespace strata::kernels { - -namespace { -/// The A/B arm. Host-token-path only, so it needs no atomics; see the note on `ple_prefetch_enable`. -bool g_ple_prefetch = true; -} // namespace - -void ple_prefetch_enable(bool on) { g_ple_prefetch = on; } -bool ple_prefetch_enabled() { return g_ple_prefetch; } - -PleConsts ple_artifact_consts() { - // docs/gguf-dump-shard1.txt, verbatim. Written once here rather than derived, because `head_offsets` is - // ALSO in the metadata as its own array - and deriving one from the other would hide a mismatch between - // them instead of surfacing it. The parity test checks the two agree. - PleConsts c{}; - c.mult[0] = 23703573157769ull; - c.mult[1] = 20109073645365ull; - c.mult[2] = 8052911324071ull; - const uint64_t vocab[PLE_N_HEADS] = { - 20000003, 20000023, 20000033, 20000047, 20000059, 20000063, 20000069, 20000077, - 20000081, 20000093, 20000107, 20000147, 20000153, 20000159, 20000161, 20000171}; - const uint64_t offset[PLE_N_HEADS] = { - 0, 20000003, 40000026, 60000059, 80000106, 100000165, 120000228, 140000297, - 160000374, 180000455, 200000548, 220000655, 240000802, 260000955, 280001114, 300001275}; - for (int i = 0; i < PLE_N_HEADS; ++i) { - c.vocab[i] = vocab[i]; - c.offset[i] = offset[i]; - } - return c; -} - -uint64_t ngram_mixed(const int64_t* ctx, const uint64_t* mult, int n) { - // The first term is an ASSIGNMENT and the rest are XORed into it, which is how the source writes it - // (`uint64_t mixed = ctx[0]*m[0]; for j=1.. mixed ^= ctx[j]*m[j];`). Every product wraps mod 2^64, - // which is what the `(uint64_t)` casts in the source make explicit. - uint64_t mixed = (uint64_t) ctx[0] * mult[0]; - for (int j = 1; j < n; ++j) mixed ^= (uint64_t) ctx[j] * mult[j]; - return mixed; -} - -void ngram_rows(const int32_t* tokens, const int32_t* prev, int n_tokens, const PleConsts& c, uint32_t* out) { - const int n_prev = NGRAM_SIZE - 1; - for (int i = 0; i < n_tokens; ++i) { - int64_t ctx[NGRAM_SIZE]; - ctx[0] = tokens[i]; - bool cut = false; - for (int s = 1; s < NGRAM_SIZE; ++s) { - // `prev` is OLDEST FIRST, so predecessor `s` positions back is entry (n_prev - s): s=1 reads the - // NEWEST. Reading index (s-1) instead walks the window backwards, which still produces indices - // in range and so cannot be caught by a range check - only by an oracle. - const int32_t t = cut ? TOKEN_NULL : prev[i * n_prev + (n_prev - s)]; - // The cut is evaluated BEFORE the value is stored, so the position whose predecessor was EOS is - // itself EOS. Storing first and then cutting would leave position s holding the real token while - // position s+1 became EOS - one token of history too much. - cut = cut || t < 0 || t == PLE_EOS_TOKEN_ID; - ctx[s] = cut ? PLE_EOS_TOKEN_ID : t; - } - for (int n = 2; n <= NGRAM_SIZE; ++n) { - const uint64_t mixed = ngram_mixed(ctx, c.mult, n); - const int base = (n - 2) * HEADS_PER_NGRAM; - for (int g = 0; g < HEADS_PER_NGRAM; ++g) { - const int h = base + g; - out[i * PLE_N_HEADS + h] = (uint32_t) (mixed % c.vocab[h] + c.offset[h]); - } - } - } -} - -namespace { -const int8_t kIq4Nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113}; -} - -int iq4nl_code(int code) { return kIq4Nl[code & 15]; } - -void iq4nl_dequant_row(const uint8_t* row, float* out160) { - for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) { - const uint8_t* blk = row + (size_t) b * 18; - uint16_t dbits; - std::memcpy(&dbits, blk, 2); - const float d = f32_from_f16(dbits); - const uint8_t* qs = blk + 2; - // SPLIT HALVES: qs[j] holds elements j and j+16, not 2j and 2j+1. - for (int j = 0; j < 16; ++j) { - out160[b * 32 + j] = d * (float) kIq4Nl[qs[j] & 0x0F]; - out160[b * 32 + j + 16] = d * (float) kIq4Nl[qs[j] >> 4]; - } - } -} - -namespace { -struct Fp8Table { - float v[256]; - Fp8Table() { - for (int x = 0; x < 256; ++x) { - const int s = x >> 7, e = (x >> 3) & 15, m = x & 7; - float f; - if (e == 15 && m == 7) f = 0.0f; // NaN in e4m3fn; never in a real table, read as 0 - else if (e == 0) f = std::ldexp((float) m / 8.0f, -6); - else f = std::ldexp(1.0f + (float) m / 8.0f, e - 7); - v[x] = s ? -f : f; - } - } -}; -const Fp8Table kFp8; -} // namespace - -void fp8_e4m3_dequant_row(const uint8_t* row, float scale, float* out160) { - for (int j = 0; j < PLE_HEAD_DIM; ++j) out160[j] = kFp8.v[row[j]] * scale; -} - -// --------------------------------------------------------------------------------------------------- -struct PleTable::Impl { - GgufFile* file = nullptr; - const uint8_t* data = nullptr; - void* own = nullptr; // `--ple-io ram`: the table in memory of its own (`data` points into it) - uint64_t own_bytes = 0; - uint64_t n_rows = 0; - bool q5_0 = false; // #296: Q5_0 rows (110 B), the mapped reader only - mutable uint64_t bytes_read = 0; - // Direct mode (plan v0.3 P2): the mapping above is released after the header parse and every row comes - // from an unbuffered SSD read into `raw`. - PleIo mode = PleIo::Mmap; - strata::ngram::PleReader reader; - strata::ngram::PleReader::Ticket ticket; - bool pending = false; - bool locked = false; - uint32_t rows[PLE_N_HEADS] = {}; - uint8_t raw[PLE_N_HEADS * PLE_ROW_BYTES_MAX] = {}; - static constexpr size_t kMaxPrefetch = 16; - size_t n_prefetch = 0; - strata::ngram::PleReader::Ticket prefetch_tickets[kMaxPrefetch] = {}; - uint32_t prefetch_keys[kMaxPrefetch][PLE_N_HEADS] = {}; - uint8_t prefetch_raw[kMaxPrefetch][PLE_N_HEADS * PLE_ROW_BYTES_MAX] = {}; - bool fp8 = false; // F8_E4M3 rows (tools/ple_fp8_pack.py); else IQ4_NL - float scale = 1.0f; // the FP8 table's one scale - uint32_t rb = PLE_ROW_BYTES; // bytes per row - void decode(const uint8_t* row, float* out160) const { - if (fp8) fp8_e4m3_dequant_row(row, scale, out160); - else if (q5_0) - for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) strata::dequantize_q5_0(row + (size_t) b * 22, out160 + b * 32); - else iq4nl_dequant_row(row, out160); - } -}; - -PleTable::PleTable() : impl_(new Impl) {} -PleTable::~PleTable() { close(); delete impl_; } - -bool PleTable::open(const std::string& gguf_path, std::string& err) { - return open(gguf_path, err, PleIoOptions{}); -} - -bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoOptions& io) { - close(); - try { - impl_->file = new GgufFile(gguf_path); - } catch (const std::exception& e) { - err = e.what(); - return false; - } - const TensorInfo* t = impl_->file->find("per_layer_token_embd.weight"); - if (t == nullptr) { - err = "per_layer_token_embd.weight is not in " + gguf_path; - close(); - return false; - } - // [160, 320001536]: ne0 = 160 is the FAST axis, so the ROW index is shape[1] and a row is contiguous. - if (t->shape.size() != 2 || t->shape[0] != (uint64_t) PLE_HEAD_DIM) { - err = "per_layer_token_embd.weight has an unexpected shape"; - close(); - return false; - } - // IQ4_NL (ISTA-DASLab's shard 2, the original's own GGUF), Q5_0 (#296: OrcaRouter's GGUF), or the FP8 table as - // shipped: I8 bytes marked strata.ple.format = f8_e4m3 with strata.ple.scale (tools/ple_fp8_pack.py) - impl_->fp8 = false; - impl_->q5_0 = std::strcmp(t->type_name(), "Q5_0") == 0; - impl_->rb = impl_->q5_0 ? (PLE_HEAD_DIM / 32) * 22 : PLE_ROW_BYTES; - if (std::strcmp(t->type_name(), "I8") == 0) { - const MetaValue* f = impl_->file->get("strata.ple.format"); - const MetaValue* s = impl_->file->get("strata.ple.scale"); - if (f == nullptr || f->s != "f8_e4m3" || s == nullptr || !(s->num() > 0.0)) { - err = "per_layer_token_embd.weight is I8 without strata.ple.format = f8_e4m3 and a positive strata.ple.scale"; - close(); - return false; - } - impl_->fp8 = true; - impl_->scale = (float) s->num(); - impl_->rb = PLE_ROW_BYTES_FP8; - } else if (!impl_->q5_0 && std::strcmp(t->type_name(), "IQ4_NL") != 0) { - err = std::string("per_layer_token_embd.weight is ") + t->type_name() + ", not IQ4_NL, Q5_0 or FP8 (I8)"; - close(); - return false; - } - // PleReader's row_bytes has been a runtime parameter since the FP8 table (160 B rows) needed it; Q5_0's - // 110 B rows go through the exact same generic path (ple_reader_test --selftest covers both 90 and 110 B - // rows: straddling, caching, in-flight tickets, keep-alive). This refusal was stale. - impl_->n_rows = t->shape[1]; - impl_->data = impl_->file->tensor_data(*t); - - // THE CHECK THAT MAKES THE OFFSET FALSIFIABLE. The manifest's `shard2_tensor.offset` is 0, but that is - // the offset within the GGUF's DATA SECTION: the file's first 192 bytes are a header, and reading at 0 - // would decode the header plus 192 bytes of shifted rows - still plausible IQ4_NL, and wrong for every - // row. `GgufFile` parses the header, so `tensor_data` is already correct; this asserts the tensor - // exactly fills the file from there, which is what makes the whole arrangement checkable rather than - // assumed. A wrong data offset would leave a different remainder. - // A shard may hold other tensors too (Swift 1.5's shard 1 holds layers 0-12 and the table): the table must - // then fit inside the file at its own offset; alone in its shard (the original's shard 2) it fills it exactly. - const uint64_t need = impl_->n_rows * (uint64_t) impl_->rb; - const uint64_t have = impl_->file->file_size() - impl_->file->data_start(); - const bool alone = impl_->file->tensors().size() == 1; - if (alone ? need != have : t->offset + need > have) { - char buf[256]; - std::snprintf(buf, sizeof buf, - "PLE table size mismatch: %llu rows x %d B = %llu at offset %llu, but the file holds %llu from " - "data_start %llu", - (unsigned long long) impl_->n_rows, (int) impl_->rb, (unsigned long long) need, - (unsigned long long) t->offset, (unsigned long long) have, - (unsigned long long) impl_->file->data_start()); - err = buf; - close(); - return false; - } - if (io.mode == PleIo::Direct) { - // The parse above is the validated source of the offset; the mapping itself is not kept, so no page of - // the table can enter this process's working set or the file cache through it. - const uint64_t table_offset = impl_->file->data_start() + t->offset; - const uint64_t n_rows = impl_->n_rows; - delete impl_->file; - impl_->file = nullptr; - impl_->data = nullptr; - if (!impl_->reader.open(gguf_path, table_offset, n_rows, io.max_inflight, io.cache_rows, err, io.io_thread, - impl_->rb)) { - close(); - return false; - } - impl_->reader.set_keepalive(io.keepalive_ms, io.keepalive_window_s); - impl_->n_rows = n_rows; - } - if (io.mode == PleIo::Mmap && io.lock && impl_->data != nullptr) { -#if !defined(_WIN32) - // UnbiasedStrata: the table is read into memory of its own, not locked inside the file mapping. Several - // readers load it (a network store's speed is per stream, and a refused read is retried), no later page - // fault can go back to the file, and it does not depend on `ulimit -l` (8 MB in a container). - const uint64_t table_offset = impl_->file->data_start() + t->offset; - void* mem = mmap(nullptr, (size_t) need, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - if (mem == MAP_FAILED) { - err = "cannot allocate " + std::to_string(need >> 20) + " MiB of RAM for the n-gram table: " + std::strerror(errno); - close(); - return false; - } - impl_->own = mem; - impl_->own_bytes = need; - if (!strata::platform::read_range(gguf_path, table_offset, (uint8_t*) mem, need, 16, err, "n-gram table")) { - close(); - return false; - } - delete impl_->file; - impl_->file = nullptr; - impl_->data = (const uint8_t*) mem; - impl_->locked = mlock(mem, (size_t) need) == 0; // extra: the memory is already resident either way -#endif - } - impl_->mode = io.mode; - return true; -} - -void PleTable::wait_prefetches() { - if (impl_->n_prefetch == 0) return; - std::string dummy; - for (size_t i = 0; i < impl_->n_prefetch; ++i) (void) impl_->reader.collect(impl_->prefetch_tickets[i], dummy); - impl_->n_prefetch = 0; -} - -void PleTable::prefetch_rows(const uint32_t* rows16) { - if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) { - for (size_t i = 0; i < impl_->n_prefetch; ++i) - if (std::memcmp(impl_->prefetch_keys[i], rows16, sizeof(uint32_t) * PLE_N_HEADS) == 0) return; - if (impl_->n_prefetch >= Impl::kMaxPrefetch) wait_prefetches(); - const size_t slot = impl_->n_prefetch++; - std::memcpy(impl_->prefetch_keys[slot], rows16, sizeof(uint32_t) * PLE_N_HEADS); - impl_->prefetch_tickets[slot] = impl_->reader.issue(impl_->prefetch_keys[slot], PLE_N_HEADS, impl_->prefetch_raw[slot]); - return; - } -#if defined(_WIN32) - if (impl_->data != nullptr && g_ple_prefetch) { - WIN32_MEMORY_RANGE_ENTRY ranges[PLE_N_HEADS]; - ULONG_PTR n = 0; - for (int h = 0; h < PLE_N_HEADS; ++h) { - if (rows16[h] >= impl_->n_rows) continue; - ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * impl_->rb); - ranges[n].NumberOfBytes = impl_->rb; - ++n; - } - if (n > 0) (void) PrefetchVirtualMemory(GetCurrentProcess(), n, ranges, 0); - } -#endif -} - -void PleTable::close() { - wait_prefetches(); - impl_->reader.close(); - impl_->pending = false; - impl_->locked = false; // the unmap below releases the lock - impl_->mode = PleIo::Mmap; - delete impl_->file; - impl_->file = nullptr; - impl_->data = nullptr; -#if !defined(_WIN32) - if (impl_->own != nullptr) munmap(impl_->own, (size_t) impl_->own_bytes); -#endif - impl_->own = nullptr; - impl_->own_bytes = 0; - impl_->n_rows = 0; - impl_->rb = PLE_ROW_BYTES; - impl_->q5_0 = false; - impl_->fp8 = false; -} - -bool PleTable::is_open() const { return impl_->data != nullptr || impl_->reader.is_open(); } -bool PleTable::locked() const { return impl_->locked; } -const char* PleTable::format() const { return impl_->fp8 ? "F8_E4M3" : impl_->q5_0 ? "Q5_0" : "IQ4_NL"; } -PleIo PleTable::mode() const { return impl_->mode; } -uint64_t PleTable::rows() const { return impl_->n_rows; } -uint64_t PleTable::bytes_read() const { return impl_->bytes_read; } - -void PleTable::read_row(uint32_t row, float* out160) const { - if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) { - uint8_t raw[PLE_ROW_BYTES_MAX]; - std::string err; - const auto t = impl_->reader.issue(&row, 1, raw); - if (!impl_->reader.collect(t, err)) { - std::memset(out160, 0, (size_t) PLE_HEAD_DIM * sizeof(float)); - return; - } - impl_->decode(raw, out160); - impl_->bytes_read += impl_->rb; - return; - } - if (impl_->data == nullptr || row >= impl_->n_rows) { - std::memset(out160, 0, (size_t) PLE_HEAD_DIM * sizeof(float)); - return; - } - impl_->decode(impl_->data + (size_t) row * impl_->rb, out160); - impl_->bytes_read += impl_->rb; -} - -bool PleTable::issue(const uint32_t* rows16) { - wait_prefetches(); - std::memcpy(impl_->rows, rows16, sizeof impl_->rows); - if (impl_->mode == PleIo::Direct) { - if (impl_->pending) return false; // one token in flight per table - impl_->ticket = impl_->reader.issue(impl_->rows, PLE_N_HEADS, impl_->raw); - impl_->pending = true; - return true; - } -#if defined(_WIN32) - if (impl_->data != nullptr && g_ple_prefetch) { - WIN32_MEMORY_RANGE_ENTRY ranges[PLE_N_HEADS]; - ULONG_PTR n = 0; - for (int h = 0; h < PLE_N_HEADS; ++h) { - if (rows16[h] >= impl_->n_rows) continue; - ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * impl_->rb); - ranges[n].NumberOfBytes = impl_->rb; - ++n; - } - if (n > 0) (void) PrefetchVirtualMemory(GetCurrentProcess(), n, ranges, 0); - } -#endif - impl_->pending = true; - return true; -} - -bool PleTable::collect(float* out2560, std::string& err) { - if (!impl_->pending) { err = "PleTable::collect without issue"; return false; } - impl_->pending = false; - if (impl_->mode == PleIo::Direct) { - if (!impl_->reader.collect(impl_->ticket, err)) return false; - for (int h = 0; h < PLE_N_HEADS; ++h) - impl_->decode(impl_->raw + (size_t) h * impl_->rb, out2560 + (size_t) h * PLE_HEAD_DIM); - impl_->bytes_read += (uint64_t) PLE_N_HEADS * impl_->rb; - return true; - } - for (int h = 0; h < PLE_N_HEADS; ++h) read_row(impl_->rows[h], out2560 + (size_t) h * PLE_HEAD_DIM); - return true; -} - -bool PleTable::gather_batch(const uint32_t* rows, size_t n_tokens, float* out, std::string& err) { - if (impl_->pending) { err = "PleTable::gather_batch while a token is in flight"; return false; } - const size_t n = n_tokens * (size_t) PLE_N_HEADS; - if (impl_->mode == PleIo::Direct) { - // Fast path: if all requested tokens match our in-flight/completed prefetch slots, collect them directly - // without issuing a second PleReader ticket or copying through RowCache. - if (impl_->n_prefetch >= n_tokens && n_tokens <= Impl::kMaxPrefetch) { - bool exact_match = true; - for (size_t t = 0; t < n_tokens; ++t) { - if (std::memcmp(impl_->prefetch_keys[t], rows + t * PLE_N_HEADS, sizeof(uint32_t) * PLE_N_HEADS) != 0) { - exact_match = false; - break; - } - } - if (exact_match) { - for (size_t i = 0; i < impl_->n_prefetch; ++i) { - if (!impl_->reader.collect(impl_->prefetch_tickets[i], err)) { - impl_->n_prefetch = 0; - return false; - } - } - impl_->n_prefetch = 0; - for (size_t t = 0; t < n_tokens; ++t) { - for (int h = 0; h < PLE_N_HEADS; ++h) { - impl_->decode(impl_->prefetch_raw[t] + (size_t) h * impl_->rb, - out + (t * PLE_N_HEADS + (size_t) h) * PLE_HEAD_DIM); - } - } - impl_->bytes_read += (uint64_t) n * impl_->rb; - return true; - } - } - wait_prefetches(); - std::vector raw(n * impl_->rb); - const auto ticket = impl_->reader.issue(rows, n, raw.data()); - if (!impl_->reader.collect(ticket, err)) return false; - for (size_t i = 0; i < n; ++i) impl_->decode(raw.data() + i * impl_->rb, out + i * PLE_HEAD_DIM); - impl_->bytes_read += (uint64_t) n * impl_->rb; - return true; - } - wait_prefetches(); - for (size_t i = 0; i < n; ++i) read_row(rows[i], out + i * PLE_HEAD_DIM); - return true; -} - -void PleTable::set_injected_delay_us(double us) { impl_->reader.set_injected_delay_us(us); } - -std::string PleTable::io_report() const { - if (impl_->mode != PleIo::Direct || !impl_->reader.is_open()) return {}; - const strata::ngram::ReaderStats s = impl_->reader.snapshot(); - char buf[400]; - int n = std::snprintf(buf, sizeof buf, - "ple io: %llu rows, %.1f%% row-cache hits, %llu SSD reads (%.1f MB), read p50 %.0f us p99 %.0f us, " - "blocked %.3f ms total (submit %.3f ms), cache %llu/%llu rows", - (unsigned long long) s.requests, s.requests ? 100.0 * (double) s.cache_hits / (double) s.requests : 0.0, - (unsigned long long) s.reads, (double) s.bytes / 1e6, s.percentile(0.5), s.percentile(0.99), - s.wait_us / 1000.0, s.submit_us / 1000.0, (unsigned long long) impl_->reader.cache_size(), - (unsigned long long) impl_->reader.cache_capacity()); - if (s.keepalive_reads > 0 && n > 0 && n < (int) sizeof buf) - std::snprintf(buf + n, sizeof buf - (size_t) n, ", SSD kept awake by %llu reads (slowest %.1f ms)", - (unsigned long long) s.keepalive_reads, s.keepalive_us_max / 1000.0); - return buf; -} - -void PleTable::gather(const uint32_t* rows16, float* out2560) const { - if (impl_->mode == PleIo::Direct) { - // `gather` stays const for its existing callers; the reader's state is the table's I/O state. - PleTable* self = const_cast(this); - std::string err; - if (!self->issue(rows16) || !self->collect(out2560, err)) { - std::fprintf(stderr, "PleTable::gather: %s\n", err.empty() ? "a token is already in flight" : err.c_str()); - std::memset(out2560, 0, (size_t) NG_N_EMBD * sizeof(float)); - } - return; - } - // ================================ SIXTEEN SERIAL PAGE FAULTS, MEASURED ================================ - // - // **THIS COST 2.10-2.61 ms PER TOKEN AND HAD NEVER BEEN IN THE PLAN'S BUDGET AT ALL.** The round-309 - // `token host phases` line put it second behind the layer loop among avoidable terms, and the arithmetic - // says why: the table is 320,001,536 rows of `PLE_ROW_BYTES` = 90 B in a 26.8 GB mapping, so the sixteen - // rows a token needs are 1,440 B - **0.5 MB/s**. That is not bandwidth, it is latency: sixteen reads into - // sixteen different 4 KB pages scattered across 26.8 GB, taken ONE AT A TIME, and on this machine the PLE - // shard is 26.8 GB against 63 GB of RAM that the 31.6 GB expert arena is also competing for, so they are - // not in the OS cache. Sixteen serial NVMe reads at ~150 us is 2.4 ms, which is the measurement. - // - // `PrefetchVirtualMemory` issues all sixteen in ONE call and lets them complete in parallel. It is a hint - // and cannot change the answer - a range it does not fetch is simply faulted in by the read that follows - - // so the only risk is that it does nothing. -#if defined(_WIN32) - if (impl_->data != nullptr && g_ple_prefetch) { - WIN32_MEMORY_RANGE_ENTRY ranges[PLE_N_HEADS]; - ULONG_PTR n = 0; - for (int h = 0; h < PLE_N_HEADS; ++h) { - // Out-of-range rows are handled by `read_row` as zeros and have no address to prefetch. - if (rows16[h] >= impl_->n_rows) continue; - ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * impl_->rb); - ranges[n].NumberOfBytes = impl_->rb; - ++n; - } - if (n > 0) (void) PrefetchVirtualMemory(GetCurrentProcess(), n, ranges, 0); - } -#endif - // HEAD-SLOWEST, which is what `ggml_get_rows` does and what the source's own comment says: head h's 160 - // values occupy [h*160, (h+1)*160). A head-fastest layout would put element (d, h) at d*16 + h and needs - // a real transpose - a reshape of the same flat buffer compares equal and would make the check vacuous. - for (int h = 0; h < PLE_N_HEADS; ++h) read_row(rows16[h], out2560 + (size_t) h * PLE_HEAD_DIM); -} - -} // namespace strata::kernels diff --git a/src/kernels/ple_fp8_parity.cpp b/src/kernels/ple_fp8_parity.cpp deleted file mode 100644 index 09dd199..0000000 --- a/src/kernels/ple_fp8_parity.cpp +++ /dev/null @@ -1,84 +0,0 @@ -// src/kernels/ple_fp8_parity.cpp - the FP8 PLE table (tools/ple_fp8_pack.py) read through PleTable, against values -// decoded from the checkpoint itself, and against the IQ4_NL table it replaces. -// -// ple_fp8_parity [] -// -// reference.bin: int32 n, uint32 rows[n], float32 values[n][160] - the rows as torch decodes the checkpoint's -// F8_E4M3 bytes, times its weight_scale (n a multiple of 16 for the gather_batch check). Every row must match BIT FOR BIT through -// both I/O modes (Direct and Mmap) and through the prompt path's gather_batch. With the IQ4_NL shard the same rows -// are compared too: same table, so a correlation near 0.997 - a shifted row order would be ~0. -#include "strata/kernels/ngram.hpp" - -#include -#include -#include -#include -#include -#include - -namespace k = strata::kernels; - -int main(int argc, char** argv) { - if (argc < 3) { - std::fprintf(stderr, "usage: ple_fp8_parity []\n"); - return 2; - } - std::ifstream f(argv[2], std::ios::binary); - int32_t n = 0; - f.read((char*) &n, 4); - std::vector rows((size_t) n); - std::vector ref((size_t) n * k::PLE_HEAD_DIM); - f.read((char*) rows.data(), (std::streamsize) rows.size() * 4); - f.read((char*) ref.data(), (std::streamsize) ref.size() * 4); - if (!f || n <= 0) { std::fprintf(stderr, "cannot read %s\n", argv[2]); return 2; } - - int bad = 0; - for (const k::PleIo mode : {k::PleIo::Direct, k::PleIo::Mmap}) { - k::PleTable t; - std::string err; - k::PleIoOptions io; - io.mode = mode; - if (!t.open(argv[1], err, io)) { std::fprintf(stderr, "open: %s\n", err.c_str()); return 1; } - std::vector got((size_t) n * k::PLE_HEAD_DIM); - for (int i = 0; i < n; ++i) t.read_row(rows[(size_t) i], got.data() + (size_t) i * k::PLE_HEAD_DIM); - int diff = 0; - for (size_t j = 0; j < got.size(); ++j) diff += std::memcmp(&got[j], &ref[j], 4) != 0; - std::vector batch((size_t) n * k::PLE_HEAD_DIM); // the prompt path: all rows as one request - const bool ok = t.gather_batch(rows.data(), (size_t) n / k::PLE_N_HEADS, batch.data(), err); - int bdiff = 0; - const size_t nb = (size_t) n / k::PLE_N_HEADS * k::PLE_N_HEADS * k::PLE_HEAD_DIM; - for (size_t j = 0; ok && j < nb; ++j) bdiff += std::memcmp(&batch[j], &ref[j], 4) != 0; - std::printf("%-6s %s, %llu rows: read_row %d/%zu values differ, gather_batch %s %d differ\n", - mode == k::PleIo::Direct ? "Direct" : "Mmap", t.format(), (unsigned long long) t.rows(), diff, - got.size(), ok ? "ok," : "FAILED,", bdiff); - bad += diff + bdiff + (ok ? 0 : 1) + (std::strcmp(t.format(), "F8_E4M3") != 0); - } - if (argc > 3) { - k::PleTable q; - std::string err; - if (!q.open(argv[3], err)) { std::fprintf(stderr, "open %s: %s\n", argv[3], err.c_str()); return 1; } - double cmin = 1, rsum = 0; - int counted = 0; - std::vector v(k::PLE_HEAD_DIM); - for (int i = 0; i < n; ++i) { - q.read_row(rows[(size_t) i], v.data()); - const float* r = ref.data() + (size_t) i * k::PLE_HEAD_DIM; - double sa = 0, sb = 0, sab = 0, sa2 = 0, sb2 = 0, e2 = 0, r2 = 0; - for (int j = 0; j < k::PLE_HEAD_DIM; ++j) { - sa += r[j]; sb += v[j]; sab += (double) r[j] * v[j]; sa2 += (double) r[j] * r[j]; sb2 += (double) v[j] * v[j]; - e2 += ((double) v[j] - r[j]) * ((double) v[j] - r[j]); r2 += (double) r[j] * r[j]; - } - if (r2 == 0) continue; // an all-zero row (the table has some) - const double m = k::PLE_HEAD_DIM; - const double c = (sab - sa * sb / m) / std::sqrt((sa2 - sa * sa / m) * (sb2 - sb * sb / m)); - cmin = std::fmin(cmin, c); - rsum += std::sqrt(e2 / r2); - ++counted; - } - std::printf("IQ4_NL table, same rows: correlation min %.4f, error vs FP8 %.1f%% mean (%d non-zero rows)\n", - cmin, 100 * rsum / (counted ? counted : 1), counted); - if (cmin < 0.98) ++bad; - } - std::printf("RESULT: %s\n", bad ? "MISMATCH" : "FP8 rows exact"); - return bad ? 1 : 0; -} diff --git a/src/kernels/ple_oracle_vectors.inc b/src/kernels/ple_oracle_vectors.inc deleted file mode 100644 index 60c53b3..0000000 --- a/src/kernels/ple_oracle_vectors.inc +++ /dev/null @@ -1,105 +0,0 @@ -// GENERATED by tests/python/gen_ple_oracle.py - DO NOT EDIT BY HAND. -// -// Sources, none of them this project's own code: -// hash ref/ngram.py::ngram_rows (qwen4exp.cpp L1092-1124, validated bit-exact in round 101) -// table the ORIGINAL GGUF's bytes, read at the offset the validated gguf_reader reports, -// dequantized with numpy -// offsets pack/full/manifest.json - -#pragma once -#include - -namespace strata::kernels::ple_oracle { - -struct HashCase { const char* name; int n_tokens; const int32_t* tokens; - const int32_t* prev; const uint32_t* rows; }; - -// window direction -inline const int32_t case0_tokens[4] = {11, 22, 33, 44}; -inline const int32_t case0_prev[8] = {-1, -1, 11, -1, 22, 11, 33, 22}; -inline const uint32_t case0_rows[64] = { - 13555483, 24877159, 54278900, 63631058, 98394898, 117447587, 136774765, 157274238, 173487882, 192109366, 213364329, 236577563, 258758149, 262164274, 283572184, 312653920, - 3278367, 29880471, 46922633, 62971672, 94904487, 113013549, 120925297, 159537733, 161636484, 186269036, 207870452, 237789268, 242975733, 269388091, 285131318, 305889870, - 2485282, 23858032, 54544880, 69506925, 82331991, 106607168, 133019998, 141570514, 173894108, 180423171, 211374553, 239810912, 253076960, 266343146, 290765399, 312876099, - 12721672, 27113445, 44309803, 60385209, 97021817, 115900810, 134219364, 151977589, 161183764, 181257609, 201344488, 221596875, 241635416, 261674107, 281687144, 301751935, -}; -// EOS one back cuts both -inline const int32_t case1_tokens[3] = {7, 8, 9}; -inline const int32_t case1_prev[6] = {-1, -1, 7, 248044, 248044, 7}; -inline const uint32_t case1_rows[48] = { - 2927653, 34980843, 54748278, 66612378, 97814964, 109013870, 126560393, 151352333, 167888935, 182235580, 215170017, 237467519, 247510681, 278779700, 296141806, 304994522, - 7508793, 29969020, 54939975, 74089003, 91535754, 104816064, 125484693, 154439441, 164805529, 181662903, 214193203, 238193346, 259492009, 262016223, 296463606, 310742083, - 5471414, 32902469, 56618078, 65819961, 82278798, 107765152, 125994638, 156967341, 179716672, 187881262, 219224344, 222418510, 250276020, 278493068, 281311927, 316005603, -}; -// NULL reads as EOS -inline const int32_t case2_tokens[2] = {100, 101}; -inline const int32_t case2_prev[4] = {-1, -1, -1, -1}; -inline const uint32_t case2_rows[32] = { - 5727835, 21884476, 43702108, 66434789, 84094509, 104112171, 134886528, 157314943, 162363667, 189466439, 200618315, 232121522, 258547276, 266199001, 289022207, 305180972, - 14526383, 36975477, 51939184, 65076202, 94510971, 111786935, 138448715, 155393638, 167579692, 181767276, 211184823, 226303266, 246271192, 267465224, 281469089, 313531602, -}; -// token id 0 is NOT missing -inline const int32_t case3_tokens[2] = {100, 101}; -inline const int32_t case3_prev[4] = {0, 0, 100, 0}; -inline const uint32_t case3_rows[32] = { - 223356, 29869136, 44693816, 65450370, 83243562, 109175069, 138072664, 149936704, 175869089, 193667153, 214433731, 233779437, 242682975, 271587098, 294555343, 309396483, - 9825591, 35767834, 58740777, 62904867, 86476006, 107666813, 129453358, 151836075, 160726459, 190511348, 208596315, 234569026, 259467109, 264365567, 292665383, 314164387, -}; -// own EOS does not cut itself -inline const int32_t case4_tokens[3] = {248044, 5, 248044}; -inline const int32_t case4_prev[6] = {-1, -1, 248044, -1, 5, 248044}; -inline const uint32_t case4_rows[48] = { - 9663979, 26558231, 56120240, 74755659, 80459717, 109265651, 132697467, 151022725, 170054832, 192967038, 200687722, 225763581, 259275737, 272983544, 297596484, 300986548, - 15389869, 39778609, 55713969, 62213332, 88817728, 118483999, 133731511, 155458159, 179763390, 197956758, 205378969, 220499474, 242466248, 265658744, 293662119, 315720898, - 9663979, 26558231, 56120240, 74755659, 80459717, 109265651, 132697467, 151022725, 170054832, 192967038, 200687722, 225763581, 259275737, 272983544, 297596484, 300986548, -}; -// real vocabulary ids -inline const int32_t case5_tokens[5] = {248043, 12345, 248043, 7, 200000}; -inline const int32_t case5_prev[10] = {-1, -1, 248043, -1, 12345, 248043, 248043, 12345, 7, 248043}; -inline const uint32_t case5_rows[80] = { - 5224855, 30284709, 43929396, 72280505, 94883662, 109322550, 131203836, 140794991, 166459826, 181131035, 209237474, 226844350, 246236135, 265823742, 299063341, 305586418, - 11270970, 23825822, 53627731, 75297762, 86108900, 117131242, 124369521, 148669731, 173053968, 186938961, 219076364, 237563026, 246838602, 277288915, 294366759, 301712965, - 9040325, 23423119, 51729309, 72606490, 88803423, 101106903, 139785146, 145105493, 165075797, 186774126, 216848848, 228384799, 252197080, 276291559, 284385762, 305326936, - 4918924, 35785322, 51404601, 69479989, 96595301, 119006811, 132661231, 157603286, 167367331, 194295259, 207336314, 231383366, 248222822, 265383752, 291175661, 300670030, - 19540326, 36155593, 54730668, 61035256, 83860210, 111525643, 123077188, 158579165, 171421264, 181503411, 210257194, 220050508, 255765827, 271545193, 290152687, 303296503, -}; - -inline const HashCase kHashCases[] = { - {"window direction", 4, case0_tokens, case0_prev, case0_rows}, - {"EOS one back cuts both", 3, case1_tokens, case1_prev, case1_rows}, - {"NULL reads as EOS", 2, case2_tokens, case2_prev, case2_rows}, - {"token id 0 is NOT missing", 2, case3_tokens, case3_prev, case3_rows}, - {"own EOS does not cut itself", 3, case4_tokens, case4_prev, case4_rows}, - {"real vocabulary ids", 5, case5_tokens, case5_prev, case5_rows}, -}; -inline constexpr int kHashCaseCount = 6; - -// The table: sampled values of two rows, plus the whole-row L1 sums so a wrong codebook or a -// wrong scale cannot hide between the samples. Row 0 and the LAST row. -inline constexpr uint64_t kTableRows = 320001536ull; -inline constexpr uint64_t kTableDataStart = 192ull; -inline constexpr uint64_t kTableFileSize = 28800138432ull; -inline const uint32_t kProbeRows[] = {0, 12345, 320001535}; -inline constexpr int kProbeCount = 3; -inline const float kProbeHead[][8] = { - {-1.001119614e-02f, 1.290917397e-02f, -1.817822456e-02f, 1.290917397e-02f, -6.586313248e-03f, 5.795955658e-03f, -6.586313248e-03f, 5.795955658e-03f}, - {5.563795567e-03f, -4.314780235e-03f, 3.974139690e-03f, -1.476109028e-03f, -1.135468483e-04f, 1.135468483e-03f, -1.010566950e-02f, -6.017982960e-03f}, - {0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f}, -}; -inline const float kProbeTail[][8] = { - {2.571296692e-02f, 1.607060432e-02f, 3.139948845e-02f, 5.439281464e-03f, -1.705956459e-02f, -3.214120865e-03f, -2.200436592e-02f, 2.472400665e-03f}, - {-1.942408085e-02f, 5.811929703e-03f, -9.941458702e-03f, 3.823637962e-03f, -5.353093147e-03f, -1.529455185e-03f, -1.529455185e-03f, -5.353093147e-03f}, - {0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f}, -}; -inline const double kProbeSum[] = {2.011959553e+00, 9.968549609e-01, 0.000000000e+00}; -inline constexpr float kInterleavedSeparation = 1.253766603e+00f; - -// pack/full/dense.bin regions for the two quantized PLE weights -inline constexpr uint64_t kKeyCodesOffset = 1017723776ull; -inline constexpr uint64_t kKeyCodesBytes = 6553600ull; -inline constexpr uint64_t kKeyScalesOffset = 1024277376ull; -inline constexpr uint64_t kKeyScalesBytes = 819200ull; -inline constexpr uint64_t kValueOffset = 1025219456ull; -inline constexpr uint64_t kValueBytes = 26214400ull; - -} // namespace strata::kernels::ple_oracle diff --git a/src/kernels/ple_parity.cpp b/src/kernels/ple_parity.cpp deleted file mode 100644 index 20da022..0000000 --- a/src/kernels/ple_parity.cpp +++ /dev/null @@ -1,1184 +0,0 @@ -// src/kernels/ple_parity.cpp - P2.S4's test: the n-gram hash, the IQ4_NL table read, and the PLE block. -// -// THREE PARTS, THREE DIFFERENT ORACLES, and none of them is this project's own code: -// -// A. THE HASH against `ref/ngram.py::ngram_rows`, via `ple_oracle_vectors.inc` (generated). The properties -// are asserted OBSERVABLE first - XOR vs sum, `%` vs `&`, the cut DIRECTION, the NULL sentinel - because -// each rival reading produces a perfectly valid index in range. -// B. THE TABLE against numpy reading the ORIGINAL GGUF at the offset the validated `gguf_reader` reports. -// C. THE BLOCK against ggml's own graph, captured in `bench/micro/ple_in.bin` / `ple_out.bin` by -// `ple_layer_xcheck.cpp`. That file records EVERY intermediate (key, value, gate, gated, normalized, -// conv_out, result), so a mismatch can be attributed to a stage instead of guessed at - and the weights -// in it were checked to be the artifact's real ones before this test was written. -#include "strata/kernels/ple.hpp" -#include "strata/kernels/ngram.hpp" -#include "strata/kernels/f16_bits.hpp" -#include "strata/kernels/native_mmvq.hpp" -#include "ple_oracle_vectors.inc" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace k = strata::kernels; -namespace o = strata::kernels::ple_oracle; - -namespace { - -void ck(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -/// TOLERANCE CHECKS MUST BE NaN-SAFE, and `x <= t` is not. -/// -/// `x <= t` AND `x > t` are BOTH false for NaN, so a check written either way can silently pass - round 197 -/// found `shared_expert_parity` printing a perfect score for an entirely-NaN fixture because the accumulator -/// was `if (rel > worst) worst = rel;` and NaN is never greater. Every comparison in this file goes through -/// `le`/`gt`, which require the value to be FINITE first, and every compared pair is counted for non-finite -/// entries and the count printed. A NaN fixture is then a loud failure rather than a green line. -bool le(double x, double t) { return std::isfinite(x) && x <= t; } -bool gt(double x, double t) { return std::isfinite(x) && x > t; } - -/// How many entries of `a` are not finite. Printed next to every comparison. -long long nonfinite(const float* a, size_t n) { - long long k = 0; - for (size_t i = 0; i < n; ++i) - if (!std::isfinite(a[i])) ++k; - return k; -} - -/// Normalised L1 with the reference magnitude returned. For the STAGE comparisons a plain |ref| denominator -/// is right: these are dense vectors of O(1) values with no cancellation between them. -/// -/// Returns NaN if EITHER side has a non-finite entry, so a caller that forgets `le`/`gt` still cannot read a -/// finite-looking number out of a broken fixture. -double rel_l1(const float* a, const float* b, size_t n, double* mag_out = nullptr, - long long* nf_out = nullptr) { - double d = 0, m = 0; - long long nf = 0; - for (size_t i = 0; i < n; ++i) { - if (!std::isfinite(a[i]) || !std::isfinite(b[i])) { ++nf; continue; } - d += std::fabs((double) a[i] - (double) b[i]); - m += std::fabs((double) a[i]); - } - if (mag_out) *mag_out = m / (double) (n ? n : 1); - if (nf_out) *nf_out = nf; - if (nf) return std::nan(""); - return d / (m > 1e-30 ? m : 1e-30); -} - -/// The file's size, WITHOUT reading it. -/// -/// The first version of this test called `read_file(gguf)` - which reads the WHOLE file into a vector - three -/// times, on a 28.8 GB GGUF. That is 27 GB of RSS, three full passes over the file, and a 132-second ctest -/// entry in a suite where every other test is under a second. A test that slow stops being run, which is how -/// a gate stops being a gate. Everything below now reads only the bytes it actually compares. -long long file_size(const char* path) { - std::FILE* f = std::fopen(path, "rb"); - if (!f) return -1; -#if defined(_MSC_VER) - _fseeki64(f, 0, SEEK_END); - const long long n = _ftelli64(f); -#else - std::fseek(f, 0, SEEK_END); - const long long n = std::ftell(f); -#endif - std::fclose(f); - return n; -} - -/// `n` bytes at `off`, or an empty vector. -std::vector read_at(const char* path, long long off, size_t n) { - std::vector v(n); - std::FILE* f = std::fopen(path, "rb"); - if (!f) return {}; -#if defined(_MSC_VER) - if (_fseeki64(f, off, SEEK_SET) != 0) { std::fclose(f); return {}; } -#else - if (std::fseek(f, (long) off, SEEK_SET) != 0) { std::fclose(f); return {}; } -#endif - const size_t got = std::fread(v.data(), 1, n, f); - std::fclose(f); - if (got != n) return {}; - return v; -} - -/// Only used for the pack, which is 5.4 GB rather than 28.8 GB - and even then the caller says which region. -std::vector read_path(const char* path) { - const long long n = file_size(path); - if (n <= 0) return {}; - return read_at(path, 0, (size_t) n); -} - -/// Dequantize one IQ4_NL row with an INTERLEAVED nibble order, to show the correct split-half order is -/// observable. Deliberately shares nothing with the kernel's decoder. -void deq_interleaved(const uint8_t* row, float* out160) { - for (int b = 0; b < k::PLE_HEAD_DIM / 32; ++b) { - const uint8_t* blk = row + (size_t) b * 18; - uint16_t db; - std::memcpy(&db, blk, 2); - const float d = k::f32_from_f16(db); - for (int j = 0; j < 16; ++j) { - out160[b * 32 + 2 * j] = d * (float) k::iq4nl_code(blk[2 + j] & 0x0F); - out160[b * 32 + 2 * j + 1] = d * (float) k::iq4nl_code(blk[2 + j] >> 4); - } - } -} - -struct PleCapture { - int n_embd = 0, hc = 0, nt = 0, kern = 0, dil = 0; - float eps = 0.0f; - std::vector emb, hidden, w_key, w_value, w_nk, w_nq, w_nc, w_conv, hist; - // oracle outputs - std::vector key, value, gate, gated, normalized, conv_out, result; -}; - -bool load_capture(const char* in_path, const char* out_path, PleCapture& c) { - std::FILE* fi = std::fopen(in_path, "rb"); - if (!fi) return false; - int32_t h[5] = {0}; - if (std::fread(h, 4, 5, fi) != 5) { std::fclose(fi); return false; } - c.n_embd = h[0]; c.hc = h[1]; c.nt = h[2]; c.kern = h[3]; c.dil = h[4]; - if (std::fread(&c.eps, 4, 1, fi) != 1) { std::fclose(fi); return false; } - // Validate before deriving sizes or allocating. This bounded diagnostic - // format is for this model's geometry and at most 64 captured tokens. - if (c.n_embd != k::NG_N_EMBD || c.hc != k::NG_HC || c.nt <= 0 || c.nt > 64 || - c.kern != k::PLE_CONV_KERNEL || c.dil != k::NGRAM_SIZE || c.eps != k::NG_RMS_EPS) { - std::fclose(fi); return false; - } - const long long nd = c.n_embd, hcd = (long long) c.hc * c.n_embd, nt = c.nt, - hist = (long long) (c.kern - 1) * c.dil; - const long long in_bytes = 24 + 4 * (nt * nd + nt * hcd + hcd * nd + nd * nd + - 3 * hcd + hcd * c.kern + hist * hcd); - const long long out_bytes = 12 + 4 * nt * (5 * hcd + nd + c.hc); - if (file_size(in_path) != in_bytes || file_size(out_path) != out_bytes) { - std::fclose(fi); return false; - } - auto rd = [](std::FILE* file, std::vector& v, long long n) { - v.resize((size_t) n); - return n == 0 || std::fread(v.data(), 4, (size_t) n, file) == (size_t) n; - }; - bool ok = rd(fi, c.emb, nt * nd) && rd(fi, c.hidden, nt * hcd) && rd(fi, c.w_key, hcd * nd) && - rd(fi, c.w_value, nd * nd) && rd(fi, c.w_nk, hcd) && rd(fi, c.w_nq, hcd) && rd(fi, c.w_nc, hcd) && - rd(fi, c.w_conv, hcd * c.kern) && rd(fi, c.hist, hist * hcd); - std::fclose(fi); - if (!ok) return false; - - std::FILE* fo = std::fopen(out_path, "rb"); - if (!fo) return false; - int32_t oh[3] = {0}; - if (std::fread(oh, 4, 3, fo) != 3) { std::fclose(fo); return false; } - if (oh[0] != c.n_embd || oh[1] != hcd || oh[2] != c.nt) { std::fclose(fo); return false; } - ok = rd(fo, c.key, nt * hcd) && rd(fo, c.value, nt * nd) && rd(fo, c.gate, nt * c.hc) && rd(fo, c.gated, nt * hcd) && - rd(fo, c.normalized, nt * hcd) && rd(fo, c.conv_out, nt * hcd) && rd(fo, c.result, nt * hcd); - std::fclose(fo); - return ok; -} - -int history_advance_regression() { - const size_t channels = (size_t) k::NG_HC_DIM, rows = (size_t) k::NG_HIST, guard = 16; - const size_t count = channels * rows; - std::vector expected(count), normalized(channels), actual(count); - for (size_t c = 0; c < channels; ++c) - for (size_t r = 0; r < rows; ++r) expected[c * rows + r] = -float(c * 16 + r + 1); - float *history_storage = nullptr, *norm_storage = nullptr; - ck(cudaMalloc(&history_storage, (count + 2 * guard) * sizeof(float)), "history regression allocation"); - ck(cudaMalloc(&norm_storage, (channels + 2 * guard) * sizeof(float)), "history norm allocation"); - ck(cudaMemset(history_storage, 0xa5, (count + 2 * guard) * sizeof(float)), "history guard init"); - ck(cudaMemset(norm_storage, 0xa5, (channels + 2 * guard) * sizeof(float)), "history norm guard init"); - float* history = history_storage + guard; - float* norm = norm_storage + guard; - ck(cudaMemcpy(history, expected.data(), count * sizeof(float), cudaMemcpyHostToDevice), "history initial values"); - cudaStream_t stream; - cudaGraph_t graph; - cudaGraphExec_t executable; - ck(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), "history regression stream"); - ck(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "history regression capture"); - k::ple_history_advance(history, norm, stream); - ck(cudaStreamEndCapture(stream, &graph), "history regression capture end"); - ck(cudaGraphInstantiate(&executable, graph, nullptr, nullptr, 0), "history regression instantiate"); - int bad = 0; - for (int token = 0; token < 12; ++token) { - for (size_t c = 0; c < channels; ++c) { - normalized[c] = float((token + 1) * 1000000 + c); // distinct exactly represented integers - for (size_t r = 0; r + 1 < rows; ++r) expected[c * rows + r] = expected[c * rows + r + 1]; - expected[c * rows + rows - 1] = normalized[c]; - } - ck(cudaMemcpyAsync(norm, normalized.data(), channels * sizeof(float), cudaMemcpyHostToDevice, stream), "history new normalized row"); - ck(cudaGraphLaunch(executable, stream), "history captured advance"); - ck(cudaStreamSynchronize(stream), "history captured advance sync"); - ck(cudaMemcpy(actual.data(), history, count * sizeof(float), cudaMemcpyDeviceToHost), "history readback"); - if (std::memcmp(actual.data(), expected.data(), count * sizeof(float)) != 0) { - std::printf(" history advance mismatch after token %d\n", token); - ++bad; - } - } - bool overlap_refused = false, null_refused = false; - try { k::ple_history_advance(history, history + 1, stream); } - catch (const std::invalid_argument&) { overlap_refused = true; } - try { k::ple_history_advance(history, nullptr, stream); } - catch (const std::invalid_argument&) { null_refused = true; } - if (!overlap_refused || !null_refused) ++bad; - auto guard_ok = [&](float* storage, size_t payload) { - uint8_t before[64], after[64]; - ck(cudaMemcpy(before, storage, sizeof(before), cudaMemcpyDeviceToHost), "history prefix guard"); - ck(cudaMemcpy(after, storage + guard + payload, sizeof(after), cudaMemcpyDeviceToHost), "history suffix guard"); - return std::all_of(before, before + 64, [](uint8_t b) { return b == 0xa5; }) && - std::all_of(after, after + 64, [](uint8_t b) { return b == 0xa5; }); - }; - if (!guard_ok(history_storage, count) || !guard_ok(norm_storage, channels)) ++bad; - std::printf(" PLE history 12 captured steps, row-fastest state and guards: %s\n", bad == 0 ? "pass" : "FAIL"); - ck(cudaGraphExecDestroy(executable), "history graph exec destroy"); - ck(cudaGraphDestroy(graph), "history graph destroy"); - ck(cudaStreamDestroy(stream), "history stream destroy"); - cudaFree(history_storage); cudaFree(norm_storage); - return bad; -} - -} // namespace - -int main(int argc, char** argv) { - bool selftest = false; - bool check_fixtures = false; - std::string pack = "pack/full"; - // --gguf, else $STRATA_PLE_GGUF, else the development layout (run from the engine root) - std::string gguf = std::getenv("STRATA_PLE_GGUF") ? std::getenv("STRATA_PLE_GGUF") - : "../../Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf"; - std::string in_bin = "bench/micro/ple_in.bin", out_bin = "bench/micro/ple_out.bin"; - for (int i = 1; i < argc; ++i) { - const std::string a = argv[i]; - if (a == "--selftest") selftest = true; - else if (a == "--check-fixtures") check_fixtures = true; - else if (a == "--pack" && i + 1 < argc) pack = argv[++i]; - else if (a == "--gguf" && i + 1 < argc) gguf = argv[++i]; - else if (a == "--in" && i + 1 < argc) in_bin = argv[++i]; - else if (a == "--out" && i + 1 < argc) out_bin = argv[++i]; - else { std::fprintf(stderr, "usage: ple_parity [--selftest] [--check-fixtures] [--pack D] [--gguf F] [--in F] [--out F]\n"); - return 2; } - } - if (selftest && check_fixtures) { - std::fprintf(stderr, "ple_parity: --check-fixtures is CPU-only; use it separately from --selftest\n"); - return 2; - } - // Required self-test fixtures are checked before the first CUDA call, so - // missing files cannot become an apparent pass or a misleading GPU error. - k::PleTable table; - std::string err; - PleCapture cap; - bool preflight_done = false; - if (selftest || check_fixtures) { - if (!table.open(gguf, err) || table.rows() != o::kTableRows || - file_size(gguf.c_str()) != (long long) o::kTableDataStart + (long long) o::kTableRows * k::PLE_ROW_BYTES) { - std::fprintf(stderr, "ple_parity: required PLE table is missing or incompatible: %s (%s)\n", gguf.c_str(), err.c_str()); - return 2; - } - const uint64_t pack_needed = std::max({o::kKeyCodesOffset + o::kKeyCodesBytes, - o::kKeyScalesOffset + o::kKeyScalesBytes, o::kValueOffset + o::kValueBytes}); - const long long pack_size = file_size((pack + "/dense.bin").c_str()); - if (pack_size < 0 || (uint64_t) pack_size < pack_needed) { - std::fprintf(stderr, "ple_parity: required dense pack is missing or truncated: %s/dense.bin\n", pack.c_str()); - return 2; - } - if (!load_capture(in_bin.c_str(), out_bin.c_str(), cap)) { - std::fprintf(stderr, "ple_parity: required block fixtures are missing, truncated or incompatible: %s / %s\n", in_bin.c_str(), out_bin.c_str()); - return 2; - } - preflight_done = true; - if (check_fixtures) { - std::puts("PASS required PLE fixture structure on CPU; no GPU numerical checks were run"); - return 0; - } - if (!k::ple_block_available()) { - std::fprintf(stderr, "ple_parity: --selftest requires a CUDA device for block checks\n"); - return 2; - } - } - int bad = history_advance_regression(); - const k::PleConsts C = k::ple_artifact_consts(); - - // ============================ A. THE HASH ============================ - std::printf("A. the n-gram hash, against ref/ngram.py with the artifact's own constants\n"); - - // ---- the constants must be internally consistent BEFORE they are used: `head_offsets` is its own array - // in the metadata, so deriving it from `vocab_sizes` would hide a disagreement between them. - { - uint64_t run = 0; - bool ok = true; - for (int h = 0; h < k::PLE_N_HEADS; ++h) { - if (C.offset[h] != run) ok = false; - run += C.vocab[h]; - } - const uint64_t total = run; - const bool fits = total <= k::PLE_TABLE_ROWS; - std::printf(" %-46s %s (sum %llu <= %llu rows; %llu spare)\n", - "head_offsets == the running sum of vocab_sizes", ok && fits ? "yes" : "*** NO ***", - (unsigned long long) total, (unsigned long long) k::PLE_TABLE_ROWS, - (unsigned long long) (k::PLE_TABLE_ROWS - total)); - if (!ok || !fits) ++bad; - } - - for (int ci = 0; ci < o::kHashCaseCount; ++ci) { - const o::HashCase& hc = o::kHashCases[ci]; - std::vector got((size_t) hc.n_tokens * k::PLE_N_HEADS); - k::ngram_rows(hc.tokens, hc.prev, hc.n_tokens, C, got.data()); - long long diff = 0; - for (size_t i = 0; i < got.size(); ++i) - if (got[i] != hc.rows[i]) ++diff; - std::printf(" %-46s %s (%lld of %zu differ)\n", hc.name, diff ? "*** WRONG ***" : "matches", diff, - got.size()); - if (diff) { - for (int t = 0; t < hc.n_tokens && diff; ++t) { - for (int h = 0; h < k::PLE_N_HEADS; ++h) { - const uint32_t g = got[(size_t) t * 16 + h], w = hc.rows[(size_t) t * 16 + h]; - if (g != w) { - std::printf(" first: t=%d h=%d got %u want %u\n", t, h, g, w); - t = hc.n_tokens; - break; - } - } - } - ++bad; - } - } - - // ---- the rival readings, each computed and required to DIFFER from the oracle ------------------- - // - // Every one of these produces a 16-element vector of valid indices. That is the whole reason the hash is - // transcribed property by property: no range check, no shape check and no summing test can see any of - // them, only an oracle can - and only a DELIBERATELY-WRONG fixture can show that the oracle comparison - // has the power to catch them. - { - const o::HashCase& hc = o::kHashCases[0]; // the window-direction case, 4 tokens - const int T = hc.n_tokens, np = k::NGRAM_SIZE - 1, n_heads = k::PLE_N_HEADS; - std::vector xor_v((size_t) T * n_heads), sum_v((size_t) T * n_heads), - mask_v((size_t) T * n_heads), back_v((size_t) T * n_heads), zero_v((size_t) T * n_heads); - for (int i = 0; i < T; ++i) { - int64_t ctx[k::NGRAM_SIZE]; - ctx[0] = hc.tokens[i]; - for (int s = 1; s < k::NGRAM_SIZE; ++s) ctx[s] = hc.prev[i * np + (np - s)]; - for (int n = 2; n <= k::NGRAM_SIZE; ++n) { - // (1) SUM instead of XOR - uint64_t sum = 0; - for (int j = 0; j < n; ++j) sum += (uint64_t) ctx[j] * C.mult[j]; - // (2) mask instead of modulo: the vocab sizes are NOT powers of two - uint64_t xr = k::ngram_mixed(ctx, C.mult, n); - // (4) token 0 treated as "missing" the way -1 is - int64_t ctx0[k::NGRAM_SIZE]; - for (int j = 0; j < k::NGRAM_SIZE; ++j) - ctx0[j] = (ctx[j] == k::TOKEN_NULL || ctx[j] == 0) ? k::PLE_EOS_TOKEN_ID : ctx[j]; - uint64_t xr0 = k::ngram_mixed(ctx0, C.mult, n); - // (3) the window read NEWEST-first instead of oldest-first: prev index (s-1) - int64_t ctxb[k::NGRAM_SIZE]; - ctxb[0] = hc.tokens[i]; - for (int s = 1; s < k::NGRAM_SIZE; ++s) ctxb[s] = hc.prev[i * np + (s - 1)]; - uint64_t xrb = k::ngram_mixed(ctxb, C.mult, n); - const int base = (n - 2) * k::HEADS_PER_NGRAM; - for (int g = 0; g < k::HEADS_PER_NGRAM; ++g) { - const int h = base + g; - xor_v[(size_t) i * n_heads + h] = (uint32_t) (xr % C.vocab[h] + C.offset[h]); - sum_v[(size_t) i * n_heads + h] = (uint32_t) (sum % C.vocab[h] + C.offset[h]); - mask_v[(size_t) i * n_heads + h] = - (uint32_t) ((xr & (C.vocab[h] - 1)) + C.offset[h]); - back_v[(size_t) i * n_heads + h] = (uint32_t) (xrb % C.vocab[h] + C.offset[h]); - zero_v[(size_t) i * n_heads + h] = (uint32_t) (xr0 % C.vocab[h] + C.offset[h]); - } - } - } - struct Rival { const char* name; const std::vector* v; }; - const Rival rivals[] = {{"XOR vs SUM", &sum_v}, - {"% vs & (vocab sizes are not powers of two)", &mask_v}, - {"window read newest-first, not oldest-first", &back_v}, - {"token id 0 treated as the NULL sentinel", &zero_v}}; - for (const Rival& r : rivals) { - // A rival is observable if it disagrees with the ORACLE, which is what the test above compares. - long long d = 0; - for (size_t i = 0; i < r.v->size(); ++i) - if ((*r.v)[i] != hc.rows[i]) ++d; - const bool visible = d > 0; - std::printf(" %-46s %s (%lld of %zu rows differ from the oracle)\n", r.name, - visible ? "yes" : "*** NO - the fixture cannot see this ***", d, r.v->size()); - if (!visible) ++bad; - } - (void) xor_v; - } - - // ---- the EOS cut DIRECTION, which needs a case where the two directions disagree ---------------- - { - const o::HashCase& hc = o::kHashCases[1]; // [[N,N],[7,EOS],[EOS,7]] - const int T = hc.n_tokens, np = k::NGRAM_SIZE - 1, n_heads = k::PLE_N_HEADS; - std::vector fwd((size_t) T * n_heads), bwd((size_t) T * n_heads); - for (int i = 0; i < T; ++i) { - int64_t f[k::NGRAM_SIZE], b[k::NGRAM_SIZE]; - f[0] = b[0] = hc.tokens[i]; - bool cf = false, cb = false; - for (int s = 1; s < k::NGRAM_SIZE; ++s) { - const int32_t fv = hc.prev[i * np + (np - s)]; - cf = cf || fv < 0 || fv == k::PLE_EOS_TOKEN_ID; - f[s] = cf ? k::PLE_EOS_TOKEN_ID : fv; - // the BACKWARD reading: only the position that IS EOS becomes EOS - const int32_t bv = hc.prev[i * np + (np - s)]; - b[s] = (bv < 0 || bv == k::PLE_EOS_TOKEN_ID) ? k::PLE_EOS_TOKEN_ID : bv; - (void) cb; - } - for (int n = 2; n <= k::NGRAM_SIZE; ++n) { - const uint64_t mf = k::ngram_mixed(f, C.mult, n), mb = k::ngram_mixed(b, C.mult, n); - const int base = (n - 2) * k::HEADS_PER_NGRAM; - for (int g = 0; g < k::HEADS_PER_NGRAM; ++g) { - const int h = base + g; - fwd[(size_t) i * n_heads + h] = (uint32_t) (mf % C.vocab[h] + C.offset[h]); - bwd[(size_t) i * n_heads + h] = (uint32_t) (mb % C.vocab[h] + C.offset[h]); - } - } - } - long long d = 0; - for (size_t i = 0; i < fwd.size(); ++i) - if (fwd[i] != bwd[i]) ++d; - std::printf(" %-46s %s (%lld of %zu rows differ)\n", - "cut propagates FORWARD vs only at the EOS position", - d > 0 ? "yes" : "*** NO ***", d, fwd.size()); - if (!d) ++bad; - } - - // ============================ B. THE TABLE ============================ - std::printf("\nB. the IQ4_NL table, against numpy reading the original GGUF\n"); - if (!preflight_done && !table.open(gguf, err)) { - std::printf(" cannot open the PLE table: %s\n", err.c_str()); - std::printf("\nple_parity: %d failures, TABLE AND BLOCK SKIPPED; partial diagnostic only\n", bad); - return selftest || bad ? 1 : 0; - } - std::printf(" %-46s %llu (expected %llu)\n", "rows", (unsigned long long) table.rows(), - (unsigned long long) o::kTableRows); - if (table.rows() != o::kTableRows) ++bad; - - // The size identity is what makes the data offset FALSIFIABLE: the tensor must exactly fill the file from - // data_start. Deriving the row count from the file size instead gives 320001538 rows and data_start 12, - // which is self-consistent and wrong. - { - const long long sz = file_size(gguf.c_str()); - const long long need = (long long) o::kTableDataStart + (long long) table.rows() * k::PLE_ROW_BYTES; - const bool ok = sz == need; - std::printf(" %-46s %s (%lld vs %lld; data_start %llu)\n", - "data_start + rows*90 == file size", ok ? "yes" : "*** NO ***", sz, need, - (unsigned long long) o::kTableDataStart); - if (!ok) ++bad; - } - - // Read the raw bytes through the mapped table by comparing against numpy's decode of the SAME offsets. - // 90 BYTES AT A TIME, not the whole file - see `file_size`'s note. - { - int probe_bad = 0; - for (int p = 0; p < o::kProbeCount; ++p) { - const uint32_t row = o::kProbeRows[p]; - std::vector got(k::PLE_HEAD_DIM); - table.read_row(row, got.data()); - const std::vector raw = - read_at(gguf.c_str(), (long long) o::kTableDataStart + (long long) row * k::PLE_ROW_BYTES, - (size_t) k::PLE_ROW_BYTES); - if (raw.size() != (size_t) k::PLE_ROW_BYTES) { std::printf(" short read at row %u\n", row); ++probe_bad; continue; } - std::vector ref(k::PLE_HEAD_DIM); - k::iq4nl_dequant_row(raw.data(), ref.data()); - // the sampled values from the generator (numpy), which is the oracle proper. - // NOT `fmax`: it DISCARDS NaN, so a NaN element would leave these at 0 and the row would report - // a perfect match. A plain comparison propagates the NaN into `ok`. - double head = 0, tail = 0, sum = 0; - for (int i = 0; i < 8; ++i) { - const double dh = std::fabs((double) got[i] - (double) o::kProbeHead[p][i]); - const double dt = std::fabs((double) got[k::PLE_HEAD_DIM - 8 + i] - - (double) o::kProbeTail[p][i]); - if (p == 0 && i == 0) { head = dh; tail = dt; } - else { head = (dh > head) ? dh : head; tail = (dt > tail) ? dt : tail; } - } - for (int i = 0; i < k::PLE_HEAD_DIM; ++i) sum += std::fabs((double) got[i]); - const long long nfg = nonfinite(got.data(), k::PLE_HEAD_DIM); - const bool ok = le(head, 0.0) && le(tail, 0.0) && le(std::fabs(sum - o::kProbeSum[p]), 1e-9) && - nfg == 0; - std::printf(" %-46s %s (row %u: head %.3e tail %.3e sum d %.3e, non-finite %lld)\n", - p == 0 ? "row matches numpy's decode of the same bytes" : " (same, another row)", - ok ? "yes" : "*** NO ***", row, head, tail, std::fabs(sum - o::kProbeSum[p]), nfg); - if (!ok) ++probe_bad; - // and the two decoders must agree with each other bit for bit - for (int i = 0; i < k::PLE_HEAD_DIM; ++i) - if (got[i] != ref[i]) { std::printf(" byte-level decode differs at %d\n", i); ++probe_bad; break; } - } - bad += probe_bad; - } - - // ---- the split-half nibble order must be observable --------------------------------------------- - { - const std::vector raw = - read_at(gguf.c_str(), (long long) o::kTableDataStart + - (long long) o::kProbeRows[0] * k::PLE_ROW_BYTES, - (size_t) k::PLE_ROW_BYTES); - std::vector want(k::PLE_HEAD_DIM), inter(k::PLE_HEAD_DIM); - k::iq4nl_dequant_row(raw.data(), want.data()); - deq_interleaved(raw.data(), inter.data()); - const double rel = rel_l1(want.data(), inter.data(), k::PLE_HEAD_DIM); - const bool visible = gt(rel, 0.05); - std::printf(" %-46s %s (%.2f%% apart; generator says %.4f)\n", - "split-half vs INTERLEAVED nibbles observable", - visible ? "yes" : "*** NO ***", rel * 100, (double) o::kInterleavedSeparation); - if (!visible) ++bad; - } - - // ---- and reading at file offset 0 instead of data_start must be observable ---------------------- - { - const std::vector at_ds = read_at(gguf.c_str(), (long long) o::kTableDataStart, - (size_t) k::PLE_ROW_BYTES); - const std::vector at_0 = read_at(gguf.c_str(), 0, (size_t) k::PLE_ROW_BYTES); - std::vector ok_v(k::PLE_HEAD_DIM), at0(k::PLE_HEAD_DIM); - k::iq4nl_dequant_row(at_ds.data(), ok_v.data()); - k::iq4nl_dequant_row(at_0.data(), at0.data()); - const double rel = rel_l1(ok_v.data(), at0.data(), k::PLE_HEAD_DIM); - const bool visible = gt(rel, 0.05); - std::printf(" %-46s %s (%.2f%% apart)\n", - "data_start 192 vs file offset 0 observable", visible ? "yes" : "*** NO ***", rel * 100); - if (!visible) ++bad; - } - - // ---- head-slowest flatten ---------------------------------------------------------------------- - { - const uint32_t rows16[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; - std::vector emb(k::NG_N_EMBD), one(k::PLE_HEAD_DIM); - table.gather(rows16, emb.data()); - bool blockwise = true; - for (int h = 0; h < k::PLE_N_HEADS && blockwise; ++h) { - table.read_row((uint32_t) h, one.data()); - for (int d = 0; d < k::PLE_HEAD_DIM; ++d) - if (emb[h * k::PLE_HEAD_DIM + d] != one[d]) { blockwise = false; break; } - } - // the rival: head-fastest, element (d,h) at d*16+h - a real transpose, not a reshape - std::vector fast(k::NG_N_EMBD); - for (int d = 0; d < k::PLE_HEAD_DIM; ++d) - for (int h = 0; h < k::PLE_N_HEADS; ++h) fast[d * k::PLE_N_HEADS + h] = emb[h * k::PLE_HEAD_DIM + d]; - long long diff = 0; - for (int i = 0; i < k::NG_N_EMBD; ++i) - if (fast[i] != emb[i]) ++diff; - std::printf(" %-46s %s (head h occupies [h*160,(h+1)*160))\n", "gather is head-slowest", - blockwise ? "yes" : "*** NO ***"); - std::printf(" %-46s %s (%lld of %d elements differ)\n", "head-fastest would differ", - diff > 0 ? "yes" : "*** NO ***", diff, k::NG_N_EMBD); - if (!blockwise || !diff) ++bad; - } - - // ============================ C. THE BLOCK ============================ - std::printf("\nC. the PLE block, against ggml's own graph (ple_in.bin / ple_out.bin)\n"); - if (!preflight_done && !load_capture(in_bin.c_str(), out_bin.c_str(), cap)) { - std::printf(" cannot load %s / %s\n", in_bin.c_str(), out_bin.c_str()); - std::printf("\nple_parity: %d failures, BLOCK SKIPPED; partial diagnostic only\n", bad); - return selftest || bad ? 1 : 0; - } - std::printf(" capture: n_embd %d, hc %d, nt %d, kern %d, dil %d, eps %g\n", cap.n_embd, cap.hc, cap.nt, - cap.kern, cap.dil, (double) cap.eps); - if (cap.n_embd != k::NG_N_EMBD || cap.hc != k::NG_HC || cap.kern != k::PLE_CONV_KERNEL || - cap.dil != k::NGRAM_SIZE) { - std::printf(" *** the capture's geometry is not the artifact's ***\n"); - return 1; - } - - if (!k::ple_block_available()) { - std::printf(" no CUDA device; the block SKIPPED, not passed.\n"); - std::printf("\nple_parity: %d failures, BLOCK SKIPPED\n", bad); - return selftest || bad ? 1 : 0; - } - - // ---- the two quantized weights, from the PACK, not from the capture. - // The capture holds `w_key` already dequantized to f32; the kernel needs the CODES AND SCALES, and - // re-quantizing the f32 would be a different tensor. Reading the pack is right and it was checked: - // the pack's decode of row 0 reproduces the capture's w_key row 0 exactly (see the round entry). - // Only the two regions are read, not all 5.4 GB of `dense.bin`. - std::vector key_codes = - read_at((pack + "/dense.bin").c_str(), (long long) o::kKeyCodesOffset, (size_t) o::kKeyCodesBytes); - const std::vector raw_scales = - read_at((pack + "/dense.bin").c_str(), (long long) o::kKeyScalesOffset, (size_t) o::kKeyScalesBytes); - const std::vector raw_value = - read_at((pack + "/dense.bin").c_str(), (long long) o::kValueOffset, (size_t) o::kValueBytes); - if (key_codes.empty() || raw_scales.empty() || raw_value.empty()) { - std::printf(" cannot read the ple_key/ple_value regions from %s/dense.bin\n", pack.c_str()); - return 2; - } - // fp16 -> f32 for the scales, which is what every S-form kernel in this project expects - const size_t n_scales = raw_scales.size() / 2; - std::vector key_scales(n_scales); - for (size_t i = 0; i < n_scales; ++i) { - uint16_t h; - std::memcpy(&h, raw_scales.data() + i * 2, 2); - key_scales[i] = k::f32_from_f16(h); - } - // ple_value is BF16 promoted to 32 bits in the pack; take the high half, which is exact - std::vector value_bf16(raw_value.size() / 4); - for (size_t i = 0; i < value_bf16.size(); ++i) { - uint32_t u; - std::memcpy(&u, raw_value.data() + i * 4, 4); - value_bf16[i] = (uint16_t) (u >> 16); - } - // ple_conv1d is F16 in the pack; the capture holds it as f32 in ggml order, and the kernel wants F16 - std::vector conv1d_f16(cap.w_conv.size()); - for (size_t i = 0; i < conv1d_f16.size(); ++i) conv1d_f16[i] = k::f16_from_f32(cap.w_conv[i]); - - // ---- the check that the two sources describe the SAME weights --------------------------------- - { - // dequantize key row 0 with the canonical rule and compare to the capture's w_key row 0. - // NOT `fmax`, for the reason above: it discards NaN, so a NaN would leave `worst` at 0 and report a - // perfect match. - double worst = 0; - bool first = true; - long long nf = 0; - for (int d = 0; d < k::NG_N_EMBD; ++d) { - const uint8_t byte = key_codes[d / 4]; - const int code = (byte >> ((d % 4) * 2)) & 3; - const float v = (float) (code + (-1)) * key_scales[d / 64]; - if (!std::isfinite(v) || !std::isfinite(cap.w_key[d])) { ++nf; continue; } - const double diff = std::fabs((double) v - (double) cap.w_key[d]); - if (first) { worst = diff; first = false; } - else worst = (diff > worst) ? diff : worst; - } - std::printf(" %-46s %s (worst |d| %.3e, non-finite %lld)\n", - "pack ple_key row 0 == the capture's w_key row 0", - (le(worst, 0.0) && nf == 0) ? "yes" : "*** NO ***", worst, nf); - if (!le(worst, 0.0) || nf) ++bad; - } - - // ---- run the block for both tokens of the capture --------------------------------------------- - const size_t hcd = (size_t) k::NG_HC_DIM, nd = (size_t) k::NG_N_EMBD; - std::vector dev_key(hcd), dev_value(nd), dev_gate(k::NG_HC), dev_gated(hcd), dev_norm(hcd), - dev_conv(hcd), dev_res(hcd); - float *d_emb = nullptr, *d_hid = nullptr, *d_hist = nullptr, *d_nk = nullptr, *d_nq = nullptr, - *d_nc = nullptr, *d_ck = nullptr, *d_cv = nullptr, *d_cn = nullptr, *d_cr = nullptr; - uint8_t* d_kc = nullptr; - uint16_t *d_vb = nullptr, *d_c1 = nullptr; - float *d_g = nullptr, *d_v = nullptr, *d_gd = nullptr, *d_nm = nullptr, *d_co = nullptr; - ck(cudaMalloc(&d_emb, nd * 4), "emb"); - ck(cudaMalloc(&d_hid, hcd * 4), "hid"); - ck(cudaMalloc(&d_hist, (size_t) k::NG_HIST * hcd * 4), "hist"); - ck(cudaMalloc(&d_nk, hcd * 4), "nk"); - ck(cudaMalloc(&d_nq, hcd * 4), "nq"); - ck(cudaMalloc(&d_nc, hcd * 4), "nc"); - ck(cudaMalloc(&d_kc, key_codes.size()), "kc"); - ck(cudaMalloc(&d_vb, value_bf16.size() * 2), "vb"); - ck(cudaMalloc(&d_c1, conv1d_f16.size() * 2), "c1"); - ck(cudaMalloc(&d_g, k::NG_HC * 4), "g"); - ck(cudaMalloc(&d_v, nd * 4), "v"); - ck(cudaMalloc(&d_gd, hcd * 4), "gd"); - ck(cudaMalloc(&d_nm, hcd * 4), "nm"); - ck(cudaMalloc(&d_co, hcd * 4), "co"); - ck(cudaMalloc(&d_ck, hcd * 4), "ck"); - ck(cudaMalloc(&d_cv, nd * 4), "cv"); - ck(cudaMalloc(&d_cn, hcd * 4), "cn"); - ck(cudaMalloc(&d_cr, hcd * 4), "cr"); - ck(cudaMemcpy(d_nk, cap.w_nk.data(), hcd * 4, cudaMemcpyHostToDevice), "cnk"); - ck(cudaMemcpy(d_nq, cap.w_nq.data(), hcd * 4, cudaMemcpyHostToDevice), "cnq"); - ck(cudaMemcpy(d_nc, cap.w_nc.data(), hcd * 4, cudaMemcpyHostToDevice), "cnc"); - ck(cudaMemcpy(d_kc, key_codes.data(), key_codes.size(), cudaMemcpyHostToDevice), "ckc"); - ck(cudaMemcpy(d_vb, value_bf16.data(), value_bf16.size() * 2, cudaMemcpyHostToDevice), "cvb"); - ck(cudaMemcpy(d_c1, conv1d_f16.data(), conv1d_f16.size() * 2, cudaMemcpyHostToDevice), "cc1"); - - k::PleWeights w{}; - w.key_codes = d_kc; - w.key_scales = key_scales.data(); // uploaded per call below so the pointer is a device one - w.value_bf16 = d_vb; - w.norm_key = d_nk; - w.norm_query = d_nq; - w.norm_conv = d_nc; - w.conv1d_f16 = d_c1; - float* d_ks = nullptr; - ck(cudaMalloc(&d_ks, key_scales.size() * 4), "ks"); - ck(cudaMemcpy(d_ks, key_scales.data(), key_scales.size() * 4, cudaMemcpyHostToDevice), "cks"); - w.key_scales = d_ks; - - // Per-stage comparison. Each stage the oracle records is a separate line, so a mismatch says WHICH part - // of the block is wrong rather than only that the sum is. The oracle writes each array token-major, so - // every slice is an explicit (offset, count) pair - deriving the offset from the stage's NAME, which the - // first version of this did, is a fixture that breaks the moment a name changes. - struct Stage { const char* name; const std::vector* got; const std::vector* all; - size_t offset; size_t n; }; - double worst_all = 0; - - // THE CONV HISTORY ADVANCES BETWEEN TOKENS, and getting this wrong is why token 1 compared badly at - // first. The capture is a TWO-TOKEN ubatch: ggml pads `[hist(9) | normalized(0..nt-1)]` ONCE and the conv - // reads rows `t+0, t+3, t+6, t+9` for output position t. So token 1's window is rows 1,4,7 of the SAME - // history plus row 10 - which is token 1's own normalized - i.e. the state slides by one NORMALIZED row - // per token. Feeding both tokens the original history compares my block's t=0 against ggml's t=1, and - // both my kernel and my host reference made the same mistake, so they agreed with each other and only the - // oracle could see it. - // - // ggml layout for the state is `ne=(hist, hc_dim)`: flat = row + NG_HIST*channel. - std::vector hist_state = cap.hist; - for (int t = 0; t < cap.nt; ++t) { - ck(cudaMemcpy(d_emb, cap.emb.data() + (size_t) t * nd, nd * 4, cudaMemcpyHostToDevice), "cemb"); - ck(cudaMemcpy(d_hid, cap.hidden.data() + (size_t) t * hcd, hcd * 4, cudaMemcpyHostToDevice), "chid"); - ck(cudaMemcpy(d_hist, hist_state.data(), (size_t) k::NG_HIST * hcd * 4, cudaMemcpyHostToDevice), - "chist"); - k::PleOut out{}; - out.key = d_ck; out.value = d_cv; out.gate = d_g; out.gated = d_gd; - out.normalized = d_nm; out.conv = d_co; out.result = d_cr; - // the workspace is the caller's, and the sync the block used to do is now the caller's too - void* ple_ws = nullptr; - ck(cudaMalloc(&ple_ws, k::ple_block_scratch_bytes()), "ple_block scratch"); - if (t == 0) { - const size_t bytes = (size_t) k::ple_block_scratch_bytes(); - ck(cudaMemset(ple_ws, 0xa5, bytes), "PLE prelaunch guard sentinel"); - const struct AliasCase { float* k::PleOut::* field; size_t offset; } cases[] = { - {&k::PleOut::key, 0}, {&k::PleOut::value, hcd}, {&k::PleOut::gate, hcd + nd}, - {&k::PleOut::gated, hcd + nd + (size_t) k::NG_HC}, - {&k::PleOut::normalized, 2 * hcd + nd + (size_t) k::NG_HC}, - {&k::PleOut::conv, 3 * hcd + nd + (size_t) k::NG_HC}, {&k::PleOut::result, 0} - }; - int refused = 0; - for (const auto& item : cases) { - k::PleOut invalid = out; - invalid.*(item.field) = static_cast(ple_ws) + item.offset; - try { k::ple_block(d_emb, d_hid, d_hist, w, invalid, ple_ws, nullptr); } - catch (const std::invalid_argument&) { ++refused; } - } - ck(cudaDeviceSynchronize(), "PLE guard no-launch sync"); - std::vector sentinel(bytes); - ck(cudaMemcpy(sentinel.data(), ple_ws, bytes, cudaMemcpyDeviceToHost), "PLE guard sentinel readback"); - const bool unchanged = std::all_of(sentinel.begin(), sentinel.end(), [](uint8_t b) { return b == 0xa5; }); - const bool rejected = refused == 7 && unchanged; - std::printf(" PLE old caller output offsets rejected before launch: %s (%d/7, scratch %s)\n", - rejected ? "pass" : "FAIL", refused, unchanged ? "unchanged" : "CORRUPTED"); - if (!rejected) ++bad; - } - k::ple_block(d_emb, d_hid, d_hist, w, out, ple_ws, nullptr); - ck(cudaDeviceSynchronize(), "ple_block sync"); - ck(cudaMemcpy(dev_key.data(), d_ck, hcd * 4, cudaMemcpyDeviceToHost), "rck"); - ck(cudaMemcpy(dev_value.data(), d_cv, nd * 4, cudaMemcpyDeviceToHost), "rcv"); - ck(cudaMemcpy(dev_gate.data(), d_g, k::NG_HC * 4, cudaMemcpyDeviceToHost), "rg"); - ck(cudaMemcpy(dev_gated.data(), d_gd, hcd * 4, cudaMemcpyDeviceToHost), "rgd"); - ck(cudaMemcpy(dev_norm.data(), d_nm, hcd * 4, cudaMemcpyDeviceToHost), "rnm"); - ck(cudaMemcpy(dev_conv.data(), d_co, hcd * 4, cudaMemcpyDeviceToHost), "rco"); - ck(cudaMemcpy(dev_res.data(), d_cr, hcd * 4, cudaMemcpyDeviceToHost), "rcr"); - - const size_t ok_ = (size_t) t * hcd, ov = (size_t) t * nd, og = (size_t) t * (size_t) k::NG_HC; - const Stage stages[] = { - {"key (grouped_norm of ple_key @ emb)", &dev_key, &cap.key, ok_, hcd}, - {"value (ple_value @ emb, BF16)", &dev_value, &cap.value, ov, nd}, - {"gate (signed sqrt, sigmoid)", &dev_gate, &cap.gate, og, (size_t) k::NG_HC}, - {"gated (value broadcast * gate)", &dev_gated, &cap.gated, ok_, hcd}, - {"normalized (grouped_norm(gated, ple_norm_conv))", &dev_norm, &cap.normalized, ok_, hcd}, - {"conv_out (dilated conv, then SiLU)", &dev_conv, &cap.conv_out, ok_, hcd}, - {"result (hidden + gated + conv)", &dev_res, &cap.result, ok_, hcd}, - }; - for (const Stage& s : stages) { - std::vector want(s.all->begin() + (long long) s.offset, - s.all->begin() + (long long) (s.offset + s.n)); - double mag = 0; - long long nf = 0; - const double rel = rel_l1(want.data(), s.got->data(), s.n, &mag, &nf); - // NaN-SAFE: `rel > worst_all` is false for NaN, so `fmax` here would silently report a perfect - // score for a fixture full of NaNs - round 197's exact failure. - worst_all = (rel > worst_all) ? rel : worst_all; - if (nf) worst_all = std::nan(""); - const bool last = (std::strncmp(s.name, "result", 6) == 0); - std::printf(" token %d %-46s rel %.3e (mean |ref| %.4f, non-finite %lld)%s\n", t, s.name, rel, - mag, nf, last && !le(rel, 1e-2) ? " *** over 1e-2 ***" : ""); - // TOLERANCE, and what sets it: this comparison is the GPU against a capture whose weights are - // F32, so ggml performed NO activation conversion while the kernel applies the CONTRACT (Q8_0 - // for the Q2_0 weight, BF16 for the BF16 one). The contract's per-element cost is 2^-9 = 1.95e-3 - // for BF16 and ~0.4% for Q8_0, so the OUTPUT difference is ~2e-3 wherever there is no - // cancellation and larger where there is - `conv_out` cancels by ~77x and is the one stage that - // exceeds it. `result` is the quantity that matters and 1e-2 is five times the contract's own - // per-element size, so it is a bound on "the contract and nothing else", not a judgement call. - // The HOST reference below uses the capture's own F32 weights and is asserted at 1e-4, which is - // what proves the difference here IS the contract. - if (last && !le(rel, 1e-2)) ++bad; - } - - if (t == 0) { - // Deliberate BF16 halfway values make the value projection's activation precision visible. - // The scalar reference uses the actual packed BF16 weight bits and unrounded F32 inputs. - std::vector witness(nd), reference_value(nd), native_value(nd), native_result(hcd), replay(hcd); - for (size_t i = 0; i < nd; ++i) witness[i] = i % 7 == 0 ? 1.00390625f : -0.501953125f; - for (size_t row = 0; row < nd; ++row) { - double sum = 0.0; - for (size_t col = 0; col < nd; ++col) { - const uint32_t bits = uint32_t(value_bf16[row * nd + col]) << 16; - float weight; - std::memcpy(&weight, &bits, sizeof(weight)); - sum += double(weight) * witness[col]; - } - reference_value[row] = float(sum); - } - ck(cudaMemcpy(d_emb, witness.data(), nd * sizeof(float), cudaMemcpyHostToDevice), "native PLE witness"); - k::ple_block(d_emb, d_hid, d_hist, w, out, ple_ws, nullptr); - ck(cudaDeviceSynchronize(), "legacy PLE witness sync"); - std::vector legacy_value(nd); - ck(cudaMemcpy(legacy_value.data(), d_cv, nd * sizeof(float), cudaMemcpyDeviceToHost), "legacy PLE witness value"); - cudaStream_t stream; - ck(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), "native PLE stream"); - k::ple_set_native_bf16(true); - k::ple_block(d_emb, d_hid, d_hist, w, out, ple_ws, stream); - ck(cudaStreamSynchronize(stream), "native PLE sync"); - ck(cudaMemcpy(native_value.data(), d_cv, nd * sizeof(float), cudaMemcpyDeviceToHost), "native PLE value"); - ck(cudaMemcpy(native_result.data(), d_cr, hcd * sizeof(float), cudaMemcpyDeviceToHost), "native PLE result"); - long long nf = 0; - const double rel = rel_l1(reference_value.data(), native_value.data(), nd, nullptr, &nf); - const double separation = rel_l1(native_value.data(), legacy_value.data(), nd); - const bool correct = le(rel, 2e-6) && nf == 0 && gt(separation, 1e-5); - std::printf(" native PLE value: %s (ref rel %.3e, BF16 separation %.3e)\n", - correct ? "pass" : "FAIL", rel, separation); - if (!correct) ++bad; - cudaGraph_t graph; - cudaGraphExec_t executable; - ck(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "native PLE capture"); - k::ple_block(d_emb, d_hid, d_hist, w, out, ple_ws, stream); - ck(cudaStreamEndCapture(stream, &graph), "native PLE capture end"); - ck(cudaGraphInstantiate(&executable, graph, nullptr, nullptr, 0), "native PLE instantiate"); - k::ple_set_native_bf16(false); - ck(cudaGraphLaunch(executable, stream), "native PLE replay"); - ck(cudaStreamSynchronize(stream), "native PLE replay sync"); - ck(cudaMemcpy(replay.data(), d_cr, hcd * sizeof(float), cudaMemcpyDeviceToHost), "native PLE replay result"); - const bool captured = std::memcmp(native_result.data(), replay.data(), hcd * sizeof(float)) == 0; - std::printf(" native PLE captured selection: %s\n", captured ? "byte-identical" : "FAIL"); - if (!captured) ++bad; - ck(cudaGraphExecDestroy(executable), "native PLE graph exec destroy"); - ck(cudaGraphDestroy(graph), "native PLE graph destroy"); - ck(cudaStreamDestroy(stream), "native PLE stream destroy"); - ck(cudaMemcpy(d_emb, cap.emb.data(), nd * sizeof(float), cudaMemcpyHostToDevice), "restore PLE embedding"); - k::ple_block(d_emb, d_hid, d_hist, w, out, ple_ws, nullptr); - ck(cudaDeviceSynchronize(), "restored PLE sync"); - ck(cudaMemcpy(replay.data(), d_cr, hcd * sizeof(float), cudaMemcpyDeviceToHost), "restored PLE result"); - const bool restored = std::memcmp(dev_res.data(), replay.data(), hcd * sizeof(float)) == 0; - std::printf(" restored PLE default: %s\n", restored ? "byte-identical" : "FAIL"); - if (!restored) ++bad; - } - - if (t == 0) { - // This checks native-projection wiring and graph lifetime, independently - // of the legacy CPU/F32 structural capture. Actual Q2_0 arithmetic is - // checked separately by native_mmvq_parity against the pinned CUDA DLL. - const size_t blocks = n_scales, native_bytes = blocks * 18, guard = 64; - const size_t qbytes = k::native_q8_1_bytes(k::NG_N_EMBD); - std::vector native_key(native_bytes); - for (size_t b = 0; b < blocks; ++b) { - std::memcpy(native_key.data() + b * 18, raw_scales.data() + b * 2, 2); - std::memcpy(native_key.data() + b * 18 + 2, key_codes.data() + b * 16, 16); - } - void *native_storage = nullptr, *q_storage = nullptr; - float* raw_projection = nullptr; - ck(cudaMalloc(&native_storage, native_bytes + 2 * guard), "native PLE weights"); - ck(cudaMalloc(&q_storage, qbytes + 2 * guard), "native PLE q8 scratch"); - ck(cudaMalloc(&raw_projection, hcd * 4), "native PLE raw projection"); - ck(cudaMemset(native_storage, 0xa5, native_bytes + 2 * guard), "native PLE weight guards"); - ck(cudaMemset(q_storage, 0xa5, qbytes + 2 * guard), "native PLE q8 guards"); - void* native_data = static_cast(native_storage) + guard; - void* native_q = static_cast(q_storage) + guard; - ck(cudaMemcpy(native_data, native_key.data(), native_bytes, cudaMemcpyHostToDevice), "native PLE weights upload"); - k::PleWeights nw = w; - nw.key_native_data = native_data; nw.key_native_type = 42; nw.key_native_q8_1 = native_q; - cudaStream_t stream; - ck(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), "native PLE key stream"); - const size_t workspace_bytes = (size_t) k::ple_block_scratch_bytes(); - ck(cudaMemset(ple_ws, 0xa5, workspace_bytes), "native PLE no-launch sentinel"); - int refused = 0; - for (int c = 0; c < 9; ++c) { - auto invalid = nw; - if (c == 0) invalid.key_native_type = 11; - if (c == 1) invalid.key_native_q8_1 = nullptr; - if (c == 3) invalid.key_native_q8_1 = ple_ws; - if (c == 4) invalid.key_native_q8_1 = d_emb; - if (c == 5) invalid.key_native_q8_1 = out.key; - if (c == 6) invalid.key_native_q8_1 = static_cast(native_q) + 1; - if (c == 7) invalid.key_native_data = static_cast(native_data) + 1; - if (c == 8) invalid.key_native_q8_1 = native_data; - try { k::ple_block(d_emb, d_hid, d_hist, invalid, out, ple_ws, c == 2 ? nullptr : stream); } - catch (const std::invalid_argument&) { ++refused; } - } - ck(cudaStreamSynchronize(stream), "native PLE refusal sync"); - std::vector sentinel(workspace_bytes); - ck(cudaMemcpy(sentinel.data(), ple_ws, workspace_bytes, cudaMemcpyDeviceToHost), "native PLE refusal sentinel"); - const bool untouched = std::all_of(sentinel.begin(), sentinel.end(), [](uint8_t x) { return x == 0xa5; }); - std::printf(" native PLE key prelaunch guards: %s (%d/9, workspace %s)\n", - refused == 9 && untouched ? "pass" : "FAIL", refused, untouched ? "unchanged" : "changed"); - if (refused != 9 || !untouched) ++bad; - cudaGraph_t graph = nullptr; cudaGraphExec_t executable = nullptr; - std::vector projected(hcd), normalized(hcd), actual_key(hcd), actual_result(hcd), replay(hcd); - for (int p = 0; p < std::min(cap.nt, 2); ++p) { - ck(cudaMemcpy(d_emb, cap.emb.data() + (size_t) p * nd, nd * 4, cudaMemcpyHostToDevice), "native PLE key input"); - k::native_q2_0_f32(native_data, d_emb, native_q, raw_projection, k::NG_N_EMBD, k::NG_HC_DIM, 1, stream); - ck(cudaStreamSynchronize(stream), "native PLE raw key sync"); - ck(cudaMemcpy(projected.data(), raw_projection, hcd * 4, cudaMemcpyDeviceToHost), "native PLE raw key read"); - for (int c = 0; c < k::NG_HC; ++c) { - double sum = 0; - for (size_t j = 0; j < nd; ++j) { const float v = projected[(size_t) c * nd + j]; sum += double(v * v); } - const float scale = 1.0f / std::sqrt(float(sum / double(nd)) + k::NG_RMS_EPS); - for (size_t j = 0; j < nd; ++j) { const size_t i = (size_t) c * nd + j; normalized[i] = projected[i] * scale * cap.w_nk[i]; } - } - k::ple_block(d_emb, d_hid, d_hist, nw, out, ple_ws, stream); - ck(cudaStreamSynchronize(stream), "native PLE key direct sync"); - ck(cudaMemcpy(actual_key.data(), d_ck, hcd * 4, cudaMemcpyDeviceToHost), "native PLE key read"); - ck(cudaMemcpy(actual_result.data(), d_cr, hcd * 4, cudaMemcpyDeviceToHost), "native PLE result read"); - const double rel = rel_l1(normalized.data(), actual_key.data(), hcd); - const bool wired = le(rel, 2e-6) && nonfinite(actual_result.data(), hcd) == 0; - std::printf(" native PLE key projection->existing norm input %d: %s (rel %.3e)\n", p, wired ? "pass" : "FAIL", rel); - if (!wired) ++bad; - if (p == 0) { - ck(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "native PLE key capture"); - k::ple_block(d_emb, d_hid, d_hist, nw, out, ple_ws, stream); - ck(cudaStreamEndCapture(stream, &graph), "native PLE key capture end"); - ck(cudaGraphInstantiate(&executable, graph, nullptr, nullptr, 0), "native PLE key instantiate"); - } - nw.key_native_data = nullptr; // graph selection must survive descriptor changes - for (int repeat = 0; repeat < 2; ++repeat) { - ck(cudaGraphLaunch(executable, stream), "native PLE key replay"); - ck(cudaStreamSynchronize(stream), "native PLE key replay sync"); - ck(cudaMemcpy(replay.data(), d_cr, hcd * 4, cudaMemcpyDeviceToHost), "native PLE key replay read"); - if (std::memcmp(actual_result.data(), replay.data(), hcd * 4) != 0) ++bad; - } - nw.key_native_data = native_data; - } - ck(cudaGraphExecDestroy(executable), "native PLE key executable destroy"); - ck(cudaGraphDestroy(graph), "native PLE key graph destroy"); - for (int b = 0; b < 2; ++b) { - const void* storage = b == 0 ? native_storage : q_storage; - const size_t payload = b == 0 ? native_bytes : qbytes; - std::vector ends(2 * guard); - ck(cudaMemcpy(ends.data(), storage, guard, cudaMemcpyDeviceToHost), "native PLE prefix guard"); - ck(cudaMemcpy(ends.data() + guard, static_cast(storage) + guard + payload, guard, cudaMemcpyDeviceToHost), "native PLE suffix guard"); - if (!std::all_of(ends.begin(), ends.end(), [](uint8_t x) { return x == 0xa5; })) ++bad; - } - ck(cudaStreamDestroy(stream), "native PLE key stream destroy"); - cudaFree(raw_projection); cudaFree(q_storage); cudaFree(native_storage); - ck(cudaMemcpy(d_emb, cap.emb.data(), nd * 4, cudaMemcpyHostToDevice), "native PLE restore input"); - k::ple_block(d_emb, d_hid, d_hist, w, out, ple_ws, nullptr); - ck(cudaDeviceSynchronize(), "native PLE default restore sync"); - ck(cudaMemcpy(replay.data(), d_cr, hcd * 4, cudaMemcpyDeviceToHost), "native PLE default restore read"); - const bool restored = std::memcmp(dev_res.data(), replay.data(), hcd * 4) == 0; - std::printf(" native PLE key graph/repeat/buffer guards checked; restored default: %s\n", restored ? "byte-identical" : "FAIL"); - if (!restored) ++bad; - } - - if (t == 0) { - // The engine only needs result and normalized. Export normalized after the complete private - // workspace; result may overwrite hidden once its original values are no longer needed. - const size_t workspace_bytes = (size_t) k::ple_block_scratch_bytes(); - void* compact_workspace = nullptr; - ck(cudaMalloc(&compact_workspace, workspace_bytes + hcd * sizeof(float)), "compact PLE workspace"); - k::PleOut compact{}; - compact.normalized = reinterpret_cast(static_cast(compact_workspace) + workspace_bytes); - compact.result = d_hid; - k::ple_block(d_emb, d_hid, d_hist, w, compact, compact_workspace, nullptr); - ck(cudaDeviceSynchronize(), "compact PLE sync"); - std::vector compact_norm(hcd), compact_result(hcd); - ck(cudaMemcpy(compact_norm.data(), compact.normalized, hcd * sizeof(float), cudaMemcpyDeviceToHost), "compact PLE normalized"); - ck(cudaMemcpy(compact_result.data(), d_hid, hcd * sizeof(float), cudaMemcpyDeviceToHost), "compact PLE result"); - const bool equal = std::memcmp(compact_norm.data(), dev_norm.data(), hcd * sizeof(float)) == 0 && - std::memcmp(compact_result.data(), dev_res.data(), hcd * sizeof(float)) == 0; - std::printf(" PLE separate exports and in-place hidden result: %s\n", equal ? "byte-identical" : "FAIL"); - if (!equal) ++bad; - ck(cudaMemcpy(d_hid, cap.hidden.data(), hcd * sizeof(float), cudaMemcpyHostToDevice), "restore PLE hidden input"); - cudaFree(compact_workspace); - } - - // slide the conv state by one NORMALIZED row, which is what the next token's window needs - for (size_t c = 0; c < hcd; ++c) - for (size_t r = 0; r + 1 < (size_t) k::NG_HIST; ++r) - hist_state[r + (size_t) k::NG_HIST * c] = hist_state[(r + 1) + (size_t) k::NG_HIST * c]; - for (size_t c = 0; c < hcd; ++c) - hist_state[((size_t) k::NG_HIST - 1) + (size_t) k::NG_HIST * c] = dev_norm[c]; - cudaFree(ple_ws); - } - - // ---- the trap that matters most: gated vs normalized as the conv input -------------------------- - // `ref/ngram.py`'s docstring calls `terms` "the padded gated values"; the source pads `normalized`. - // Feeding the conv the gated values instead is a one-word change with every shape intact, so it is - // computed here and required to differ. - { - const double rel_norm_gated = rel_l1(cap.gated.data(), cap.normalized.data(), hcd); - std::printf(" %-52s %s (%.2f%% apart)\n", "normalized vs gated as the conv input is observable", - rel_norm_gated > 0.05 ? "yes" : "*** NO ***", rel_norm_gated * 100); - if (!(rel_norm_gated > 0.05)) ++bad; - } - - // ---- the conv TAP ORDER: tap 0 reads the furthest back, not the current row --------------------- - { - // Recompute the conv on the host with the taps reversed, from the ORACLE's own `normalized`, and - // require the result to differ from the oracle's conv_out. - const size_t hcd2 = hcd; - std::vector rev(hcd2, 0.0f); - for (size_t c = 0; c < hcd2; ++c) { - float acc = 0; - for (int kk = 0; kk < k::PLE_CONV_KERNEL; ++kk) { - // THE RIVAL READING OF THE TAP CONVENTION. ggml's is `t - (K-1-k)*d`, i.e. tap 0 reads the - // FURTHEST back; the natural misreading is `t - k*d`, i.e. tap 0 reads the CURRENT row. - // - // The first version of this trap wrote `row = kk*dil` for the rival - which is ALGEBRAICALLY - // THE SAME as the correct `hist - (K-1-kk)*dil` whenever `hist == (K-1)*dil`, because - // `9-(3-kk)*3 == 3kk` identically. It reported "0.00% apart" and was measuring nothing. - // The rival has to REVERSE the row order: `(K-1-kk)*dil` gives 9,6,3,0 against the correct - // 0,3,6,9, so tap 0 pairs the kernel's first weight with the NEWEST row instead of the oldest. - const int row = (k::PLE_CONV_KERNEL - 1 - kk) * k::NGRAM_SIZE; - // ROW-FASTEST: the capture's history is ggml's `ne=(hist, hc_dim)`, flat = row + hist*channel - const float v = (row == k::NG_HIST) ? cap.normalized[c] - : cap.hist[(size_t) row + (size_t) k::NG_HIST * c]; - // GGML-NATIVE: `w_conv[k + kern*c]`, because the capture's tensor is ne=(kern, hc_dim) with - // ne0 = kern fast. `w_conv[kk*hc_dim + c]` is the TRANSPOSE and is what this reference had - // first - it reported 115% on conv_out while the GPU kernel, which carries the layout note, - // was within 4.6e-02. The oracle caught the reference, not the kernel, which is the whole - // reason for having one. - acc += cap.w_conv[(size_t) kk + (size_t) k::PLE_CONV_KERNEL * c] * v; - } - rev[c] = acc / (1.0f + std::exp(-acc)); - } - const double rel = rel_l1(cap.conv_out.data(), rev.data(), hcd2); - std::printf(" %-52s %s (%.2f%% apart)\n", "reversed conv tap order is observable", - gt(rel, 0.05) ? "yes" : "*** NO ***", rel * 100); - if (!gt(rel, 0.05)) ++bad; - } - - // ---- THE HOST f32 REFERENCE, which is what makes the gaps above ATTRIBUTABLE rather than mysterious. - // - // `ple_layer_xcheck.cpp` builds ggml's graph with the weights as **F32 tensors** (`ggml_new_tensor_2d(..., - // GGML_TYPE_F32, ...)`). `ggml_mul_mat` converts src1 to src0's `vec_dot_type`, so with an F32 weight - // ggml performs NO activation conversion at all - while the real `ple_key` is Q2_0 (contract Q8_0) and the - // real `ple_value` is BF16 (contract BF16). - // - // **The capture is therefore a valid oracle for the STRUCTURE and not for the ACTIVATION CONTRACT.** This - // reference reproduces it exactly, in f32, using the capture's own weights - which proves every LAYOUT in - // the block (the conv kernel's `k + kern*c`, the row-fastest history, per-stream grouped norms, the - // head-slowest gather) independently of the GPU. Whatever gap remains between the GPU and the capture is - // then exactly the contract, and nothing else. - // Hoisted out of the reference block below: the term-magnitude metric needs the state the LAST token - // used, and that block has already closed by the time it runs. - std::vector hist_last; - { - const size_t H = hcd, N = nd; - std::vector k_ref(H), q_ref(H), v_ref(N), gt_ref(k::NG_HC), gd_ref(H), nm_ref(H), cv_ref(H), - rs_ref(H); - auto gnorm = [&](const float* x, const float* w, float* y, int n) { - for (int c = 0; c < k::NG_HC; ++c) { - double sum = 0.0; - for (int d = 0; d < k::NG_N_EMBD; ++d) { - const float xv = x[c * k::NG_N_EMBD + d]; - sum += (double) (xv * xv); // f32 product, widened - as ggml does - } - const float mean = (float) (sum / k::NG_N_EMBD); - const float scale = 1.0f / std::sqrt(mean + cap.eps); - for (int d = 0; d < k::NG_N_EMBD; ++d) - y[c * k::NG_N_EMBD + d] = x[c * k::NG_N_EMBD + d] * scale * w[c * k::NG_N_EMBD + d]; - } - (void) n; - }; - // The SAME history advance as the GPU loop, so the two are compared on identical inputs. - std::vector hist_ref = cap.hist; - for (int t = 0; t < cap.nt; ++t) { - const float* emb = cap.emb.data() + (size_t) t * N; - const float* hid = cap.hidden.data() + (size_t) t * H; - // key = w_key @ emb, with the capture's F32 weight and NO activation conversion - for (size_t o = 0; o < H; ++o) { - double a = 0; - for (size_t i = 0; i < N; ++i) a += (double) cap.w_key[o * N + i] * (double) emb[i]; - k_ref[o] = (float) a; - } - gnorm(k_ref.data(), cap.w_nk.data(), k_ref.data(), k::NG_N_EMBD); - gnorm(hid, cap.w_nq.data(), q_ref.data(), k::NG_N_EMBD); - for (size_t o = 0; o < N; ++o) { - double a = 0; - for (size_t i = 0; i < N; ++i) a += (double) cap.w_value[o * N + i] * (double) emb[i]; - v_ref[o] = (float) a; - } - for (int c = 0; c < k::NG_HC; ++c) { - double a = 0; - for (int d = 0; d < k::NG_N_EMBD; ++d) - a += (double) k_ref[c * k::NG_N_EMBD + d] * (double) q_ref[c * k::NG_N_EMBD + d]; - const float s = (float) (a / (double) 1.0) / std::sqrt((float) k::NG_N_EMBD); - const float mag = std::sqrt(std::fmax(std::fabs(s), 1e-6f)); - const float sgn = (s > 0) ? 1.0f : ((s < 0) ? -1.0f : 0.0f); - gt_ref[c] = 1.0f / (1.0f + std::exp(-(sgn * mag))); - } - for (size_t i = 0; i < H; ++i) - gd_ref[i] = v_ref[i % N] * gt_ref[i / N]; - gnorm(gd_ref.data(), cap.w_nc.data(), nm_ref.data(), k::NG_N_EMBD); - for (size_t c = 0; c < H; ++c) { - float acc = 0; - for (int kk = 0; kk < k::PLE_CONV_KERNEL; ++kk) { - const int row = k::NG_HIST - (k::PLE_CONV_KERNEL - 1 - kk) * k::NGRAM_SIZE; - // capture history is ggml `ne=(hist, hc_dim)`: flat = row + hist*channel. `hist_ref` is - // the ADVANCED state, so this reference sees exactly what the GPU call saw. - const float vv = (row == k::NG_HIST) ? nm_ref[c] - : hist_ref[(size_t) row + (size_t) k::NG_HIST * c]; - acc += cap.w_conv[(size_t) kk + (size_t) k::PLE_CONV_KERNEL * c] * vv; - } - cv_ref[c] = acc / (1.0f + std::exp(-acc)); - } - for (size_t i = 0; i < H; ++i) rs_ref[i] = hid[i] + gd_ref[i] + cv_ref[i]; - - const size_t ok_ = (size_t) t * H, ov = (size_t) t * N, og = (size_t) t * (size_t) k::NG_HC; - struct HCmp { const char* name; const std::vector* got; const std::vector* all; - size_t off; size_t n; }; - const HCmp cmps[] = { - {"key", &k_ref, &cap.key, ok_, H}, {"value", &v_ref, &cap.value, ov, N}, - {"gate", >_ref, &cap.gate, og, (size_t) k::NG_HC}, - {"gated", &gd_ref, &cap.gated, ok_, H}, {"normalized", &nm_ref, &cap.normalized, ok_, H}, - {"conv_out", &cv_ref, &cap.conv_out, ok_, H}, - {"result", &rs_ref, &cap.result, ok_, H}, - }; - for (const HCmp& s : cmps) { - std::vector want(s.all->begin() + (long long) s.off, - s.all->begin() + (long long) (s.off + s.n)); - long long nf = 0; - const double rel = rel_l1(want.data(), s.got->data(), s.n, nullptr, &nf); - const bool ok = le(rel, 1e-4) && nf == 0; - std::printf(" host f32 reference, token %d %-12s rel %.3e (non-finite %lld)%s\n", t, s.name, - rel, nf, ok ? "" : " *** FAIL ***"); - if (!ok) ++bad; - } - - // save the state this token used, then slide it - identical to the GPU-side advance - if (t == cap.nt - 1) hist_last = hist_ref; - for (size_t c = 0; c < hcd; ++c) - for (size_t r = 0; r + 1 < (size_t) k::NG_HIST; ++r) - hist_ref[r + (size_t) k::NG_HIST * c] = hist_ref[(r + 1) + (size_t) k::NG_HIST * c]; - for (size_t c = 0; c < hcd; ++c) - hist_ref[((size_t) k::NG_HIST - 1) + (size_t) k::NG_HIST * c] = nm_ref[c]; - } - // TOLERANCE: 1e-4. Both sides are f32 (or f64-accumulated) sums of 2560 products, so the only - // difference is summation ORDER, which is ~n*eps = 2560*6e-8 = 1.5e-4 worst case and far less in - // practice. A STRUCTURAL error - a transposed conv kernel, a channel-slow history, a head-fastest - // gather - is O(1), so the two are three orders apart and the bound is not a judgement call. - } - - // ---- `conv_out`'s error must be measured against the TERMS, not the result ---------------------- - // - // The dilated conv sums four terms and the sum CANCELS: `normalized` has mean |.| around 0.70 and the - // result's is around 0.009, a factor of ~77. Dividing by the result therefore reports the CONDITION - // NUMBER and not the arithmetic - the same metric mistake this project has made four times (rounds 169, - // 189, 194, 196), and it is what made `conv_out` look like the worst stage at 4.55e-02. - { - // `dev_conv` holds the LAST token after the loop above, and the capture is token-major. - const float* oc = cap.conv_out.data() + (size_t) (cap.nt - 1) * hcd; - double num = 0, terms = 0, res = 0; - for (size_t c = 0; c < hcd; ++c) { - double t_sum = 0; - for (int kk = 0; kk < k::PLE_CONV_KERNEL; ++kk) { - const int row = k::NG_HIST - (k::PLE_CONV_KERNEL - 1 - kk) * k::NGRAM_SIZE; - const float v = (row == k::NG_HIST) - ? cap.normalized[(size_t) (cap.nt - 1) * hcd + c] - : hist_last[(size_t) row + (size_t) k::NG_HIST * c]; - t_sum += std::fabs((double) cap.w_conv[(size_t) kk + (size_t) k::PLE_CONV_KERNEL * c] * - (double) v); - } - terms += t_sum; - res += std::fabs((double) oc[c]); - num += std::fabs((double) oc[c] - (double) dev_conv[c]); - } - std::printf("\n conv_out (token %d) against the TERM magnitude, not the result: rel %.3e" - " (|result|/|terms| = %.4f)\n", - cap.nt - 1, num / terms, res / terms); - } - - std::printf("\nple_parity: %d failures (worst stage rel %.3e)\n", bad, worst_all); - if (bad) return 1; - if (selftest) std::printf("ple_parity OK\n"); - return 0; -} diff --git a/src/kernels/ple_q5_parity.cpp b/src/kernels/ple_q5_parity.cpp deleted file mode 100644 index cd387a8..0000000 --- a/src/kernels/ple_q5_parity.cpp +++ /dev/null @@ -1,59 +0,0 @@ -// Real-artifact Q5_0 PLE rows against ggml's reference dequantizer. -#define NOMINMAX -#include "strata/artifact/gguf_reader.hpp" -#include "strata/kernels/ngram.hpp" -#include "ggml.h" - -#include -#include -#include -#include -#include - -int main(int argc, char** argv) { - if (argc != 2) { - std::fprintf(stderr, "usage: ple_q5_parity \n"); - return 2; - } - strata::GgufFile gguf(argv[1]); - const auto* tensor = gguf.find("per_layer_token_embd.weight"); - if (!tensor || tensor->type != 6 || tensor->shape.size() != 2 || tensor->shape[0] != 160) { - std::fprintf(stderr, "expected Q5_0 PLE [160, N]\n"); - return 2; - } - strata::kernels::PleIoOptions options; - options.mode = strata::kernels::PleIo::Mmap; - strata::kernels::PleTable table; - std::string err; - if (!table.open(argv[1], err, options)) { - std::fprintf(stderr, "%s\n", err.c_str()); - return 1; - } - const auto* traits = ggml_get_type_traits(GGML_TYPE_Q5_0); - const uint8_t* bytes = gguf.tensor_data(*tensor); - const uint32_t probes[] = {0, 1, 12345, 20000003, (uint32_t) (table.rows() - 1)}; - double max_abs = 0.0; - for (uint32_t row : probes) { - float got[160], want[160]; - table.read_row(row, got); - traits->to_float(bytes + (size_t) row * 110, want, 160); - for (int i = 0; i < 160; ++i) - max_abs = std::max(max_abs, (double) std::fabs(got[i] - want[i])); - } - uint32_t rows[16]; - for (int i = 0; i < 16; ++i) rows[i] = probes[i % 5]; - float batch[16 * 160]; - if (!table.issue(rows) || !table.collect(batch, err)) { - std::fprintf(stderr, "collect: %s\n", err.c_str()); - return 1; - } - for (int h = 0; h < 16; ++h) { - float want[160]; - traits->to_float(bytes + (size_t) rows[h] * 110, want, 160); - for (int i = 0; i < 160; ++i) - max_abs = std::max(max_abs, (double) std::fabs(batch[h * 160 + i] - want[i])); - } - std::printf("Q5_0 PLE: %zu rows, max_abs %.3e %s\n", (size_t) table.rows(), max_abs, - max_abs <= 1e-6 ? "PASS" : "FAIL"); - return max_abs <= 1e-6 ? 0 : 1; -} diff --git a/src/kernels/q5_projection_parity.cpp b/src/kernels/q5_projection_parity.cpp deleted file mode 100644 index 20faf99..0000000 --- a/src/kernels/q5_projection_parity.cpp +++ /dev/null @@ -1,62 +0,0 @@ -// Q5_1 shared-expert projection: Strata CUDA dequantization vs ggml. -#define NOMINMAX -#include "strata/artifact/gguf_reader.hpp" -#include "strata/kernels/dequant_bf16.hpp" -#include "ggml.h" - -#include -#include -#include -#include -#include -#include -#include - -int main(int argc, char** argv) { - if (argc != 2) { - std::fprintf(stderr, "usage: q5_projection_parity \n"); - return 2; - } - strata::GgufFile gguf(argv[1]); - const auto* t = gguf.find("blk.0.ffn_down_shexp.weight"); - if (!t || t->type != 7 || t->shape.size() != 2) { - std::fprintf(stderr, "expected blk.0.ffn_down_shexp.weight Q5_1\n"); - return 2; - } - const int64_t cols = (int64_t) t->shape[0], rows = std::min(4, (int64_t) t->shape[1]); - const size_t weight_bytes = (size_t) rows * (size_t) (cols / 32) * 24; - const size_t elements = (size_t) rows * (size_t) cols; - const uint8_t* source = gguf.tensor_data(*t); - void *dweight = nullptr, *dfloat = nullptr, *dbf16 = nullptr; - if (cudaMalloc(&dweight, weight_bytes) != cudaSuccess || - cudaMalloc(&dfloat, elements * sizeof(float)) != cudaSuccess || - cudaMalloc(&dbf16, elements * sizeof(uint16_t)) != cudaSuccess) { - std::fprintf(stderr, "CUDA allocation failed\n"); - return 1; - } - cudaMemcpy(dweight, source, weight_bytes, cudaMemcpyHostToDevice); - strata::kernels::dequant_f32(7, dweight, 0, rows, cols, (float*) dfloat, nullptr); - strata::kernels::dequant_bf16(7, dweight, 0, rows, cols, (uint16_t*) dbf16, nullptr); - std::vector got(elements), ref(elements); - std::vector got_bf16(elements); - cudaMemcpy(got.data(), dfloat, elements * sizeof(float), cudaMemcpyDeviceToHost); - cudaMemcpy(got_bf16.data(), dbf16, elements * sizeof(uint16_t), cudaMemcpyDeviceToHost); - cudaFree(dweight); cudaFree(dfloat); cudaFree(dbf16); - const auto* traits = ggml_get_type_traits(GGML_TYPE_Q5_1); - for (int64_t r = 0; r < rows; ++r) - traits->to_float(source + (size_t) r * (size_t) (cols / 32) * 24, - ref.data() + (size_t) r * (size_t) cols, cols); - double max_abs = 0; - size_t bf16_bad = 0; - for (size_t i = 0; i < elements; ++i) { - max_abs = std::max(max_abs, (double) std::fabs(got[i] - ref[i])); - uint32_t bits; - std::memcpy(&bits, &ref[i], sizeof(bits)); - const uint16_t expected = (uint16_t) ((bits + 0x7fffu + ((bits >> 16) & 1u)) >> 16); - if (got_bf16[i] != expected) ++bf16_bad; - } - const bool ok = max_abs <= 1e-6 && bf16_bad == 0; - std::printf("Q5_1 projection: %zu elements, max_abs %.3e, bf16 differences %zu %s\n", - elements, max_abs, bf16_bad, ok ? "PASS" : "FAIL"); - return ok ? 0 : 1; -} diff --git a/src/kernels/qsa_attn_bench.cpp b/src/kernels/qsa_attn_bench.cpp deleted file mode 100644 index b56e4da..0000000 --- a/src/kernels/qsa_attn_bench.cpp +++ /dev/null @@ -1,151 +0,0 @@ -// src/kernels/qsa_attn_bench.cpp - what the split-K decode attention costs per call (GPU, synthetic, no model). -// -// qsa_attn_bench [--heads N,KV] [--kv fp16|int8|q4_0] [--cells C1,C2,...] [--reps R] -// -// One query row over `cells` cells (the identity selection, width = cells) through `qsa_decode_attn_step` on random -// pools behind a shuffled page table; the time is the median of `reps` back-to-back calls bracketed by events. -// Uses only the entry points the kernel had before Qwen3.6 step 3 (explicit ids), so the same file builds against -// the old kernel and the new one: the before / after numbers of docs/qwen36-port/step3-attn.md come from it. -// Exit 77 without a device. -#include "strata/kernels/qsa_decode_attn.hpp" -#include "strata/kernels/kv_q4.hpp" -#include "strata/kernels/kv_q8.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include - -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 T* up(const std::vector& 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 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 nd(0.f, 1.f); - k::QsaAttnPools pl; - uint64_t bytes_per_cell = 0; - if (kv == "fp16") { - std::vector 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 code(-127, 127); - std::vector kq((size_t) rows * HD), vq((size_t) rows * HD); - std::vector 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 byte(0, 255); - const uint64_t ROW = k::kv_q4_bytes_per_head((int) HD); - std::vector 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 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 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 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 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; -} diff --git a/src/kernels/qsa_dense_parity.cpp b/src/kernels/qsa_dense_parity.cpp deleted file mode 100644 index 0287a1e..0000000 --- a/src/kernels/qsa_dense_parity.cpp +++ /dev/null @@ -1,616 +0,0 @@ -// src/kernels/qsa_dense_parity.cpp - dense attention (Qwen3.6-35B-A3B, docs/QWEN36-35B-A3B.md 3.3) through the -// engine's split-K decode kernel and the tensor-core prompt kernel: the query-head group G as a template -// parameter (2, 8, 12), a null `ids` as the identity selection, the bounded split-K scratch, and the sparse -// selection width refused for the dense model. GPU, synthetic, plus the oracle's fixtures when given. -// -// qsa_dense_parity [--fixtures DIR] [--selftest] -// -// DIR is what cmake/qwen36_attn_fixtures.cmake writes: .gguf and -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 - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -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 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 T* up(const std::vector& h) { - T* d = dalloc(h.size()); - ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload"); - return d; -} -template std::vector down(const T* d, size_t n) { - std::vector 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& a, const std::vector& 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& a, const std::vector& 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& a, const std::vector& 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& q, const std::vector& K, const std::vector& V, int64_t cells, - int64_t width, int64_t n_head, int64_t n_kv, std::vector& out, std::vector* 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 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 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& x, int64_t rows, int n_rot, double theta, const std::vector& 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 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 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& kcur, - const std::vector& 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(P.rows * HD); P.v_pool = dalloc(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(P.rows * HD); P.v_q = dalloc(P.rows * HD); - P.k_scale = dalloc(P.rows * (HD / k::KV_Q8_GROUP)); P.v_scale = dalloc(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(P.rows * q4row); P.v_q4 = dalloc(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(P.rows * HD); P.k_scale = dalloc(P.rows * (HD / k::KV_Q8_GROUP)); - P.v_q4 = dalloc(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 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& 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& 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& 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(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 nd(0.f, 1.f); - std::vector 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(width - 77, 1)}; - std::vector 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 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(scr * n_q); - float* d_attn = dalloc((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((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 ref_row; - for (int64_t i = 0; i < n_q; ++i) { - std::vector 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 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 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((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 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 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 load_f32(const fs::path& p, size_t expect) { - std::vector 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 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: -.f32, a repeated name numbered -#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 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 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 kc(k_eng), vc(v_in); - Pools P = make_pools(0, T, s, rng, kc, vc); - std::vector 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(k::qsa_decode_attn_scratch_floats(cap, s) * T); - float* d_attn = dalloc((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 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 K32(k_eng.begin(), k_eng.end()), V32(v_in.begin(), v_in.end()); - std::vector kqv_f32((size_t) NH * T * HD), probs_f32((size_t) NH * T * T, 0.f), row; - std::vector pr; - for (int64_t t = 0; t < T; ++t) { - std::vector 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((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 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 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 Ka(ka.begin(), ka.end()); - std::vector kqv_a((size_t) NH * T * HD); - for (int64_t t = 0; t < T; ++t) { - std::vector 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 kqv_m((size_t) NH * T * HD); - for (int64_t t = 0; t < T; ++t) { - std::vector 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; -} diff --git a/src/kernels/qsa_oracle_vectors.inc b/src/kernels/qsa_oracle_vectors.inc deleted file mode 100644 index 0ceec33..0000000 --- a/src/kernels/qsa_oracle_vectors.inc +++ /dev/null @@ -1,134 +0,0 @@ -// GENERATED by scripts/_gen_f16_oracle.py - do not edit. -// {f32 bits, np.float16(np.float32(x)) bits} interleaved, flat, for qsa_parity.cpp. - 0x00000000u, 0x0000u, 0x80000000u, 0x8000u, 0x3F800000u, 0x3C00u, - 0xBF800000u, 0xBC00u, 0x3F000000u, 0x3800u, 0x477FE000u, 0x7BFFu, - 0x477FEF00u, 0x7BFFu, 0x477FF000u, 0x7C00u, 0x47800000u, 0x7C00u, - 0x7149F2CAu, 0x7C00u, 0xF149F2CAu, 0xFC00u, 0x38800000u, 0x0400u, - 0x33800000u, 0x0001u, 0x33000000u, 0x0000u, 0x3380D959u, 0x0001u, - 0xB380D959u, 0x8001u, 0x337FFAE5u, 0x0001u, 0x322BCC77u, 0x0000u, - 0x00000001u, 0x0000u, 0x3EAAAAABu, 0x3555u, 0x39000000u, 0x0800u, - 0x47000000u, 0x7800u, 0x3727C5ACu, 0x00A8u, 0x38800800u, 0x0400u, - 0x38801000u, 0x0400u, 0x38801800u, 0x0401u, 0x39000800u, 0x0800u, - 0x39001000u, 0x0800u, 0x39001800u, 0x0801u, 0x39800000u, 0x0C00u, - 0x39800800u, 0x0C00u, 0x39801000u, 0x0C00u, 0x39801800u, 0x0C01u, - 0x3A000000u, 0x1000u, 0x3A000800u, 0x1000u, 0x3A001000u, 0x1000u, - 0x3A001800u, 0x1001u, 0x3A800000u, 0x1400u, 0x3A800800u, 0x1400u, - 0x3A801000u, 0x1400u, 0x3A801800u, 0x1401u, 0x3B000000u, 0x1800u, - 0x3B000800u, 0x1800u, 0x3B001000u, 0x1800u, 0x3B001800u, 0x1801u, - 0x3B800000u, 0x1C00u, 0x3B800800u, 0x1C00u, 0x3B801000u, 0x1C00u, - 0x3B801800u, 0x1C01u, 0x3C000000u, 0x2000u, 0x3C000800u, 0x2000u, - 0x3C001000u, 0x2000u, 0x3C001800u, 0x2001u, 0x3C800000u, 0x2400u, - 0x3C800800u, 0x2400u, 0x3C801000u, 0x2400u, 0x3C801800u, 0x2401u, - 0x3D000000u, 0x2800u, 0x3D000800u, 0x2800u, 0x3D001000u, 0x2800u, - 0x3D001800u, 0x2801u, 0x3D800000u, 0x2C00u, 0x3D800800u, 0x2C00u, - 0x3D801000u, 0x2C00u, 0x3D801800u, 0x2C01u, 0x3E000000u, 0x3000u, - 0x3E000800u, 0x3000u, 0x3E001000u, 0x3000u, 0x3E001800u, 0x3001u, - 0x3E800000u, 0x3400u, 0x3E800800u, 0x3400u, 0x3E801000u, 0x3400u, - 0x3E801800u, 0x3401u, 0x3F000800u, 0x3800u, 0x3F001000u, 0x3800u, - 0x3F001800u, 0x3801u, 0x3F800800u, 0x3C00u, 0x3F801000u, 0x3C00u, - 0x3F801800u, 0x3C01u, 0x40000000u, 0x4000u, 0x40000800u, 0x4000u, - 0x40001000u, 0x4000u, 0x40001800u, 0x4001u, 0x40800000u, 0x4400u, - 0x40800800u, 0x4400u, 0x40801000u, 0x4400u, 0x40801800u, 0x4401u, - 0x41000000u, 0x4800u, 0x41000800u, 0x4800u, 0x41001000u, 0x4800u, - 0x41001800u, 0x4801u, 0x41800000u, 0x4C00u, 0x41800800u, 0x4C00u, - 0x41801000u, 0x4C00u, 0x41801800u, 0x4C01u, 0x42000000u, 0x5000u, - 0x42000800u, 0x5000u, 0x42001000u, 0x5000u, 0x42001800u, 0x5001u, - 0x42800000u, 0x5400u, 0x42800800u, 0x5400u, 0x42801000u, 0x5400u, - 0x42801800u, 0x5401u, 0x43000000u, 0x5800u, 0x43000800u, 0x5800u, - 0x43001000u, 0x5800u, 0x43001800u, 0x5801u, 0x43800000u, 0x5C00u, - 0x43800800u, 0x5C00u, 0x43801000u, 0x5C00u, 0x43801800u, 0x5C01u, - 0x44000000u, 0x6000u, 0x44000800u, 0x6000u, 0x44001000u, 0x6000u, - 0x44001800u, 0x6001u, 0x44800000u, 0x6400u, 0x44800800u, 0x6400u, - 0x44801000u, 0x6400u, 0x44801800u, 0x6401u, 0x45000000u, 0x6800u, - 0x45000800u, 0x6800u, 0x45001000u, 0x6800u, 0x45001800u, 0x6801u, - 0x45800000u, 0x6C00u, 0x45800800u, 0x6C00u, 0x45801000u, 0x6C00u, - 0x45801800u, 0x6C01u, 0x46000000u, 0x7000u, 0x46000800u, 0x7000u, - 0x46001000u, 0x7000u, 0x46001800u, 0x7001u, 0x46800000u, 0x7400u, - 0x46800800u, 0x7400u, 0x46801000u, 0x7400u, 0x46801800u, 0x7401u, - 0x47000800u, 0x7800u, 0x47001000u, 0x7800u, 0x47001800u, 0x7801u, - 0x33C00000u, 0x0002u, 0x34000000u, 0x0002u, 0x34200000u, 0x0002u, - 0x34400000u, 0x0003u, 0x34600000u, 0x0004u, 0x34800000u, 0x0004u, - 0x34900000u, 0x0004u, 0x34A00000u, 0x0005u, 0x34B00000u, 0x0006u, - 0x34C00000u, 0x0006u, 0x34D00000u, 0x0006u, 0x34E00000u, 0x0007u, - 0x34F00000u, 0x0008u, 0x35000000u, 0x0008u, 0x35080000u, 0x0008u, - 0x35100000u, 0x0009u, 0x35180000u, 0x000Au, 0x35200000u, 0x000Au, - 0x35280000u, 0x000Au, 0x35300000u, 0x000Bu, 0x35380000u, 0x000Cu, - 0x35400000u, 0x000Cu, 0x35480000u, 0x000Cu, 0x35500000u, 0x000Du, - 0x35580000u, 0x000Eu, 0x35600000u, 0x000Eu, 0x35680000u, 0x000Eu, - 0x35700000u, 0x000Fu, 0x35780000u, 0x0010u, 0x35800000u, 0x0010u, - 0x35840000u, 0x0010u, 0x35880000u, 0x0011u, 0x358C0000u, 0x0012u, - 0x35900000u, 0x0012u, 0x35940000u, 0x0012u, 0x35980000u, 0x0013u, - 0x359C0000u, 0x0014u, 0x35A00000u, 0x0014u, 0x35A40000u, 0x0014u, - 0x35A80000u, 0x0015u, 0x35AC0000u, 0x0016u, 0x35B00000u, 0x0016u, - 0x35B40000u, 0x0016u, 0x35B80000u, 0x0017u, 0x35BC0000u, 0x0018u, - 0x35C00000u, 0x0018u, 0x35C40000u, 0x0018u, 0x35C80000u, 0x0019u, - 0x35CC0000u, 0x001Au, 0x35D00000u, 0x001Au, 0x35D40000u, 0x001Au, - 0x35D80000u, 0x001Bu, 0x35DC0000u, 0x001Cu, 0x35E00000u, 0x001Cu, - 0x35E40000u, 0x001Cu, 0x35E80000u, 0x001Du, 0x35EC0000u, 0x001Eu, - 0x35F00000u, 0x001Eu, 0x35F40000u, 0x001Eu, 0x35F80000u, 0x001Fu, - 0x35FC0000u, 0x0020u, 0x36000000u, 0x0020u, 0x36020000u, 0x0020u, - 0x36040000u, 0x0021u, 0x36060000u, 0x0022u, 0x36080000u, 0x0022u, - 0x360A0000u, 0x0022u, 0x360C0000u, 0x0023u, 0x360E0000u, 0x0024u, - 0x36100000u, 0x0024u, 0x36120000u, 0x0024u, 0x36140000u, 0x0025u, - 0x36160000u, 0x0026u, 0x36180000u, 0x0026u, 0x361A0000u, 0x0026u, - 0x361C0000u, 0x0027u, 0x361E0000u, 0x0028u, 0xB70C380Bu, 0x808Cu, - 0xC62CBAD6u, 0xF166u, 0xC6167C83u, 0xF0B4u, 0xC5E87D75u, 0xEF44u, - 0xB411536Du, 0x8002u, 0x422B1CD9u, 0x5159u, 0x3BAC7D0Au, 0x1D64u, - 0x3E777C7Eu, 0x33BCu, 0xC34DA8EFu, 0xDA6Du, 0xC7F7B602u, 0xFC00u, - 0xB58914D2u, 0x8011u, 0x40727A6Fu, 0x4394u, 0x3946E5AAu, 0x0A37u, - 0x4671C2D0u, 0x738Eu, 0x3565BDBDu, 0x000Eu, 0x3BEFF6A4u, 0x1F80u, - 0xB136ED95u, 0x8000u, 0xBB940CC6u, 0x9CA0u, 0xBD5ADDB8u, 0xAAD7u, - 0x42954B1Eu, 0x54AAu, 0x35F55F4Cu, 0x001Fu, 0x33ABC544u, 0x0001u, - 0x42DE8A1Bu, 0x56F4u, 0x445C4B5Eu, 0x62E2u, 0xC26C283Au, 0xD361u, - 0x34959C9Du, 0x0005u, 0x3D035DE5u, 0x281Bu, 0xBD5F8FB9u, 0xAAFCu, - 0x42A6E954u, 0x5537u, 0x3978C191u, 0x0BC6u, 0xB4FC63E2u, 0x8008u, - 0x40B270AEu, 0x4594u, 0x46CBF834u, 0x7660u, 0x363DC03Fu, 0x002Fu, - 0xB1B0AAD8u, 0x8000u, 0x477E0850u, 0x7BF0u, 0x3357EDFFu, 0x0001u, - 0xBEF7D490u, 0xB7BFu, 0xB230011Bu, 0x8000u, 0xC41F8C42u, 0xE0FCu, - 0x40EE6FA8u, 0x4773u, 0xC020D7F5u, 0xC107u, 0xBA17B5A6u, 0x90BEu, - 0x39F609F8u, 0x0FB0u, 0xC0169BEBu, 0xC0B5u, 0xC34D25A0u, 0xDA69u, - 0xC23263C4u, 0xD193u, 0xC05BA352u, 0xC2DDu, 0xC7355027u, 0xF9ABu, - 0x335A4A8Du, 0x0001u, 0x4196D58Bu, 0x4CB7u, 0xB2F09C6Au, 0x8000u, - 0xC6A7EA97u, 0xF53Fu, 0x308ED1F1u, 0x0000u, 0x33A60BD6u, 0x0001u, - 0xB486B455u, 0x8004u, 0x3F4A08F6u, 0x3A50u, 0x363B9A5Bu, 0x002Fu, - 0xC48BA363u, 0xE45Du, 0x3EFBCC45u, 0x37DEu, 0xBDF8FE27u, 0xAFC8u, - 0xC55797A8u, 0xEABDu, 0xC008C482u, 0xC046u, 0xC3ED6604u, 0xDF6Bu, - 0xBF0D00C6u, 0xB868u, 0xC3AC7327u, 0xDD64u, 0x3B6245DCu, 0x1B12u, - 0xC4AD660Bu, 0xE56Bu, 0x404E99CEu, 0x4275u, 0xB09DE09Du, 0x8000u, - 0x3AEFA82Eu, 0x177Du, 0x4797A354u, 0x7C00u, 0xBC662E46u, 0xA331u, - 0x3EBF9AF7u, 0x35FDu, 0xBF8B651Cu, 0xBC5Bu, 0x3DC3DF55u, 0x2E1Fu, - 0x3420659Fu, 0x0003u, 0xB5BF3014u, 0x8018u, 0x3C229714u, 0x2115u, - 0xBE7A7284u, 0xB3D4u, 0xC544A929u, 0xEA25u, 0x34711195u, 0x0004u, - 0x365D12F9u, 0x0037u, 0xC71DE14Du, 0xF8EFu, 0xBBB6EE2Au, 0x9DB7u, - 0x4285DC79u, 0x542Fu, 0xC1479433u, 0xCA3Du, 0x443A29D6u, 0x61D1u, - 0xC6870A39u, 0xF438u, 0x470B6E9Cu, 0x785Bu, 0x449AF78Au, 0x64D8u, - 0x34098DE2u, 0x0002u, 0xBBFC11E5u, 0x9FE1u, 0x42922E1Bu, 0x5491u, - 0x3DBFB02Eu, 0x2DFEu, 0xB5A516FCu, 0x8015u, 0x447B2862u, 0x63D9u, - 0xC085C952u, 0xC42Eu, 0x442CC939u, 0x6166u, 0xB126F155u, 0x8000u, - 0x3F982F47u, 0x3CC1u, 0xC36C38DFu, 0xDB62u, 0xC1E21DBCu, 0xCF11u, - 0xC42DA5DDu, 0xE16Du, 0x3AD3CEC3u, 0x169Eu, 0x35319027u, 0x000Bu, - 0x34F38AABu, 0x0008u, 0xBBB4902Du, 0x9DA5u, 0x42A8B660u, 0x5546u, - 0xBE02F143u, 0xB018u, 0xB84BE09Au, 0x8330u, 0xBF215C12u, 0xB90Bu, - 0xBA674F20u, 0x933Au, 0xC0EBE307u, 0xC75Fu, 0x3AC119A5u, 0x1609u, - 0x344B18AFu, 0x0003u, 0xC183EB4Bu, 0xCC1Fu, 0xB96414D1u, 0x8B21u, - 0xB74DB17Du, 0x80CEu, 0xC3AF2570u, 0xDD79u, 0xB570C5F3u, 0x800Fu, - 0xB568C27Cu, 0x800Fu, 0xBE03F2E7u, 0xB020u, 0xBF216402u, 0xB90Bu, - 0xC16D1B4Au, 0xCB69u, 0x35897C73u, 0x0011u, 0xB771D56Bu, 0x80F2u, - 0xB5BB317Bu, 0x8017u, 0x367F3A0Bu, 0x0040u, 0xB6EE0B0Du, 0x8077u, - 0x416379C7u, 0x4B1Cu, 0xBA821968u, 0x9411u, 0x3D07874Du, 0x283Cu, - 0xBB951706u, 0x9CA9u, 0x402BDEC0u, 0x415Fu, 0x37F183A2u, 0x01E3u, - 0x3C0CE282u, 0x2067u, 0xBD40215Fu, 0xAA01u, 0x3BE1404Eu, 0x1F0Au, - 0x429C6774u, 0x54E3u, 0xC0E2E84Eu, 0xC717u, 0xC118375Du, 0xC8C2u, - 0x338E0178u, 0x0001u, 0xBEADFB76u, 0xB570u, 0xC2CDE39Bu, 0xD66Fu, - 0x3505E06Fu, 0x0008u, 0xC0278755u, 0xC13Cu, 0x3A727A53u, 0x1394u, - 0x3F954D3Fu, 0x3CAAu, 0xBD8BB0B5u, 0xAC5Eu, 0x3F5C2F06u, 0x3AE1u, - 0x43140960u, 0x58A0u, 0x3849FB8Au, 0x0328u, 0x3A18FD84u, 0x10C8u, - 0xBE975FD3u, 0xB4BBu, 0xC0BF694Au, 0xC5FBu, 0x3D56DA35u, 0x2AB7u, - 0xC28C14ADu, 0xD461u, 0xB6BA702Au, 0x805Du, 0xC20FB679u, 0xD07Eu, - 0x412B1285u, 0x4959u, 0x3823D6E4u, 0x028Fu, 0xBC274EF6u, 0xA13Au, - 0x3ABACE39u, 0x15D6u, 0xB39C87AEu, 0x8001u, 0x3D9CCD85u, 0x2CE6u, - 0xBAC131E0u, 0x960Au, 0x33BC76EAu, 0x0001u, 0x38BBFB64u, 0x05E0u, - 0x3A718DF9u, 0x138Cu, 0x3BCD8BA9u, 0x1E6Cu, 0x4245E77Du, 0x522Fu, - 0xB8E90C7Bu, 0x8748u, 0xBA9F4029u, 0x94FAu, 0xBAA46DE7u, 0x9523u, - 0x3E984F19u, 0x34C2u, 0x380D4F2Eu, 0x0235u, 0x427ADE3Eu, 0x53D7u, - 0xB772280Fu, 0x80F2u, 0x371B1E4Eu, 0x009Bu, diff --git a/src/kernels/qsa_parity.cpp b/src/kernels/qsa_parity.cpp deleted file mode 100644 index 55dec2d..0000000 --- a/src/kernels/qsa_parity.cpp +++ /dev/null @@ -1,1555 +0,0 @@ -// src/kernels/qsa_parity.cpp - P2.S2's test for the QSA cache, indexer, selection and attention. -// -// `ref/qsa.py` carries eleven PROPERTY checks and `ref/model.py::_qsa` is the layer as the model runs it. The -// readings a prose transcription gets WRONG, each of which produces a well-formed result of the right shape, -// are computed here the wrong way round AND required to differ MATERIALLY before the kernel is judged against -// the right one - a test that only does the second half passes against either reading: -// -// 1. `pooled[b]` is rotated at the block's FIRST cell. The reference's PROPERTY 4 pins it against the -// block's LAST cell; both give a unit-norm vector and the same downstream shape. -// 2. Pool THEN norm (`rms_norm(mean(x))`) and not norm THEN pool (`mean(rms_norm(x))`). `ref/model.py` L358 -// is explicit, and the two differ whenever the four cells have different magnitudes. -// 3. The spare slot's key is `rms_norm(raw[0])` - cell ZERO - and not the last raw key, and the tail cells -// map to THAT slot and not to the last complete block. A three-row raw tail cannot produce it unless -// cell 0's key is kept, which is what makes this a real design constraint rather than a detail. -// 4. The indexer's Relu is PER HEAD, summed afterwards. `relu(sum_h dot_h)` is the rival reading and -// differs whenever any head's dot is negative. -// 5. The q -> kv head map is `q / 12` (integer division), NOT `q % 2`. `ref/qsa.py` PROPERTY 7 tests the -// same thing; with 24 and 2 the two give [0 x12, 1 x12] and [0,1,0,1,...]. -// 6. The attention reads ONLY the selected cells. The source writes -inf into the mask and zeros at the -// top-k indices, so an unselected cell has weight exactly zero even when it would score highest - -// PROPERTY 8's fixture, reproduced here with its own numbers. -// 7. `attn *= sigmoid(gate)` with the gate taken from the SECOND half of each head's 2*head_dim block, and -// the rounding to fp16 happening AFTER the multiply (one rounding, not two). -// 8. The KV cache is PAGED and the page table is not assumed to be the identity: the pool is written and -// read back at page_size 1, 4 and 512 with a REVERSED table, and the kernel's own reading of the layout -// is compared against two rivals (linear, i.e. the table ignored; and cell-major inside the page). -// -// THE METRIC. Both sums here - the indexer's sum of four relu'd dots and the attention's weighted sum of -// value rows - cancel, so a plain |want-got|/|want| reports the condition number instead of the arithmetic. -// The project has made that mistake four times (rounds 169, 189, 194, 196); where a sum is compared below, the -// denominator is the magnitude of the TERMS. -// -// WHAT SETS EACH TOLERANCE, because a tolerance nobody can explain is one nobody can tighten: -// * the fp16 converter, the pool contents, the gathered scratch and the spare indexer key: EXACT. The only -// arithmetic is a conversion, and section 0 checks that conversion against numpy's float16 over 395 -// vectors covering ties in both directions, subnormals and overflow - an oracle sharing no code with it - -// plus all 65,536 fp16 patterns in the reverse direction. -// * the pooled block keys: 1e-6. The pooling and the norm are double on both sides and are bit-exact -// BEFORE the rotation; the residual is `rope_neox_apply` (f32, reused rather than re-implemented) against -// the reference's float64 rotation, the class round 189 measured at ~1e-7. -// * the indexer scores: 1e-6 against Sum|dot_h| + |bias|, set by the fp32 storage of the pooled keys - -// 2^-24 per element over a 128-term dot. -// * the selected ids: EXACT. `docs/capture-format.md` L127 gives `indexer_ids` no tolerance. -// * the attention against a reference reading the SAME fp16 cache: 1e-5, set by f32 accumulation over -// 256-term dots plus `expf`'s 2 ulp. This is the KERNEL's number. -// * the attention against a reference reading the f32 keys: REPORTED and then checked against the phase's -// 1e-3 for FP16 paths. That difference is the FP16 CACHE's cost, not the kernel's, and it is kept -// separate so a kernel bug cannot hide inside it. -#include "strata/kernels/qsa.hpp" -#include "strata/kernels/native_qsa_indexer.hpp" - -#include "strata/kernels/f16_bits.hpp" -#include "strata/kernels/rope.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { - -using strata::kernels::f16_from_f32; -using strata::kernels::f32_from_f16; - -void check(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -/// A device buffer with the boilerplate folded in. A test that allocates twenty buffers by hand spends its -/// attention on memcpy arguments instead of on the kernel. -template -struct Dev { - T* p = nullptr; - Dev() = default; - explicit Dev(size_t n) { alloc(n); } - ~Dev() { if (p) cudaFree(p); } - Dev(const Dev&) = delete; - Dev& operator=(const Dev&) = delete; - void alloc(size_t n) { - if (p) { cudaFree(p); p = nullptr; } - if (n) check(cudaMalloc(&p, n * sizeof(T)), "cudaMalloc"); - } - void put(const std::vector& v) { - if (!p) alloc(v.size()); - check(cudaMemcpy(p, v.data(), v.size() * sizeof(T), cudaMemcpyHostToDevice), "H2D"); - } - std::vector get(size_t n) const { - std::vector v(n); - check(cudaMemcpy(v.data(), p, n * sizeof(T), cudaMemcpyDeviceToHost), "D2H"); - return v; - } -}; - -std::vector as_d(const std::vector& v) { return std::vector(v.begin(), v.end()); } -std::vector as_f(const std::vector& v) { - std::vector o(v.size()); - for (size_t i = 0; i < v.size(); ++i) o[i] = (float) v[i]; - return o; -} - -/// Relative error against the magnitude of the TERMS. See the header comment. -double rel_terms(double want, double got, double terms) { - return std::fabs(want - got) / (terms > 1e-30 ? terms : 1e-30); -} - -double rel_l1(const std::vector& a, const std::vector& b) { - double d = 0, m = 0; - for (size_t i = 0; i < a.size(); ++i) { - d += std::fabs(a[i] - b[i]); - m += std::fabs(a[i]); - } - return d / (m > 1e-30 ? m : 1e-30); -} - -int g_bad = 0; -std::string pct(double rel) { - char b[32]; - std::snprintf(b, sizeof b, "%.2f%% apart", rel * 100.0); - return b; -} -void verdict(const std::string& name, bool ok, const std::string& detail = "") { - std::printf(" %-48s %-6s %s\n", name.c_str(), ok ? "yes" : "*** NO ***", detail.c_str()); - if (!ok) ++g_bad; -} -void report(const std::string& name, double v, const char* unit) { - std::printf(" %-48s %s %.3e\n", name.c_str(), unit, v); -} -void require(const std::string& name, bool ok, const std::string& detail = "") { - std::printf(" %-48s %-6s %s\n", name.c_str(), ok ? "ok" : "*** BAD ***", detail.c_str()); - if (!ok) ++g_bad; -} - -// ================= the reference: ref/qsa.py + ref/model.py, in double ================= - -/// Which of the rival readings to compute. The defaults are the SOURCE's reading. -struct Alt { - bool rotate_at_block_start = true; ///< false: rotate at the block's LAST cell (WRONG) - bool pool_then_norm = true; ///< false: mean of the per-cell norms (WRONG) - bool dead_from_first = true; ///< false: the spare key from the LAST raw key (WRONG) - bool rope_raw = false; ///< true: rotate the raw keys before pooling (WRONG) - bool relu_per_head = true; ///< false: relu(sum of the head dots) (WRONG) - bool use_relu = true; ///< false: no relu at all (WRONG) - bool use_bias = true; ///< false: drop the per-block bias (WRONG) - bool kv_divide = true; ///< false: q % n_head_kv instead of q / 12 (WRONG) - bool apply_scale = true; ///< false: no 1/sqrt(head_dim) (WRONG) - bool gate_second_half = true; ///< false: the gate from the FIRST half (WRONG) - bool gate_sigmoid = true; ///< false: silu instead of sigmoid (WRONG) -}; - -/// `x*y + z` with the product ROUNDED first, i.e. no FMA contraction. -/// -/// MSVC contracts `ss += v*v` into an FMA even under /fp:precise, so the reference was MORE accurate than -/// the kernel's explicit `__fadd_rn(__fmul_rn(v, v))` and the spare key came out one bit different in 7 of -/// 128 components. The kernel's arithmetic is what is under test, so the reference REPRODUCES it instead of -/// beating it; `volatile` is what stops the compiler re-fusing the two operations. -double mul_add_plain(double x, double y, double z) { - const volatile double p = x * y; - return z + p; -} - -/// `ref/qsa.py::rms_norm` in double, in place. `w` may be empty (w = None). -void ref_rms_norm(std::vector& x, const std::vector& w, float eps) { - double ss = 0; - for (double v : x) ss = mul_add_plain(v, v, ss); - const double inv = 1.0 / std::sqrt(ss / (double) x.size() + (double) eps); - for (size_t i = 0; i < x.size(); ++i) x[i] = x[i] * inv * (w.empty() ? 1.0 : (double) w[i]); -} - -/// `ref/qsa.py::rope_neox` in double: NEOX pairs (i, i + n_rot/2), partial over the first n_rot dims. -/// -/// `terms`, when given, receives the magnitude of each component's TERMS - `|a c| + |b s|` where the -/// rotation subtracts - so a comparison can divide by that instead of by the result, which cancels. -void ref_rope_neox(std::vector& x, double pos, int n_rot, double theta, - std::vector* terms = nullptr) { - const int half = n_rot / 2; - std::vector a(x.begin(), x.begin() + half), b(x.begin() + half, x.begin() + n_rot); - if (terms) { - terms->assign(x.size(), 0.0); - for (size_t i = (size_t) n_rot; i < x.size(); ++i) (*terms)[i] = std::fabs(x[i]); - } - for (int i = 0; i < half; ++i) { - const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot); - const double ang = pos * inv, c = std::cos(ang), s = std::sin(ang); - x[i] = a[i] * c - b[i] * s; - x[half + i] = a[i] * s + b[i] * c; - if (terms) { - (*terms)[i] = std::fabs(a[i] * c) + std::fabs(b[i] * s); - (*terms)[half + i] = std::fabs(a[i] * s) + std::fabs(b[i] * c); - } - } -} - -const int64_t REF_R = 4; ///< IDX_BLOCK, checked against the shapes at the top of main - -/// `QsaCache`, holding f64 rows - the reference never sees an fp16 key. -struct RefCache { - std::vector> k, v, raw; - std::vector pos; - int64_t size() const { return (int64_t) pos.size(); } - void append(std::vector kk, std::vector vv, std::vector rr, double p) { - k.push_back(std::move(kk)); - v.push_back(std::move(vv)); - raw.push_back(std::move(rr)); - pos.push_back(p); - } -}; - -/// `QsaCache.pooled_raw(r)` - BEFORE the norm, which is the only place the 1/r divisor is observable. -std::vector ref_pooled_raw(const RefCache& c) { - const int64_t n_bid = c.size() / REF_R, dim = (int64_t) c.raw[0].size(); - std::vector out((size_t) n_bid * dim, 0.0); - for (int64_t b = 0; b < n_bid; ++b) - for (int64_t i = 0; i < REF_R; ++i) - for (int64_t d = 0; d < dim; ++d) out[(size_t) b * dim + d] += c.raw[(size_t) (b * REF_R + i)][(size_t) d]; - for (auto& x : out) x /= (double) REF_R; - return out; -} - -/// `pooled_keys` + `dead_pooled_key`, in the readback order `indexer_scores` uses: (n_bid + 1, idx_dim). -std::vector ref_pooled(const RefCache& c, const std::vector& w_kn, float eps, int n_rot, - double theta, const Alt& o, - std::vector* terms_out = nullptr) { - const int64_t n_bid = c.size() / REF_R, dim = (int64_t) c.raw[0].size(); - std::vector pooled((size_t) (n_bid + 1) * dim, 0.0); - std::vector> rows(c.raw); - if (o.rope_raw) - for (size_t j = 0; j < rows.size(); ++j) ref_rope_neox(rows[j], c.pos[j], n_rot, theta); - - for (int64_t b = 0; b < n_bid; ++b) { - std::vector m((size_t) dim, 0.0); - if (o.pool_then_norm) { - for (int64_t i = 0; i < REF_R; ++i) - for (int64_t d = 0; d < dim; ++d) - m[(size_t) d] += rows[(size_t) (b * REF_R + i)][(size_t) d] / (double) REF_R; - ref_rms_norm(m, w_kn, eps); - } else { - for (int64_t i = 0; i < REF_R; ++i) { - std::vector one = rows[(size_t) (b * REF_R + i)]; - ref_rms_norm(one, w_kn, eps); - for (int64_t d = 0; d < dim; ++d) m[(size_t) d] += one[(size_t) d] / (double) REF_R; - } - } - std::vector terms; - ref_rope_neox(m, o.rotate_at_block_start ? c.pos[(size_t) (b * REF_R)] - : c.pos[(size_t) (b * REF_R + REF_R - 1)], - n_rot, theta, terms_out ? &terms : nullptr); - for (int64_t d = 0; d < dim; ++d) pooled[(size_t) b * dim + d] = m[(size_t) d]; - if (terms_out) { - if (b == 0) terms_out->assign((size_t) (n_bid + 1) * dim, 0.0); - for (int64_t d = 0; d < dim; ++d) (*terms_out)[(size_t) b * dim + d] = terms[(size_t) d]; - } - } - std::vector dead = rows[o.dead_from_first ? 0 : rows.size() - 1]; - ref_rms_norm(dead, w_kn, eps); - ref_rope_neox(dead, 0.0, n_rot, theta); // the identity, but computed the reference's way - for (int64_t d = 0; d < dim; ++d) pooled[(size_t) n_bid * dim + d] = dead[(size_t) d]; - return pooled; -} - -/// `ref/qsa.py::indexer_scores` - per CELL, after the `cell_block` mapping. -std::vector ref_indexer_scores(const std::vector& pooled, int64_t n_bid, - const std::vector& q_idx, int64_t idx_n_head, int64_t idx_dim, - const std::vector& bias, int64_t n_kv, const Alt& o) { - std::vector per_block((size_t) n_bid + 1, 0.0); - for (int64_t b = 0; b <= n_bid; ++b) { - double s = 0; - for (int64_t h = 0; h < idx_n_head; ++h) { - double dot = 0; - for (int64_t d = 0; d < idx_dim; ++d) - dot += pooled[(size_t) b * idx_dim + d] * q_idx[(size_t) h * idx_dim + d]; - if (!o.use_relu) s += dot; - else if (o.relu_per_head) s += dot > 0 ? dot : 0.0; - else s += dot; - } - if (o.use_relu && !o.relu_per_head) s = s > 0 ? s : 0.0; - if (o.use_bias && !bias.empty()) s += (double) bias[(size_t) b]; - if (b == n_bid && n_kv % REF_R != 0) s = (float) s + 1e9f; - per_block[(size_t) b] = s; - } - std::vector cell((size_t) n_kv, 0.0); - for (int64_t j = 0; j < n_kv; ++j) cell[(size_t) j] = per_block[(size_t) (j / REF_R < n_bid ? j / REF_R : n_bid)]; - return cell; -} - -/// `ref/qsa.py::select_cells`, spelled with a stable sort rather than the kernel's threshold search, so the -/// two are independent implementations of one rule: score DESCENDING, ties by ASCENDING index. -std::vector ref_select(const std::vector& scores, int64_t n_kv, int64_t top_k, bool dense) { - std::vector idx((size_t) n_kv); - for (int64_t j = 0; j < n_kv; ++j) idx[(size_t) j] = (int32_t) j; - if (dense) return idx; - const int64_t width = std::min(n_kv, top_k + REF_R - 1); - std::stable_sort(idx.begin(), idx.end(), [&](int32_t a, int32_t b) { - const double sa = scores[(size_t) a], sb = scores[(size_t) b]; - if (sa != sb) return sa > sb; - return a < b; - }); - idx.resize((size_t) width); - std::sort(idx.begin(), idx.end()); - return idx; -} - -/// `ref/qsa.py::qsa_attend` over an EXPLICIT selected set, reading K/V from whichever table the caller passes -/// so that one piece of code runs on the f64 keys and on the fp16 cache's exact f32 values. -std::vector ref_attend(const std::vector& q, int64_t n_head, int64_t n_head_kv, int64_t head_dim, - const std::vector& ids, const std::vector>& k, - const std::vector>& v, const Alt& o, - std::vector* weights_out) { - const double scale = o.apply_scale ? 1.0 / std::sqrt((double) head_dim) : 1.0; - std::vector out((size_t) n_head * head_dim, 0.0); - if (weights_out) weights_out->assign((size_t) n_head * ids.size(), 0.0); - for (int64_t h = 0; h < n_head; ++h) { - const int64_t kv = o.kv_divide ? h / (n_head / n_head_kv) : h % n_head_kv; - std::vector sc(ids.size()); - for (size_t j = 0; j < ids.size(); ++j) { - double dot = 0; - for (int64_t d = 0; d < head_dim; ++d) - dot += k[(size_t) ids[j]][(size_t) (kv * head_dim + d)] * q[(size_t) (h * head_dim + d)]; - sc[j] = dot * scale; - } - const double mx = *std::max_element(sc.begin(), sc.end()); - double sum = 0; - for (auto& s : sc) { s = std::exp(s - mx); sum += s; } - for (auto& s : sc) s /= sum; - if (weights_out) - for (size_t j = 0; j < ids.size(); ++j) (*weights_out)[(size_t) h * ids.size() + j] = sc[j]; - for (int64_t d = 0; d < head_dim; ++d) { - double acc = 0; - for (size_t j = 0; j < ids.size(); ++j) acc += sc[j] * v[(size_t) ids[j]][(size_t) (kv * head_dim + d)]; - out[(size_t) (h * head_dim + d)] = acc; - } - } - return out; -} - -/// `ref/model.py::_qsa`'s last two lines. -std::vector ref_gate(const std::vector& attn, const std::vector& q_full, int64_t n_head, - int64_t head_dim, const Alt& o) { - std::vector out((size_t) n_head * head_dim, 0.0); - for (int64_t h = 0; h < n_head; ++h) - for (int64_t d = 0; d < head_dim; ++d) { - const int64_t gi = o.gate_second_half ? h * 2 * head_dim + head_dim + d : h * 2 * head_dim + d; - const double g = q_full[(size_t) gi]; - const double s = o.gate_sigmoid ? 1.0 / (1.0 + std::exp(-g)) : g / (1.0 + std::exp(-g)); - out[(size_t) (h * head_dim + d)] = attn[(size_t) (h * head_dim + d)] * s; - } - return out; -} - -/// {f32 bits, the fp16 bits numpy produces for it} interleaved. Generated by -/// `scripts/_gen_f16_oracle.py` from `np.float16(np.float32(x))`: an oracle that shares no code with -/// f16_bits.hpp, which is the whole point of the table. -const uint32_t kOracle[] = { -#include "qsa_oracle_vectors.inc" -}; -constexpr int kOracleN = (int) (sizeof(kOracle) / sizeof(kOracle[0])) / 2; - -} // namespace - -int main(int argc, char** argv) { - std::setvbuf(stdout, nullptr, _IONBF, 0); // a crash must not swallow what was printed already - bool selftest = false, dense = false, bench = false; - for (int i = 1; i < argc; ++i) { - const std::string a = argv[i]; - if (a == "--selftest") selftest = true; - else if (a == "--qsa-dense") dense = true; - else if (a == "--bench") bench = true; - else { - std::fprintf(stderr, "usage: qsa_parity [--selftest] [--qsa-dense] [--bench]\n" - " --qsa-dense attend to EVERY cell instead of the indexer's selection\n" - " (P1.S4's isolation switch; the sparse selection is still run\n" - " and checked, against the reference's dense/sparse property)\n" - " --bench time the kernels at 32K of context\n"); - return 2; - } - } - - const strata::kernels::QsaShapes S = strata::kernels::qsa_real_shapes(); - const int64_t NH = S.n_head, NKV = S.n_head_kv, HD = S.head_dim, IDXN = S.idx_n_head, IDXD = S.idx_dim, - R = S.idx_block, TOPK = S.idx_top_k; - const int64_t MAXC = strata::kernels::kTopkMaxCells; - const float EPS = strata::kernels::qsa_rms_eps(); - const double THETA = strata::kernels::qsa_freq_base(); - std::mt19937 rng(20260916u); - std::normal_distribution gauss(0.0, 1.0); - auto rnd = [&](double s) { return (float) (gauss(rng) * s); }; - - std::printf("qsa_parity: n_head %lld n_head_kv %lld head_dim %lld indexer %lldx%lld r=%lld " - "top_k %lld page (from the shapes) %lld [%s]\n\n", - (long long) NH, (long long) NKV, (long long) HD, (long long) IDXN, (long long) IDXD, - (long long) R, (long long) TOPK, (long long) S.page_size, dense ? "DENSE" : "sparse"); - require("the fixture's r is the artifact's IDX_BLOCK", R == REF_R, "r = " + std::to_string(R)); - - // ================= 0. the fp16 converter, against numpy ================= - { - int mism = 0, subnormal = 0; - for (int i = 0; i < kOracleN; ++i) { - float f; - const uint32_t fb = kOracle[2 * i]; - std::memcpy(&f, &fb, 4); - const uint16_t want = (uint16_t) kOracle[2 * i + 1]; - const uint16_t got = f16_from_f32(f); - if (got != want) { - if (mism < 5) std::printf(" f32 0x%08X -> got 0x%04X, numpy says 0x%04X\n", fb, got, want); - ++mism; - } - if ((want & 0x7C00u) == 0u && (want & 0x3FFu) != 0u) ++subnormal; - } - require("f32->f16 matches numpy's float16 on every vector", mism == 0, - std::to_string(kOracleN) + " vectors, " + std::to_string(subnormal) + " subnormal"); - int bad_rev = 0; - for (int h = 0; h < 65536; ++h) { - const int ex = (h >> 10) & 0x1F, man = h & 0x3FF; - if (ex == 31) continue; // inf/NaN come from the vector table above - const double mag = ex == 0 ? (double) man * std::ldexp(1.0, -24) - : (double) (1024 + man) * std::ldexp(1.0, ex - 25); - const double want = (h & 0x8000) ? -mag : mag; - if ((double) f32_from_f16((uint16_t) h) != want) { - if (bad_rev < 5) std::printf(" f16 0x%04X -> %.9g, want %.9g\n", h, (double) f32_from_f16((uint16_t) h), want); - ++bad_rev; - } - } - require("f16->f32 is exact on all 65,536 bit patterns", bad_rev == 0, - std::to_string(bad_rev) + " wrong"); - } - - // ================= 1. kv_append: the paged pool, three page granules ================= - const int64_t TCELLS = 1100; // 275 indexer blocks, and 3 pages at page_size 512 - std::vector kcur_all((size_t) TCELLS * NKV * HD), vcur_all((size_t) TCELLS * NKV * HD); - for (auto& x : kcur_all) x = rnd(1.0); - for (auto& x : vcur_all) x = rnd(1.0); - // EVERY pointer this kernel set takes is a DEVICE pointer - the append sources, the indexer weights - // and the rope tables alike. The first draft passed `&kcur_all[...]`, `w_kn.data()` and - // `cos_tab.data()` straight through, and every kernel that dereferenced one took an illegal access. - Dev dkcur_all, dvcur_all; - dkcur_all.put(kcur_all); - dvcur_all.put(vcur_all); - - struct PageCase { - int64_t page_size = 0, n_pages = 0; - std::vector table; - }; - std::vector pages; - for (int64_t ps : {(int64_t) 1, (int64_t) 4, (int64_t) 512}) { - PageCase c; - c.page_size = ps; - c.n_pages = (TCELLS + ps - 1) / ps; - c.table.resize((size_t) c.n_pages); - for (int64_t i = 0; i < c.n_pages; ++i) c.table[(size_t) i] = (int32_t) (c.n_pages - 1 - i); // REVERSED - pages.push_back(std::move(c)); - } - const std::vector ids = {0, 1, 2, 3, 5, 8, 13, 21, 34, 39, 1099, 700}; - - for (PageCase& c : pages) { - // THE PAGE GRANULE IS A PROPERTY OF THE SHAPES, and the kernel takes it from there rather than from an - // argument. The first version of this fixture left it at 512 while the table described 1-cell pages, - // so the kernel indexed a 1100-page table as if it had 3 pages and ran off the pool - which is what an - // illegal memory access reported. A test that feeds one geometry and expects another is measuring - // itself; the fix is to build the shapes per case. - strata::kernels::QsaShapes Sc = S; - Sc.page_size = c.page_size; - const size_t pool_n = (size_t) c.n_pages * NKV * c.page_size * HD; - Dev dk(pool_n), dv(pool_n); - Dev dtab; - dtab.put(c.table); - for (int64_t t = 0; t < TCELLS; ++t) - strata::kernels::kv_append(dk.p, dv.p, dtab.p, t, dkcur_all.p + (size_t) t * NKV * HD, - dvcur_all.p + (size_t) t * NKV * HD, Sc, nullptr); - const std::vector hk = dk.get(pool_n), hv = dv.get(pool_n); - - int mism = 0, mism_linear = 0, mism_head_major = 0; - const int64_t rows_avail = (int64_t) (pool_n / (size_t) HD); - // A rival layout's address is HYPOTHETICAL: where it would put the value may be outside the pool, - // and reading there is a host access violation rather than a mismatch. Off the end counts as - // "the value is not where the rival would put it", which is the claim being tested. - auto elsewhere = [&](int64_t r) { return r < 0 || r >= rows_avail; }; - for (int64_t cell = 0; cell < TCELLS; ++cell) - for (int64_t h = 0; h < NKV; ++h) - for (int64_t d = 0; d < HD; ++d) { - const size_t src = (size_t) (cell * NKV + h) * HD + d; - const uint16_t wk = f16_from_f32(kcur_all[src]), wv = f16_from_f32(vcur_all[src]); - // the DECLARED layout: [page][kv_head][page_size][head_dim] - const int64_t row = ((int64_t) c.table[(size_t) (cell / c.page_size)] * NKV + h) * c.page_size + - (cell % c.page_size); - if (hk[(size_t) row * HD + d] != wk || hv[(size_t) row * HD + d] != wv) ++mism; - // rival (a): the page table ignored, i.e. written at the logical address - const int64_t rl = (cell * NKV + h) * c.page_size + (cell % c.page_size); - if (elsewhere(rl) || hk[(size_t) rl * HD + d] != wk) ++mism_linear; - // rival (b): cell-major inside the page instead of head-major - const int64_t rh = ((int64_t) c.table[(size_t) (cell / c.page_size)] * c.page_size + - (cell % c.page_size)) * NKV + h; - if (elsewhere(rh) || hk[(size_t) rh * HD + d] != wk) ++mism_head_major; - } - const double n_tot = (double) (TCELLS * NKV * HD); - require("kv_append at page_size " + std::to_string(c.page_size) + ": the pool is BIT-EXACT", - mism == 0, std::to_string(mism) + " of " + std::to_string((long long) n_tot) + " bits wrong"); - verdict(" the page table is observable at page_size " + std::to_string(c.page_size), - (double) mism_linear / n_tot > 0.5, - pct((double) mism_linear / n_tot) + " (linear vs declared)"); - // The head-major rival is IDENTICAL to the declared layout when page_size == 1 (both reduce to - // `cell * n_head_kv + h`), so the separation is only asserted where the layouts actually differ. - if (c.page_size >= 4) { - verdict(" head-major-in-page is observable at page_size " + std::to_string(c.page_size), - (double) mism_head_major / n_tot > 0.5, - pct((double) mism_head_major / n_tot) + " (cell-major vs head-major)"); - } - - Dev dids; - dids.put(ids); - const size_t scr_n = ids.size() * NKV * HD; - Dev dks(scr_n), dvs(scr_n); - strata::kernels::kv_gather(dk.p, dv.p, dtab.p, dids.p, (int64_t) ids.size(), Sc, dks.p, dvs.p, nullptr); - const std::vector gk = dks.get(scr_n), gv = dvs.get(scr_n); - int gm = 0; - for (size_t j = 0; j < ids.size(); ++j) - for (int64_t h = 0; h < NKV; ++h) - for (int64_t d = 0; d < HD; ++d) { - const size_t src = (size_t) (ids[j] * NKV + h) * HD + d; - if (gk[(size_t) (j * NKV + h) * HD + d] != f16_from_f32(kcur_all[src])) ++gm; - if (gv[(size_t) (j * NKV + h) * HD + d] != f16_from_f32(vcur_all[src])) ++gm; - } - require(" kv_gather is BIT-EXACT at page_size " + std::to_string(c.page_size), gm == 0, - std::to_string(gm) + " wrong bits"); - } - - // ================= 2. indexer_key_append ================= - const int64_t NT = 10; // 2 complete blocks + a 2-cell tail - // The cells sit at POSITIONS 100..109, not at 0..9: `QsaCache.pos` is what the reference rotates by, - // and a kernel that assumes position == cell index is wrong for any sequence that does not start at 0 - // (prefix reuse, phase 5). With base 100 the two readings are 514% apart, which is asserted below. - const int32_t POS_BASE = 100; - RefCache rc; - std::vector raw_flat; - for (int64_t t = 0; t < NT; ++t) { - std::vector kk((size_t) (NKV * HD)), vv((size_t) (NKV * HD)), rr((size_t) IDXD); - for (int64_t i = 0; i < NKV * HD; ++i) { kk[(size_t) i] = gauss(rng); vv[(size_t) i] = gauss(rng); } - // cell MAGNITUDES 1, 4, 16, 64 - for the same reason round 196 gave its residual streams different - // scales: four i.i.d. rows of normal noise have nearly the same norm by accident, so "pool then norm" - // and "norm then pool" would agree to within the noise and the fixture could not see its own trap. - for (int64_t d = 0; d < IDXD; ++d) rr[(size_t) d] = gauss(rng) * std::pow(4.0, (double) (t % 4)); - for (int64_t d = 0; d < IDXD; ++d) raw_flat.push_back((float) rr[(size_t) d]); - // The reference gets the f32 PROMOTION of what the device gets, not the f64 original. Feeding it - // the f64 values left a 6e-8 relative difference, which is invisible in a score but crosses an f32 - // rounding boundary in one value in four - and the spare key is asserted BIT-EXACT. - for (int64_t d = 0; d < IDXD; ++d) rr[(size_t) d] = (double) raw_flat[(size_t) t * IDXD + d]; - rc.append(kk, vv, rr, (double) (100 + t)); - } - std::vector w_kn((size_t) IDXD); - for (auto& x : w_kn) x = 1.0f + 0.1f * rnd(1.0); - std::vector cos_tab((size_t) (2000 * S.n_rot / 2)), sin_tab(cos_tab.size()); - strata::kernels::build_rope_table((int) S.n_rot, THETA, 2000, cos_tab.data(), sin_tab.data()); - Dev dw_kn, dcos, dsin; - dw_kn.put(w_kn); - dcos.put(cos_tab); - dsin.put(sin_tab); - - const int64_t n_bid = NT / R; - const size_t pooled_n = (size_t) (n_bid + 1) * IDXD; - Dev dpooled(pooled_n), ddead((size_t) IDXD), dtail((size_t) (R - 1) * IDXD); - Dev dblockpos(1); // the rotation position, which only the DEVICE may read - // The POSITION is a device value now, because a host scalar would be baked into a captured graph. One - // `cudaMemcpy` per cell here; the layer keeps this buffer and updates it per token. - Dev dpos(1); - { - strata::kernels::QsaIndexerBuffers bufs{dtail.p, ddead.p, dpooled.p, dblockpos.p}; - Dev draw((size_t) IDXD); - for (int64_t t = 0; t < NT; ++t) { // one cell at a time: the tail is a ring and the spare row MOVES - check(cudaMemcpy(draw.p, &raw_flat[(size_t) t * IDXD], (size_t) IDXD * 4, cudaMemcpyHostToDevice), - "raw"); - const int32_t tpos = (int32_t) t; - check(cudaMemcpy(dpos.p, &tpos, 4, cudaMemcpyHostToDevice), "pos"); - strata::kernels::indexer_key_append(draw.p, dpos.p, POS_BASE, dw_kn.p, EPS, bufs, S, dcos.p, dsin.p, - nullptr); - } - const std::vector got = dpooled.get(pooled_n), got_dead = ddead.get((size_t) IDXD); - std::vector terms; - const std::vector want = ref_pooled(rc, w_kn, EPS, (int) S.n_rot, THETA, Alt{}, &terms); - const std::vector want_raw = ref_pooled_raw(rc); - - // (a) the spare slot: BIT-EXACT, because rope at position 0 is the identity in both (cos = 1, sin = 0 - // exactly), so the residual the pooled rows carry from the f32 rope cannot appear here. - int dead_bad = 0; - for (int64_t d = 0; d < IDXD; ++d) - if (got_dead[(size_t) d] != (float) want[(size_t) n_bid * IDXD + d]) ++dead_bad; - require("the spare slot's key (rms_norm of cell 0) is BIT-EXACT", dead_bad == 0, - std::to_string(dead_bad) + " of " + std::to_string(IDXD) + " wrong"); - require("the spare slot is at row n_bid and nowhere else", n_bid == 2, - "10 cells / r=4 -> 2 complete blocks"); - - // (b) the pooled blocks against the reference - // THE DENOMINATOR IS THE ROPE'S TERMS, not the result: `a*cos - b*sin` cancels, and the kernel's - // rotation runs in f32 over an f32 table (6e-8 per term) while the reference's runs in f64. Dividing - // by the result reports the cancellation, which is what made this read 1.067e-06 against a 1e-6 bar. - double worst = 0; - for (int64_t b = 0; b < n_bid; ++b) - for (int64_t d = 0; d < IDXD; ++d) { - const double wv = want[(size_t) b * IDXD + d]; - const double tm = terms[(size_t) b * IDXD + d]; - worst = std::max(worst, rel_terms(wv, (double) got[(size_t) b * IDXD + d], tm)); - } - report("pooled block keys vs the reference", worst, "rel/|rope terms|"); - if (!(worst <= 1e-6)) { std::printf(" *** over 1e-6 ***\n"); ++g_bad; } - - // (c) THE INCOMPLETE TAIL IS NOT POOLED: the two tail cells take the SPARE slot's score, which is cell - // 0's key - not their own mean. A rival reading that pools them would still fill every row. - { - std::vector tm((size_t) IDXD, 0.0); - for (int64_t i = n_bid * R; i < NT; ++i) - for (int64_t d = 0; d < IDXD; ++d) tm[(size_t) d] += rc.raw[(size_t) i][(size_t) d] / 2.0; - ref_rms_norm(tm, w_kn, EPS); - double num = 0, den = 0; - for (int64_t d = 0; d < IDXD; ++d) { - num += std::fabs(tm[(size_t) d] - (double) got_dead[(size_t) d]); - den += std::fabs(tm[(size_t) d]); - } - verdict("the incomplete tail is NOT pooled into the spare slot", num / den > 0.5, pct(num / den)); - } - - auto sep = [&](const std::string& name, const Alt& a) { - const std::vector alt = ref_pooled(rc, w_kn, EPS, (int) S.n_rot, THETA, a); - double num = 0, den = 0; - // Rows 0..n_bid INCLUSIVE: the spare slot is row n_bid and three of the four rivals change - // nothing else, so leaving it out made "the spare key from the LAST raw key" separate 0.00%. - for (int64_t b = 0; b <= n_bid; ++b) - for (int64_t d = 0; d < IDXD; ++d) { - num += std::fabs(alt[(size_t) b * IDXD + d] - want[(size_t) b * IDXD + d]); - den += std::fabs(want[(size_t) b * IDXD + d]); - } - verdict(name, num / den > 0.05, pct(num / den)); - }; - Alt a1; a1.rotate_at_block_start = false; - sep("rotating at the block's LAST cell is observable", a1); - Alt a2; a2.pool_then_norm = false; - sep("norm-then-pool vs pool-then-norm is observable", a2); - Alt a3; a3.dead_from_first = false; - sep("the spare key from the LAST raw key is observable", a3); - Alt a4; a4.rope_raw = true; - sep("rotating the RAW indexer keys is observable", a4); - { // THE POSITION BASE. The same reference with the cells at 0..9 instead of 100..109 - i.e. - // what a kernel that equates a cell's position with its index would compute. - RefCache flat = rc; - for (int64_t j = 0; j < NT; ++j) flat.pos[(size_t) j] = (double) j; - const std::vector alt = ref_pooled(flat, w_kn, EPS, (int) S.n_rot, THETA, Alt{}); - double num = 0, den = 0; - for (int64_t b = 0; b <= n_bid; ++b) - for (int64_t d = 0; d < IDXD; ++d) { - num += std::fabs(alt[(size_t) b * IDXD + d] - want[(size_t) b * IDXD + d]); - den += std::fabs(want[(size_t) b * IDXD + d]); - } - verdict("the rotation's POSITION BASE (pos_base) is observable", num / den > 0.05, - pct(num / den)); - } - - // (d) THE TRAP THIS FIXTURE CANNOT SEE, measured and reported rather than hidden. `rms_norm` divides - // by sqrt(mean(x^2) + eps), so the 1/r in the mean cancels EXCEPT through eps: mean and sum differ - // by ~eps/(2*mean(x^2)) relative. `ref/qsa.py` L463-465 makes the same point about its own test. - { - std::vector psum = want_raw; - for (auto& x : psum) x *= (double) R; - std::vector nm = want_raw, ns = psum; - for (int64_t b = 0; b < n_bid; ++b) { - std::vector m(nm.begin() + (size_t) b * IDXD, nm.begin() + (size_t) (b + 1) * IDXD); - std::vector s(ns.begin() + (size_t) b * IDXD, ns.begin() + (size_t) (b + 1) * IDXD); - ref_rms_norm(m, w_kn, EPS); - ref_rms_norm(s, w_kn, EPS); - for (int64_t d = 0; d < IDXD; ++d) { - nm[(size_t) b * IDXD + d] = m[(size_t) d]; - ns[(size_t) b * IDXD + d] = s[(size_t) d]; - } - } - double num = 0, den = 0; - for (size_t i = 0; i < want_raw.size(); ++i) { - num += std::fabs(psum[i] - want_raw[i]); - den += std::fabs(want_raw[i]); - } - verdict("the 1/r divisor IS observable in the RAW pooled value", num / den > 0.5, - pct(num / den) + " (sum vs mean, before any norm)"); - std::printf(" %-48s %.3e <-- below EVERY score tolerance; the divisor cannot be\n", - "the same divisor AFTER the norm", rel_l1(ns, nm)); - std::printf(" %-48s %s\n", "", "checked downstream at all, which is why the raw value is the"); - std::printf(" %-48s %s\n", "", "only place the mean/sum question is answerable."); - } - } - - // ================= 3. qsa_index ================= - std::vector q_idx((size_t) (IDXN * IDXD)); - for (auto& x : q_idx) x = rnd(1.0); - // A bias of ~0.4 against scores of ~20 separates "applies the bias" from "drops it" by 3.4%, which - // is not a fixture that can see its own trap. This is a guard for the kernel's optional additional - // bias, separate from the mandatory incomplete-tail bias; it is sized to - // be comparable with the scores so that dropping it is material. - std::vector bias((size_t) (n_bid + 1)); - for (auto& x : bias) x = rnd(8.0f); - { - const std::vector got_pooled = dpooled.get(pooled_n); - const std::vector p64 = as_d(got_pooled); - const std::vector q_idx64 = as_d(q_idx); - const int64_t n_kv = NT; - Dev dp, dqi, dbias, dsc; - dp.put(got_pooled); - dqi.put(q_idx); - dbias.put(bias); - dsc.alloc((size_t) n_kv); - strata::kernels::qsa_index(dp.p, n_bid, dqi.p, dbias.p, S, n_kv, dsc.p, nullptr); - const std::vector got = dsc.get((size_t) n_kv); - const std::vector want = - ref_indexer_scores(p64, n_bid, q_idx64, IDXN, IDXD, bias, n_kv, Alt{}); - - // The score is a SUM of four relu'd dots plus the bias, so the denominator is the magnitude of the - // TERMS - |dot| bounds a relu'd dot from above and is what is used here. - double worst = 0; - for (int64_t j = 0; j < n_kv; ++j) { - const int64_t cb = std::min(j / R, n_bid); - double terms = std::fabs((double) bias[(size_t) cb]); - if (cb == n_bid && n_kv % R != 0) terms += 1e9; - for (int64_t h = 0; h < IDXN; ++h) { - double dot = 0; - for (int64_t d = 0; d < IDXD; ++d) dot += p64[(size_t) cb * IDXD + d] * q_idx64[(size_t) h * IDXD + d]; - terms += std::fabs(dot); - } - worst = std::max(worst, rel_terms(want[(size_t) j], (double) got[(size_t) j], terms)); - } - report("indexer cell scores vs the reference", worst, "rel/Sum|terms|"); - if (!(worst <= 1e-6)) { std::printf(" *** over 1e-6 ***\n"); ++g_bad; } - - require("cells of one block share its score (0..3)", - got[0] == got[1] && got[1] == got[2] && got[2] == got[3] && got[0] != got[4]); - require("cells 8,9 (the tail) take the SPARE slot's score, not block 1's", - got[8] == got[9] && got[9] != got[7], "got[8] == got[9] != got[7]"); - - auto sep_scores = [&](const std::string& name, const Alt& a) { - const std::vector alt = ref_indexer_scores(p64, n_bid, q_idx64, IDXN, IDXD, bias, n_kv, a); - double num = 0, den = 0; - // The mandatory tail bias must not swamp the score-arithmetic fixture. - for (int64_t j = 0; j < n_bid * R; ++j) { - num += std::fabs(alt[(size_t) j] - want[(size_t) j]); - den += std::fabs(want[(size_t) j]); - } - verdict(name, num / den > 0.05, pct(num / den)); - }; - Alt a5; a5.relu_per_head = false; - sep_scores("relu PER HEAD vs relu(sum of heads) is observable", a5); - Alt a6; a6.use_relu = false; - sep_scores("dropping the relu is observable", a6); - Alt a7; a7.use_bias = false; - sep_scores("dropping the per-block bias is observable", a7); - } - - // Causal decode's incomplete tail must survive even when its dot-product score - // ties every completed block. The oracle supplies +1e9 in set_input_qsa; - // without it, ascending-index top-k drops every tail after the sparse switch. - // Replay one captured graph across block/page boundaries to catch stale bias. - { - const int64_t max_n = 20480; - const int64_t max_blocks = max_n / R + 1; - const int64_t cap = strata::kernels::qsa_selection_width(max_n, S); - Dev pooled, query, scores((size_t) max_n); - Dev ids((size_t) cap), step(strata::kernels::kStepCount); - pooled.put(std::vector((size_t) max_blocks * IDXD, 0.0f)); - query.put(std::vector((size_t) IDXN * IDXD, 0.0f)); - - cudaStream_t stream; - cudaGraph_t graph; - cudaGraphExec_t exec; - check(cudaStreamCreate(&stream), "tail stream"); - check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "tail capture begin"); - strata::kernels::qsa_index_step(pooled.p, query.p, nullptr, S, step.p, max_blocks, scores.p, stream); - strata::kernels::topk_512_step(scores.p, S, cap, step.p, ids.p, stream); - check(cudaStreamEndCapture(stream, &graph), "tail capture end"); - check(cudaGraphInstantiate(&exec, graph, 0), "tail instantiate"); - - const std::vector counts = { - 1, 2, 3, 4, 511, 512, 513, 2046, 2047, 2048, 2049, 2050, 2051, - 2052, 2053, 2054, 2055, 2056, 2057, 2058, 2059, 2060, - 4095, 4096, 4097, 8191, 8192, 8193, 20477, 20478, 20479, 20480}; - for (const int64_t n : counts) { - const int64_t width = strata::kernels::qsa_selection_width(n, S); - const int64_t tail = n % R; - std::vector want; - for (int64_t j = 0; j < width - tail; ++j) want.push_back((int32_t) j); - for (int64_t j = n - tail; j < n; ++j) want.push_back((int32_t) j); - - strata::kernels::qsa_index(pooled.p, n / R, query.p, nullptr, S, n, scores.p, nullptr); - strata::kernels::topk_512(scores.p, n, S, cap, ids.p, nullptr); - require("tail static n=" + std::to_string(n), ids.get((size_t) width) == want); - - std::vector values(strata::kernels::kStepCount); - strata::kernels::qsa_step_fill(values.data(), n - 1, S); - step.put(values); - check(cudaGraphLaunch(exec, stream), "tail replay"); - check(cudaStreamSynchronize(stream), "tail replay sync"); - require("tail captured n=" + std::to_string(n), ids.get((size_t) width) == want); - const auto actual_scores = scores.get((size_t) n); - bool exact_scores = true; - for (int64_t j = 0; j < n; ++j) { - const float expected = j >= n - tail ? 1e9f : 0.0f; - exact_scores = exact_scores && actual_scores[(size_t) j] == expected; - } - require(" only incomplete cells receive the bias", exact_scores); - } - check(cudaGraphExecDestroy(exec), "tail exec destroy"); - check(cudaGraphDestroy(graph), "tail graph destroy"); - check(cudaStreamDestroy(stream), "tail stream destroy"); - } - - // ================= 4. topk_512, against an independent sort ================= - { - const int64_t CAP = strata::kernels::qsa_selection_width(MAXC, S); - Dev dsc; - Dev dids; - dsc.alloc((size_t) MAXC); - dids.alloc((size_t) CAP); - std::vector sc((size_t) MAXC); - - auto one = [&](const std::string& name, int64_t n_kv) { - dsc.put(std::vector(sc.begin(), sc.begin() + n_kv)); - strata::kernels::topk_512(dsc.p, n_kv, S, CAP, dids.p, nullptr); - const int64_t width = strata::kernels::qsa_selection_width(n_kv, S); - const std::vector g = dids.get((size_t) width); - const std::vector want = ref_select(as_d(std::vector(sc.begin(), sc.begin() + n_kv)), - n_kv, TOPK, false); - const bool ok = g == want; - require(name, ok, std::to_string(width) + " ids, width = min(n_kv, top_k + r - 1)"); - if (!ok) { - for (size_t i = 0; i < std::min(g.size(), want.size()); ++i) - if (g[i] != want[i]) { - std::printf(" first difference at %zu: got %d, want %d\n", i, g[i], want[i]); - break; - } - } - bool asc = true; - for (size_t i = 1; i < g.size(); ++i) if (g[i] <= g[i - 1]) asc = false; - require(" ...ascending and unique", asc); - return g; - }; - - for (auto& x : sc) x = rnd(1.0); - one("topk_512 n_kv = 1", 1); - one("topk_512 n_kv = 7 (random)", 7); - one("topk_512 n_kv = 2048 (the plan's threshold)", 2048); - one("topk_512 n_kv = 2051 (the reference's own bound)", 2051); - one("topk_512 n_kv = 2052 (two past the plan's number)", 2052); - one("topk_512 n_kv = 5000 (random)", 5000); - one("topk_512 n_kv = 32768 (= kTopkMaxCells)", MAXC); - - // ALL-EQUAL scores: every cell ties, so the answer must be 0..width-1 and any other tie rule shows up - // on the first element. ggml does not specify the rule; the reference and the kernel both say - // ascending index, and this is the case that distinguishes them. - std::fill(sc.begin(), sc.begin() + 2052, 0.25f); - one("topk_512 with 2052 EQUAL scores (every cell ties)", 2052); - - // a tie BLOCK straddling the cut: 100 cells share the cut score and only some of them fit - for (int64_t j = 0; j < 5000; ++j) sc[(size_t) j] = (float) (-(double) j); - for (int64_t j = 2051 - 50; j < 2051 + 50; ++j) sc[(size_t) j] = -1000.0f; - one("topk_512 with a 100-cell tie straddling the cut", 5000); - - // THE IDENTITY BELOW THE BOUND. `select_cells` returns `arange` whenever width == n_kv, which is what - // "selection skipped when context <= 2,048" means - and it holds to 2,051, not 2,048. - for (int64_t n : {(int64_t) 2048, (int64_t) 2051}) { - for (int64_t j = 0; j < n; ++j) sc[(size_t) j] = rnd(1.0); - const std::vector g = one(std::string("topk_512 n_kv = ") + std::to_string(n) + - " selects every cell (identity)", - n); - bool ident = (int64_t) g.size() == n; - for (int64_t j = 0; j < n && ident; ++j) if (g[(size_t) j] != j) ident = false; - require(" ...and it really is 0,1,2,...", ident); - } - { // one past the bound the identity must FAIL, or the two checks above prove nothing - for (int64_t j = 0; j < 2052; ++j) sc[(size_t) j] = rnd(1.0); - const std::vector g = one("topk_512 n_kv = 2052 is NOT the identity", 2052); - std::vector kept(2052, 0); - for (int32_t id : g) kept[(size_t) id] = 1; - int64_t missing = 0; - for (int64_t j = 0; j < 2052; ++j) if (!kept[(size_t) j]) ++missing; - int64_t argmin = 0; - for (int64_t j = 1; j < 2052; ++j) if (sc[(size_t) j] < sc[(size_t) argmin]) argmin = j; - require(" ...exactly one cell is dropped, and it is the smallest score", - missing == 1 && !kept[(size_t) argmin], std::to_string(missing) + " dropped"); - } - } - - // ================= 5. qsa_attend on the loud-cell fixture ================= - // `ref/qsa.py` PROPERTY 8's own numbers: a key with 100 in its first dim against zeros, a value of 10 - // against 1, and q[:,0] = 1. The logit gap is 100/sqrt(256) = 6.25, so the loud cell takes ~99% of its - // head's weight - and exactly zero when it is not in the selected set. - { - const int64_t N = 8; - std::vector> k2, v2; - std::vector k2f, v2f; - for (int64_t j = 0; j < N; ++j) { - std::vector kk((size_t) (NKV * HD), 0.0), vv((size_t) (NKV * HD), 0.0); - for (int64_t h = 0; h < NKV; ++h) vv[(size_t) (h * HD)] = 1.0; - kk[0] = j == N - 1 ? 100.0 : 0.0; - vv[0] = j == N - 1 ? 10.0 : 1.0; - for (int64_t i = 0; i < NKV * HD; ++i) { k2f.push_back((float) kk[(size_t) i]); v2f.push_back((float) vv[(size_t) i]); } - k2.push_back(kk); - v2.push_back(vv); - } - std::vector q((size_t) (NH * HD), 0.0); - for (int64_t h = 0; h < NH; ++h) q[(size_t) (h * HD)] = 1.0; - - Dev dq; - dq.put(as_f(q)); - const size_t scr = (size_t) N * NKV * HD; - std::vector kbits(scr), vbits(scr); - for (size_t i = 0; i < scr; ++i) { kbits[i] = f16_from_f32(k2f[i]); vbits[i] = f16_from_f32(v2f[i]); } - Dev dks(scr), dvs(scr); - dks.put(kbits); - dvs.put(vbits); - Dev dattn((size_t) NH * HD), dwt((size_t) NH * N); - - std::vector all(N), no_loud(N - 1); - for (int64_t j = 0; j < N; ++j) all[(size_t) j] = (int32_t) j; - for (int64_t j = 0; j < N - 1; ++j) no_loud[(size_t) j] = (int32_t) j; - - // the scratch is written directly here (no pool), so this section is about the attention alone - strata::kernels::qsa_attend(dq.p, dks.p, dvs.p, N, S, dattn.p, dwt.p, nullptr); - const std::vector out_all = as_d(dattn.get((size_t) NH * HD)); - strata::kernels::qsa_attend(dq.p, dks.p, dvs.p, N - 1, S, dattn.p, nullptr, nullptr); - const std::vector out_sel = as_d(dattn.get((size_t) NH * HD)); - const std::vector wts = as_d(dwt.get((size_t) NH * N)); - - verdict("with every cell selected the loud cell dominates its head 0", out_all[0] > 5.0, - "out[0][0] = " + std::to_string(out_all[0]).substr(0, 6)); - require("with the loud cell unselected it contributes EXACTLY nothing", - std::fabs(out_sel[0] - 1.0) < 1e-6, "out[0][0] = " + std::to_string(out_sel[0]).substr(0, 8)); - double worst_sum = 0; - for (int64_t h = 0; h < NH; ++h) { - double s = 0; - for (int64_t j = 0; j < N; ++j) s += wts[(size_t) (h * N + j)]; - worst_sum = std::max(worst_sum, std::fabs(s - 1.0)); - } - report("the returned weights sum to 1 per head", worst_sum, "max |1 - sum|"); - - auto sep_attend = [&](const std::string& name, const Alt& a) { - const std::vector alt = ref_attend(q, NH, NKV, HD, all, k2, v2, a, nullptr); - double num = 0, den = 0; - for (size_t i = 0; i < alt.size(); ++i) { - num += std::fabs(alt[i] - out_all[i]); - den += std::fabs(alt[i]); - } - verdict(name, num / den > 0.05, pct(num / den)); - }; - Alt a8; a8.kv_divide = false; - sep_attend("q % 2 vs q / 12 for the kv head is observable", a8); - // The scale trap is NOT asserted on this fixture: its softmax is saturated (the loud cell holds 99% - // of the weight, so removing a 16x logit scale moves it to 100% and the output by 1.09%). It is - // asserted on the random 2100-cell fixture below, where the logits are O(10) and the temperature - // actually matters. This is round 196's lesson about a fixture that cannot see its own trap. - std::printf(" %-48s %-6s %s\n", " (the scale trap is measured on the random fixture)", "--", - "this fixture's softmax is saturated"); - { // the mask: the same reference with and without the loud cell in the selected set - const std::vector with_loud = ref_attend(q, NH, NKV, HD, all, k2, v2, Alt{}, nullptr); - const std::vector without = ref_attend(q, NH, NKV, HD, no_loud, k2, v2, Alt{}, nullptr); - double num = 0, den = 0; - for (size_t i = 0; i < with_loud.size(); ++i) { - num += std::fabs(with_loud[i] - without[i]); - den += std::fabs(with_loud[i]); - } - verdict("attending to the unselected cell is observable", num / den > 0.05, pct(num / den)); - } - } - - // ================= 6. the whole layer at n_kv = 2100, so the selection is genuinely sparse ============= - int64_t width = 0; - { - const int64_t T = 2100; // > 2051, so `width` really truncates - width = strata::kernels::qsa_selection_width(T, S); - std::vector pk((size_t) T * NKV * HD), pv((size_t) T * NKV * HD), praw((size_t) T * IDXD); - std::vector> k16((size_t) T), v16((size_t) T); - RefCache pc; - std::vector q((size_t) NH * HD); - for (auto& x : q) x = rnd(1.0); - for (int64_t t = 0; t < T; ++t) { - std::vector kk((size_t) (NKV * HD)), vv((size_t) (NKV * HD)), rr((size_t) IDXD); - for (int64_t i = 0; i < NKV * HD; ++i) { - kk[(size_t) i] = gauss(rng); - vv[(size_t) i] = gauss(rng); - pk[(size_t) t * NKV * HD + i] = (float) kk[(size_t) i]; - pv[(size_t) t * NKV * HD + i] = (float) vv[(size_t) i]; - } - for (int64_t d = 0; d < IDXD; ++d) { - rr[(size_t) d] = gauss(rng); - praw[(size_t) t * IDXD + d] = (float) rr[(size_t) d]; - } - for (int64_t i = 0; i < NKV * HD; ++i) { - kk[(size_t) i] = (double) pk[(size_t) t * NKV * HD + i]; // the f32 the device got - vv[(size_t) i] = (double) pv[(size_t) t * NKV * HD + i]; - } - for (int64_t d = 0; d < IDXD; ++d) rr[(size_t) d] = (double) praw[(size_t) t * IDXD + d]; - pc.append(kk, vv, rr, (double) t); - k16[(size_t) t].resize((size_t) (NKV * HD)); - v16[(size_t) t].resize((size_t) (NKV * HD)); - for (int64_t i = 0; i < NKV * HD; ++i) { - k16[(size_t) t][(size_t) i] = (double) f32_from_f16(f16_from_f32(pk[(size_t) t * NKV * HD + i])); - v16[(size_t) t][(size_t) i] = (double) f32_from_f16(f16_from_f32(pv[(size_t) t * NKV * HD + i])); - } - } - const int64_t p_nbid = T / R; // 525 complete blocks; the spare key sits at row 525 - const int64_t page_size = 64, n_pages = (T + page_size - 1) / page_size; - strata::kernels::QsaShapes Sp = S; // the granule lives in the shapes: see section 1 - Sp.page_size = page_size; - std::vector table((size_t) n_pages); - for (int64_t i = 0; i < n_pages; ++i) table[(size_t) i] = (int32_t) (n_pages - 1 - i); // REVERSED - - Dev dtab; - dtab.put(table); - Dev dpk_all, dpv_all; - dpk_all.put(pk); - dpv_all.put(pv); - Dev dpk((size_t) n_pages * NKV * page_size * HD), dpv((size_t) n_pages * NKV * page_size * HD); - for (int64_t t = 0; t < T; ++t) - strata::kernels::kv_append(dpk.p, dpv.p, dtab.p, t, dpk_all.p + (size_t) t * NKV * HD, - dpv_all.p + (size_t) t * NKV * HD, Sp, nullptr); - - const size_t ppooled_n = (size_t) (p_nbid + 1) * IDXD; - Dev dpp((size_t) ppooled_n), dpdead((size_t) IDXD), dptail((size_t) (R - 1) * IDXD); - Dev dblockpos2(1); - Dev dpos2(1); - Dev draw((size_t) IDXD); - strata::kernels::QsaIndexerBuffers bufs{dptail.p, dpdead.p, dpp.p, dblockpos2.p}; - for (int64_t t = 0; t < T; ++t) { - check(cudaMemcpy(draw.p, &praw[(size_t) t * IDXD], (size_t) IDXD * 4, cudaMemcpyHostToDevice), "raw"); - const int32_t tpos = (int32_t) t; - check(cudaMemcpy(dpos2.p, &tpos, 4, cudaMemcpyHostToDevice), "pos2"); - strata::kernels::indexer_key_append(draw.p, dpos2.p, 0, dw_kn.p, EPS, bufs, S, dcos.p, dsin.p, - nullptr); - } - Dev dqidx, dsc; - dqidx.put(q_idx); - dsc.alloc((size_t) T); - strata::kernels::qsa_index(dpp.p, p_nbid, dqidx.p, nullptr, S, T, dsc.p, nullptr); - - Dev dsel((size_t) T); - strata::kernels::topk_512(dsc.p, T, S, T, dsel.p, nullptr); - const std::vector sel_sparse = dsel.get((size_t) width); - const std::vector pool32 = dpp.get(ppooled_n); - const std::vector pool64 = as_d(pool32); - const std::vector q_idx64 = as_d(q_idx); - const std::vector sc_want = - ref_indexer_scores(pool64, p_nbid, q_idx64, IDXN, IDXD, {}, T, Alt{}); - const std::vector sel_want = ref_select(sc_want, T, TOPK, false); - require("the selected set matches the reference (2100 cells, width 2051)", sel_sparse == sel_want, - std::to_string(width) + " ids"); - - // HOW CLOSE IS THE CUT? `indexer_ids` is an EXACT capture key, so a boundary gap of a few fp32 ulp - // would make it sensitive to the accumulation order. The gap is measured in ulp of the cut score. - { - std::vector issel((size_t) T, 0); - for (int32_t id : sel_sparse) issel[(size_t) id] = 1; - double lo = 1e300, hi = -1e300; - for (int32_t id : sel_sparse) lo = std::min(lo, sc_want[(size_t) id]); - for (int64_t j = 0; j < T; ++j) if (!issel[(size_t) j]) hi = std::max(hi, sc_want[(size_t) j]); - if (lo == hi) { - // The cut sits inside a group of cells that all score exactly the same - here 0.0, a relu - // signal with all four head dots negative - so nothing but the ascending-index rule decides - // which of them survive. A gap metric is undefined there; the tie is the finding. - int64_t tied_in = 0, tied_out = 0; - for (int32_t id : sel_sparse) if (sc_want[(size_t) id] == lo) ++tied_in; - for (int64_t j = 0; j < T; ++j) if (!issel[(size_t) j] && sc_want[(size_t) j] == lo) ++tied_out; - std::printf(" %-48s THE CUT IS A TIE at %.6f: %lld selected, %lld rejected\n", - "the cut", lo, (long long) tied_in, (long long) tied_out); - require(" ...and the kernel picks the same ones as the reference", sel_sparse == sel_want); - } else { - report("the selection boundary gap, in fp32 ulp of the cut", - (lo - hi) / (std::fabs(lo) * 1.2e-7), "gap/ulp"); - std::printf(" %-48s last selected %.6f, first rejected %.6f\n", "the cut", lo, hi); - } - } - - // the pipeline. `--qsa-dense` swaps the SELECTION for every cell and keeps everything else; the sparse - // selection above is still compared against the reference either way. - std::vector sel = sel_sparse; - if (dense) { - sel.resize((size_t) T); - for (int64_t j = 0; j < T; ++j) sel[(size_t) j] = (int32_t) j; - } - Dev dsel2; - dsel2.put(sel); - const int64_t nsel = (int64_t) sel.size(); - Dev dks((size_t) nsel * NKV * HD), dvs((size_t) nsel * NKV * HD); - strata::kernels::kv_gather(dpk.p, dpv.p, dtab.p, dsel2.p, nsel, Sp, dks.p, dvs.p, nullptr); - Dev dqq, dattn((size_t) NH * HD), dwt((size_t) NH * nsel); - dqq.put(q); - strata::kernels::qsa_attend(dqq.p, dks.p, dvs.p, nsel, S, dattn.p, dwt.p, nullptr); - const std::vector attn = as_d(dattn.get((size_t) NH * HD)); - const std::vector wts = as_d(dwt.get((size_t) NH * nsel)); - - const std::vector q64 = as_d(q); - const std::vector attn_f64 = ref_attend(q64, NH, NKV, HD, sel, pc.k, pc.v, Alt{}, nullptr); - const std::vector attn_f16 = ref_attend(q64, NH, NKV, HD, sel, k16, v16, Alt{}, nullptr); - double num = 0, den = 0; - for (size_t i = 0; i < attn.size(); ++i) { - num += std::fabs(attn[i] - attn_f16[i]); - den += std::fabs(attn_f16[i]); - } - report("qsa_attend vs the reference on the SAME fp16 cache", num / den, "rel"); - { // the SCALE trap, on data whose softmax is not saturated - Alt a; a.apply_scale = false; - const std::vector alt = ref_attend(q64, NH, NKV, HD, sel, k16, v16, a, nullptr); - double n2 = 0, d2 = 0; - for (size_t i = 0; i < alt.size(); ++i) { - n2 += std::fabs(alt[i] - attn_f16[i]); - d2 += std::fabs(attn_f16[i]); - } - verdict("omitting 1/sqrt(head_dim) is observable (random fixture)", n2 / d2 > 0.05, pct(n2 / d2)); - } - if (!(num / den <= 1e-5)) { std::printf(" *** over 1e-5 ***\n"); ++g_bad; } - const double fp16_cost = rel_l1(attn_f64, attn_f16); - report("the fp16 KV cache's OWN cost (f32 keys vs fp16 keys)", fp16_cost, "rel"); - if (!(fp16_cost <= 1e-3)) { - std::printf(" *** the phase's 1e-3 for FP16 paths is exceeded by the CACHE ***\n"); - ++g_bad; - } - { - std::vector w_ref; - ref_attend(q64, NH, NKV, HD, sel, k16, v16, Alt{}, &w_ref); - double wn = 0, wd = 0; - for (int64_t j = 0; j < nsel; ++j) { - wn += std::fabs(wts[(size_t) j] - w_ref[(size_t) j]); - wd += std::fabs(w_ref[(size_t) j]); - } - report("the returned weights vs the reference (head 0)", wn / wd, "rel"); - } - - // the gate - std::vector q_full((size_t) (NH * 2 * HD)); - for (auto& x : q_full) x = rnd(2.0); - Dev dqf, dattnf; - dqf.put(q_full); - dattnf.put(as_f(attn)); - Dev dgate((size_t) NH * HD); - strata::kernels::qsa_gate_apply(dattnf.p, dqf.p, S, dgate.p, nullptr); - const std::vector gate16 = dgate.get((size_t) NH * HD); - const std::vector qf64 = as_d(q_full); - const std::vector gwant = ref_gate(attn, qf64, NH, HD, Alt{}); - double gnum = 0, gden = 0; - int gbits = 0; - for (size_t i = 0; i < gwant.size(); ++i) { - gnum += std::fabs((double) f32_from_f16(gate16[i]) - gwant[i]); - gden += std::fabs(gwant[i]); - if (gate16[i] != f16_from_f32((float) gwant[i])) ++gbits; - } - report("qsa_gate_apply vs the double reference", gnum / gden, "rel (f16 out quant ~2.4e-4)"); - if (!(gnum / gden <= 1e-3)) { std::printf(" *** over 1e-3 ***\n"); ++g_bad; } - std::printf(" %-48s %d of %lld (CUDA's double exp vs libm's, in the last bits)\n", - "fp16 gate bits differing from the reference", gbits, (long long) gwant.size()); - - auto sep_gate = [&](const std::string& name, const Alt& a) { - const std::vector alt = ref_gate(attn, qf64, NH, HD, a); - double n2 = 0, d2 = 0; - for (size_t i = 0; i < alt.size(); ++i) { - n2 += std::fabs(alt[i] - gwant[i]); - d2 += std::fabs(gwant[i]); - } - verdict(name, n2 / d2 > 0.05, pct(n2 / d2)); - }; - Alt a10; a10.gate_second_half = false; - sep_gate("the gate from the FIRST half is observable", a10); - Alt a11; a11.gate_sigmoid = false; - sep_gate("silu instead of sigmoid on the QSA gate is observable", a11); - - // DENSE vs SPARSE. Below the bound the width IS n_kv, so the two paths must agree EXACTLY (P1.S4's - // isolation property, `ref/qsa.py` PROPERTY 9b); above it they must differ, or the switch is a no-op. - require("below the bound, dense and sparse are the SAME selection", - ref_select(sc_want, 2000, TOPK, false) == ref_select(sc_want, 2000, TOPK, true)); - { - // BOTH SIDES COMPUTED HERE, from their own id lists and independently of `--qsa-dense`. The first - // version compared against the pipeline's `attn`, which in dense mode IS the dense attention - so the - // switch silently turned the check into a comparison of a thing with itself and reported 0.00%. - const std::vector dense_all = ref_select(sc_want, T, TOPK, true); - auto attend_ids = [&](const std::vector& ids) { - Dev did; - did.put(ids); - Dev dk2((size_t) ids.size() * NKV * HD), dv2((size_t) ids.size() * NKV * HD); - strata::kernels::kv_gather(dpk.p, dpv.p, dtab.p, did.p, (int64_t) ids.size(), Sp, dk2.p, dv2.p, - nullptr); - Dev da((size_t) NH * HD); - strata::kernels::qsa_attend(dqq.p, dk2.p, dv2.p, (int64_t) ids.size(), S, da.p, nullptr, nullptr); - return as_d(da.get((size_t) NH * HD)); - }; - const std::vector dense_attn = attend_ids(dense_all); - const std::vector sparse_attn = attend_ids(sel_sparse); - double dn = 0, dd = 0; - for (size_t i = 0; i < sparse_attn.size(); ++i) { - dn += std::fabs(dense_attn[i] - sparse_attn[i]); - dd += std::fabs(sparse_attn[i]); - } - verdict("dense differs from sparse at n_kv = 2100 (> 2051)", dn / dd > 0.05, pct(dn / dd)); - } - } - - // ================= 7. the empty selection ================= - { - Dev dq((size_t) NH * HD), dattn((size_t) NH * HD); - dq.put(std::vector((size_t) NH * HD, 1.0f)); - dattn.put(std::vector((size_t) NH * HD, 7.0f)); - strata::kernels::qsa_attend(dq.p, nullptr, nullptr, 0, S, dattn.p, nullptr, nullptr); - const std::vector got = dattn.get((size_t) NH * HD); - bool allz = true; - for (float x : got) if (x != 0.0f) allz = false; - require("an EMPTY selection gives a zero attention, not a NaN", allz, "all 6144 elements zero"); - } - - // ================= 8. --bench: what one QSA layer costs at 32K of context ================= - if (bench) { - const int64_t T = MAXC; // 32,768 cells = 32K of context - const int64_t nbid = T / R; - const int64_t ps = S.page_size, n_pages = (T + ps - 1) / ps; - const int64_t w = strata::kernels::qsa_selection_width(T, S); - std::printf("\n --bench at n_kv = %lld, page_size %lld, selection width %lld\n", (long long) T, - (long long) ps, (long long) w); - std::vector table((size_t) n_pages); - for (int64_t i = 0; i < n_pages; ++i) table[(size_t) i] = (int32_t) i; - Dev dtab; - dtab.put(table); - Dev dpk((size_t) n_pages * NKV * ps * HD), dpv((size_t) n_pages * NKV * ps * HD); - std::vector kz((size_t) NKV * HD), vz((size_t) NKV * HD); - for (auto& x : kz) x = rnd(1.0); - for (auto& x : vz) x = rnd(1.0); - Dev dkz, dvz; - dkz.put(kz); - dvz.put(vz); - strata::kernels::kv_append(dpk.p, dpv.p, dtab.p, 0, dkz.p, dvz.p, S, nullptr); - - const size_t ppooled_n = (size_t) (nbid + 1) * IDXD; - Dev dpp((size_t) ppooled_n), dsc((size_t) T); - std::vector pz(ppooled_n), sz((size_t) T); - for (auto& x : pz) x = rnd(0.1f); - for (auto& x : sz) x = std::fabs(rnd(1.0f)); - dpp.put(pz); - dsc.put(sz); - Dev dqidx; - dqidx.put(q_idx); - Dev dsel((size_t) w); - Dev dks((size_t) w * NKV * HD), dvs((size_t) w * NKV * HD); - Dev dq((size_t) NH * HD), dattn((size_t) NH * HD), dwt((size_t) NH * w); - std::vector qv((size_t) NH * HD); - for (auto& x : qv) x = rnd(1.0); - dq.put(qv); - - auto timeit = [&](const std::string& name, int reps, const std::function& fn) { - cudaEvent_t a, b; - cudaEventCreate(&a); - cudaEventCreate(&b); - fn(); - cudaDeviceSynchronize(); - cudaEventRecord(a); - for (int i = 0; i < reps; ++i) fn(); - cudaEventRecord(b); - cudaEventSynchronize(b); - float ms = 0; - cudaEventElapsedTime(&ms, a, b); - std::printf(" %-48s %8.1f us\n", name.c_str(), ms * 1000.0f / (float) reps); - cudaEventDestroy(a); - cudaEventDestroy(b); - }; - const int reps = 20; - timeit("qsa_index (8193 pooled rows x 4 heads)", reps, - [&] { strata::kernels::qsa_index(dpp.p, nbid, dqidx.p, nullptr, S, T, dsc.p, nullptr); }); - timeit("topk_512 (32768 cells)", reps, - [&] { strata::kernels::topk_512(dsc.p, T, S, w, dsel.p, nullptr); }); - strata::kernels::topk_512(dsc.p, T, S, w, dsel.p, nullptr); - timeit("kv_gather (2051 ids through the page table)", reps, - [&] { strata::kernels::kv_gather(dpk.p, dpv.p, dtab.p, dsel.p, w, S, dks.p, dvs.p, nullptr); }); - timeit("qsa_attend (2051 selected, 24 heads)", reps, - [&] { strata::kernels::qsa_attend(dq.p, dks.p, dvs.p, w, S, dattn.p, dwt.p, nullptr); }); - timeit("kv_append (one cell, 2 heads x 256)", 200, - [&] { strata::kernels::kv_append(dpk.p, dpv.p, dtab.p, 0, dkz.p, dvz.p, S, nullptr); }); - timeit("ONE QSA LAYER (index+topk+gather+attend)", reps, [&] { - strata::kernels::qsa_index(dpp.p, nbid, dqidx.p, nullptr, S, T, dsc.p, nullptr); - strata::kernels::topk_512(dsc.p, T, S, w, dsel.p, nullptr); - strata::kernels::kv_gather(dpk.p, dpv.p, dtab.p, dsel.p, w, S, dks.p, dvs.p, nullptr); - strata::kernels::qsa_attend(dq.p, dks.p, dvs.p, w, S, dattn.p, dwt.p, nullptr); - }); - } - - // ================= 6. indexer_key_append IS CAPTURABLE ================= - // - // THE PROPERTY THE DEVICE-POSITION REFACTOR WAS FOR, TESTED DIRECTLY rather than argued. `indexer_key_append` - // took `int64_t pos` as a host scalar, which a CUDA graph bakes in at capture time - so a captured call - // would replay the first token's position forever: `slot = pos % r` never advances, no block completes, and - // the indexer keeps pooling cells 0-3 for the whole sequence. - // - // The test captures ONE call, then replays the SAME graph twice with `pos_dev` and `raw` changed between - // them, and requires the second replay to land in a DIFFERENT pooled row with the reference's value. If the - // position were still baked in, both replays would write row 0 and the pooled rows would be identical. - // - // That is the negative control built into the assertion: "row 1 is correct" alone could also pass for a - // graph that reread the position by accident, but "row 0 unchanged AND row 1 correct AND row 1 != row 0" - // cannot pass for a baked-in position. - { - std::printf("\n-- indexer_key_append under graph capture\n"); - const int R2 = 4; - const int64_t NCELL = 8; // two complete blocks of r=4 - const size_t IDXD2 = (size_t) IDXD; - std::vector raw2((size_t) NCELL * IDXD2); - for (size_t i = 0; i < raw2.size(); ++i) raw2[i] = (float) std::sin((double) i * 0.013) * 2.0f - 0.3f; - - const int64_t nb2 = NCELL / R2; - Dev pooled2((size_t) (nb2 + 2) * IDXD2), dead2(IDXD2), tail2((size_t) (R2 - 1) * IDXD2); - Dev bpos2(1), pos2(1); - Dev raw2d(IDXD2); - strata::kernels::QsaIndexerBuffers bufs2{tail2.p, dead2.p, pooled2.p, bpos2.p}; - - // capture ONE call, on its own stream - cudaStream_t cs = nullptr; - check(cudaStreamCreate(&cs), "cs"); - check(cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal), "begincap"); - strata::kernels::indexer_key_append(raw2d.p, pos2.p, POS_BASE, dw_kn.p, EPS, bufs2, S, dcos.p, dsin.p, - (void*) cs); - cudaGraph_t g2 = nullptr; - check(cudaStreamEndCapture(cs, &g2), "endcap"); - check(cudaStreamDestroy(cs), "csd"); - size_t nodes2 = 0; - check(cudaGraphGetNodes(g2, nullptr, &nodes2), "nodes"); - cudaGraphExec_t ex2 = nullptr; - check(cudaGraphInstantiate(&ex2, g2, 0), "inst"); - - // replay A: cells 0..3, which completes block 0 - for (int t = 0; t < 4; ++t) { - check(cudaMemcpy(raw2d.p, &raw2[(size_t) t * IDXD2], IDXD2 * 4, cudaMemcpyHostToDevice), "r2"); - const int32_t tp = t; - check(cudaMemcpy(pos2.p, &tp, 4, cudaMemcpyHostToDevice), "p2"); - check(cudaGraphLaunch(ex2, nullptr), "launchA"); - } - const std::vector afterA = pooled2.get((size_t) (nb2 + 2) * IDXD2); - - // replay B: cells 4..7 through the SAME graph, which completes block 1 - for (int t = 4; t < 8; ++t) { - check(cudaMemcpy(raw2d.p, &raw2[(size_t) t * IDXD2], IDXD2 * 4, cudaMemcpyHostToDevice), "r3"); - const int32_t tp = t; - check(cudaMemcpy(pos2.p, &tp, 4, cudaMemcpyHostToDevice), "p3"); - check(cudaGraphLaunch(ex2, nullptr), "launchB"); - } - check(cudaDeviceSynchronize(), "sync2"); - const std::vector afterB = pooled2.get((size_t) (nb2 + 2) * IDXD2); - - std::printf(" %-44s %zu nodes for one call\n", "the pooled kernel is capturable", nodes2); - - // row 0 must be UNTOUCHED by the second block's replays - int row0_same = 0; - for (size_t d = 0; d < IDXD2; ++d) - if (afterA[d] == afterB[d]) ++row0_same; - std::printf(" %-44s %d of %zu unchanged\n", "the first block's row survives replay B", row0_same, - IDXD2); - if (row0_same != (int) IDXD2) ++g_bad; - - // row 1 must now be FILLED by the captured graph - the whole point - int row1_nonzero = 0; - for (size_t d = 0; d < IDXD2; ++d) - if (afterB[IDXD2 + d] != 0.0f) ++row1_nonzero; - std::printf(" %-44s %d of %zu non-zero\n", "the SECOND block's row arrives through the same graph", - row1_nonzero, IDXD2); - if (row1_nonzero != (int) IDXD2) ++g_bad; - - // and the two rows must DIFFER, which a baked-in position cannot produce - int rows_differ = 0; - for (size_t d = 0; d < IDXD2; ++d) - if (afterB[d] != afterB[IDXD2 + d]) ++rows_differ; - std::printf(" %-44s %d of %zu differ\n", "the two pooled rows are different keys", rows_differ, - IDXD2); - // A baked-in position would have written row 0 a second time and left row 1 at zero, so these two - // assertions together are the negative control for the refactor. - if (rows_differ != (int) IDXD2) ++g_bad; - - check(cudaGraphExecDestroy(ex2), "exd"); - check(cudaGraphDestroy(g2), "gd"); - } - - // ================= the NATIVE indexer's batched append vs the sequential one ================= - // The prefill path appends a chunk in one native_qsa_indexer_append_batch call, the decode path appends - // token by token - and one cache must never be able to tell which path filled it (rope_scaling.hpp's - // one-rotation rule). So the batch's whole end state must be BIT-IDENTICAL to the sequential appends', - // under all three scaling configs: none (today's rotation), linear 2 (pure angle shrink, no correction) - // and yarn 2 (corr-dims ramp and the mscale magnitude) - both kernels must take the same RopeScaling. - // "Bit-identical" is asserted on the bit representations (memcmp of the state words): float != would - // pass a NaN-payload or -0.0 flip that the claim does not cover. Eight cells: exactly two completed - // blocks, so the paths' end states agree on block_pos too (a mid-block chunk end leaves the sequential - // path pointing at the open block's base and the batch at the last completed one's - upstream C-2's own - // semantics, the same for every scaling; see native_qsa_indexer.hpp's block_pos contract). - { - std::printf("\n-- the native indexer's batched append vs the sequential one\n"); - const int64_t NB = 8; // exactly two complete blocks of r=4 - const int32_t BASE = 100; // positions 100..107, not cell indices 0..7 - const int64_t MC = 1024; // the capacity both sides validate against - using RST = strata::kernels::RopeScalingType; - struct Variant { const char* name; RST type; double factor; double ext; }; - const Variant variants[] = {{"none", RST::None, 1.0, 0.0}, - {"linear 2", RST::Linear, 2.0, 0.0}, - {"yarn 2", RST::YaRN, 2.0, 1.0}}; - std::vector raws((size_t) NB * IDXD); - for (int64_t t = 0; t < NB; ++t) - for (int64_t d = 0; d < IDXD; ++d) - raws[(size_t) t * IDXD + d] = (float) (gauss(rng) * std::pow(4.0, (double) (t % 4))); - cudaStream_t cs = nullptr; - check(cudaStreamCreate(&cs), "cs"); - std::vector none_pooled; - for (const Variant& var : variants) { - strata::kernels::RopeScaling sc; - sc.type = var.type; - sc.factor = var.factor; - sc.ext_factor = var.ext; - const size_t prows = (size_t) (MC / R + 1) * IDXD, trows = (size_t) (R - 1) * IDXD; - Dev pooledA(prows), deadA(IDXD), tailA(trows), pooledB(prows), deadB(IDXD), tailB(trows); - Dev bposA(1), bposB(1), dpos(1); - for (Dev* dp : {&pooledA, &deadA, &tailA, &pooledB, &deadB, &tailB}) - check(cudaMemset(dp->p, 0, dp == &pooledA || dp == &pooledB ? prows * 4 - : dp == &deadA || dp == &deadB ? IDXD * 4 : trows * 4), "zero"); - check(cudaMemset(bposA.p, 0, 4), "zero"); check(cudaMemset(bposB.p, 0, 4), "zero"); - Dev draw((size_t) IDXD), drawAll; - drawAll.put(raws); - strata::kernels::QsaIndexerBuffers bufsA{tailA.p, deadA.p, pooledA.p, bposA.p}; - strata::kernels::QsaIndexerBuffers bufsB{tailB.p, deadB.p, pooledB.p, bposB.p}; - for (int64_t t = 0; t < NB; ++t) { // the sequential side: one cell, its device position - check(cudaMemcpy(draw.p, &raws[(size_t) t * IDXD], (size_t) IDXD * 4, cudaMemcpyHostToDevice), "raw"); - const int32_t tp = (int32_t) t; - check(cudaMemcpy(dpos.p, &tp, 4, cudaMemcpyHostToDevice), "pos"); - strata::kernels::native_qsa_indexer_append(draw.p, dpos.p, BASE, dw_kn.p, EPS, bufsA, S, MC, sc, cs); - } - strata::kernels::native_qsa_indexer_append_batch(drawAll.p, NB, 0, BASE, dw_kn.p, EPS, bufsB, S, MC, sc, cs); - check(cudaStreamSynchronize(cs), "sync"); - const std::vector pa = pooledA.get(prows), pb = pooledB.get(prows); - const std::vector da = deadA.get((size_t) IDXD), db = deadB.get((size_t) IDXD); - const std::vector ta = tailA.get(trows), tbb = tailB.get(trows); - const std::vector ba = bposA.get(1), bb = bposB.get(1); - long long bad = 0; - for (size_t i = 0; i < pa.size(); ++i) bad += std::memcmp(&pa[i], &pb[i], 4) != 0; - for (size_t i = 0; i < da.size(); ++i) bad += std::memcmp(&da[i], &db[i], 4) != 0; - for (size_t i = 0; i < ta.size(); ++i) bad += std::memcmp(&ta[i], &tbb[i], 4) != 0; - bad += std::memcmp(&ba[0], &bb[0], 4) != 0; - std::printf(" %-44s %s (%lld of %zu state words differ)\n", - (std::string("batch vs sequential, ") + var.name).c_str(), - bad ? "*** WRONG ***" : "bit-identical", bad, pa.size() + da.size() + ta.size() + 1); - if (bad) ++g_bad; - if (var.type == RST::None) none_pooled = pa; - else { - int moved = 0; - for (size_t i = 0; i < pa.size(); ++i) moved += std::memcmp(&pa[i], &none_pooled[i], 4) != 0; - std::printf(" %-44s %d of %zu pooled words differ from the none baseline\n", - (std::string("the scaling is visible, ") + var.name).c_str(), moved, pa.size()); - if (!moved) { std::printf(" *** the batched append ignored its scaling ***\n"); ++g_bad; } - } - } - check(cudaStreamDestroy(cs), "csd"); - } - - // ================= the spare (position 0) under rope scaling: the table indexer vs the native one ========= - // The spare key (`dead`, and `pooled[0]` until the first block completes) rotates at angle 0. Its sine is - // 0 in every scaling, so the rotation is `v * cos_tab[0][pair]`: exactly `v` unscaled (row 0 is (1, 0), the - // bit-exact value section 2 asserts), `v * mscale` under YaRN - the magnitude every other pooled row and - // the native kernel's spare carry. The table kernel used to skip the rotation at position 0, which left - // the spare the one unscaled key of a scaled cache. Asserted per variant: the table spare is BIT-EXACTLY - // the unscaled spare times row 0 on the rotated dims and the unscaled spare past them; `pooled[0]` equals - // `dead`; the native spare carries the same factor (to f32 rounding: its mscale is formed in float); and - // under YaRN the factor is observable (row 0 is not 1). - { - std::printf("\n-- the spare key (position 0) under rope scaling: table indexer vs native indexer\n"); - using RST = strata::kernels::RopeScalingType; - struct Variant { const char* name; RST type; double factor; double ext; }; - const Variant variants[] = {{"none", RST::None, 1.0, 0.0}, - {"linear 2", RST::Linear, 2.0, 0.0}, - {"yarn 2", RST::YaRN, 2.0, 1.0}}; - const int64_t MC = 64, HALF = S.n_rot / 2, NROT = S.n_rot; - std::vector raw0((size_t) IDXD); - for (int64_t d = 0; d < IDXD; ++d) raw0[(size_t) d] = rnd(3.0); - Dev draw0; - draw0.put(raw0); - Dev dpos0(1); - const int32_t zero = 0; - check(cudaMemcpy(dpos0.p, &zero, 4, cudaMemcpyHostToDevice), "pos0"); - cudaStream_t cs = nullptr; - check(cudaStreamCreate(&cs), "cs"); - const size_t prows = (size_t) (MC / R + 1) * IDXD, trows = (size_t) (R - 1) * IDXD; - // one cell at position 0 through either kernel; returns (dead, pooled[0]) - auto spare = [&](bool native, const strata::kernels::RopeScaling& sc, std::vector& dead, - std::vector& pooled0) { - Dev pooled(prows), dd((size_t) IDXD), tail(trows); - Dev bpos(1); - check(cudaMemset(pooled.p, 0, prows * 4), "zero"); - check(cudaMemset(dd.p, 0, (size_t) IDXD * 4), "zero"); - check(cudaMemset(tail.p, 0, trows * 4), "zero"); - check(cudaMemset(bpos.p, 0, 4), "zero"); - strata::kernels::QsaIndexerBuffers bufs{tail.p, dd.p, pooled.p, bpos.p}; - if (native) { - strata::kernels::native_qsa_indexer_append(draw0.p, dpos0.p, 0, dw_kn.p, EPS, bufs, S, MC, sc, cs); - } else { - std::vector tc((size_t) (MC * HALF)), ts(tc.size()); - strata::kernels::build_rope_table((int) NROT, sc, (int) MC, tc.data(), ts.data()); - Dev dc, dsn; - dc.put(tc); - dsn.put(ts); - strata::kernels::indexer_key_append(draw0.p, dpos0.p, 0, dw_kn.p, EPS, bufs, S, dc.p, dsn.p, cs); - } - check(cudaStreamSynchronize(cs), "sync"); - dead = dd.get((size_t) IDXD); - pooled0 = pooled.get((size_t) IDXD); - }; - std::vector t_none, t_none_p, n_none, n_none_p; - for (const Variant& var : variants) { - strata::kernels::RopeScaling sc; - sc.type = var.type; - sc.factor = var.factor; - sc.ext_factor = var.ext; - std::vector row0c((size_t) (MC * HALF)), row0s(row0c.size()); - strata::kernels::build_rope_table((int) NROT, sc, (int) MC, row0c.data(), row0s.data()); - std::vector td, tp, nd, np; - spare(false, sc, td, tp); - spare(true, sc, nd, np); - if (var.type == RST::None) { t_none = td; t_none_p = tp; n_none = nd; n_none_p = np; } - long long tbad = 0, pbad = 0, sin_bad = 0; - double nworst = 0; - for (int64_t i = 0; i < HALF; ++i) sin_bad += row0s[(size_t) i] != 0.0f; - for (int64_t d = 0; d < IDXD; ++d) { - const float c0 = d < NROT ? row0c[(size_t) (d % HALF)] : 1.0f; - const float want = d < NROT ? t_none[(size_t) d] * c0 : t_none[(size_t) d]; - tbad += std::memcmp(&td[(size_t) d], &want, 4) != 0; - pbad += std::memcmp(&tp[(size_t) d], &td[(size_t) d], 4) != 0; - const double nwant = (double) n_none[(size_t) d] * (double) c0; - const double den = std::max(std::fabs(nwant), 1e-6); - nworst = std::max(nworst, std::fabs((double) nd[(size_t) d] - nwant) / den); - } - require(std::string(" ") + var.name + ": row 0 of the table is (c, 0)", sin_bad == 0, - std::to_string(sin_bad) + " nonzero sines"); - require(std::string(" ") + var.name + ": the table spare is the unscaled spare times row 0, BIT-EXACT", - tbad == 0, std::to_string(tbad) + " of " + std::to_string(IDXD) + " wrong"); - require(std::string(" ") + var.name + ": the table's pooled[0] is its spare", pbad == 0, - std::to_string(pbad) + " wrong"); - require(std::string(" ") + var.name + ": the native spare carries the same row-0 factor", nworst <= 4e-7, - "worst relative " + std::to_string(nworst)); - if (var.type == RST::YaRN) { - int moved = 0; - for (int64_t d = 0; d < NROT; ++d) moved += std::memcmp(&td[(size_t) d], &t_none[(size_t) d], 4) != 0; - require(" yarn 2: the magnitude correction is observable on the table spare", - row0c[0] != 1.0f && moved > NROT / 2, - "row0 cos " + std::to_string(row0c[0]) + ", " + std::to_string(moved) + " dims moved"); - } - } - check(cudaStreamDestroy(cs), "csd"); - } - - std::printf("\nqsa: %d failures\n", g_bad); - if (g_bad) return 1; - if (selftest) std::printf("qsa_parity OK\n"); - return 0; -} diff --git a/src/kernels/qsa_prompt_attn_parity.cpp b/src/kernels/qsa_prompt_attn_parity.cpp deleted file mode 100644 index 4a0921d..0000000 --- a/src/kernels/qsa_prompt_attn_parity.cpp +++ /dev/null @@ -1,274 +0,0 @@ -// src/kernels/qsa_prompt_attn_parity.cpp - perf-review D-1: the tensor-core prompt attention (qsa_prompt_attn.hpp) -// against the FP32 kernel it replaces (`qsa_decode_attn_batch`) and an FP64 host reference (GPU, synthetic, no model). -// -// Int8, FP16 and Q4_0 pools with random codes, scales and queries; selections shaped like the prompt path's (the 2,051 -// widest, a recent window plus older cells that drift slowly from one query to the next, so neighbours share most -// of them as they do in a real prompt; short contexts take every cell). Checks: -// 1. against FP64, the new kernel's error is no larger than a small multiple of the old kernel's (both FP32 math); -// 2. the new and old outputs agree to a relative 1e-4 of the output scale; -// then times both over a prompt chunk (the old one in batches of 32, as prefill.cpp calls it). -// HIP builds (S6): the same checks for the RDNA4 matrix-core kernel (STRATA_HIP_WMMA), skipped (77) off gfx12. -// Usage: qsa_prompt_attn_parity [context=32768] [queries=2048] [reps=5] -#include "strata/kernels/qsa.hpp" -#include "strata/kernels/qsa_decode_attn.hpp" -#include "strata/kernels/qsa_prompt_attn.hpp" -#include "strata/kernels/kv_q4.hpp" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -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(2); } -} -template T* up(const std::vector& h) { - T* d = nullptr; - ck(cudaMalloc(&d, h.size() * sizeof(T) + 64), "malloc"); - ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload"); - return d; -} -float h2f(uint16_t b) { __half h; *reinterpret_cast(&h) = b; return __half2float(h); } -uint16_t f2h(float f) { __half h = __float2half(f); return *reinterpret_cast(&h); } - -int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16, 2 q4_0 -#if !defined(__HIPCC__) && !defined(STRATA_USE_HIP) - if (fmt == 2) { // mode 4 (Q4_0 KV) runs on sm_80 and newer only: below that the dispatcher keeps the old kernel - int dev = 0, major = 0; - ck(cudaGetDevice(&dev), "device"); - ck(cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev), "cc"); - if (major < 8) { - std::printf("SKIP q4_0 ctx %lld: the tensor-core kernel takes Q4_0 KV on sm_80+ only (this device: sm_%d)\n", - (long long) ctx, major); - return 0; - } - } -#endif - const k::QsaShapes s = k::qsa_real_shapes(); - const int64_t HD = s.head_dim, NKV = s.n_head_kv, NH = s.n_head, PS = s.page_size; - const int64_t pages = (ctx + PS - 1) / PS, rows = pages * NKV * PS; - std::mt19937 rng(1234 + fmt); - std::normal_distribution nd(0.f, 1.f); - std::uniform_int_distribution code(-127, 127); - std::uniform_real_distribution sc(0.005f, 0.03f); - // pools; page table a shuffled permutation (the readers must follow it) - std::vector kq, vq; - std::vector ks, vs, kh, vh; - std::vector k4, v4; // q4_0: 8 blocks of {fp16 d, 16 code bytes} per row (kv_q4.hpp) - constexpr int64_t B4 = 18, ROW4 = 8 * B4; - if (fmt == 2) { - std::uniform_int_distribution byte(0, 255); - // the scales as a q4_0 pool holds them: signed (ggml's d = max / -8) and spread over two decades, so a chunk's - // cells mix signs and magnitudes (a positive-only bound on them overflowed FP16 on real K/V) - std::uniform_real_distribution lg(std::log(0.01f), std::log(1.0f)); - auto sc4 = [&](std::mt19937& r) { return std::exp(lg(r)) * (byte(r) & 1 ? -1.0f : 1.0f); }; - k4.resize(rows * ROW4); v4.resize(rows * ROW4); - for (auto* pool : {&k4, &v4}) - for (int64_t b = 0; b < rows * 8; ++b) { - const uint16_t d = f2h(sc4(rng)); - std::memcpy(pool->data() + b * B4, &d, 2); - for (int j = 0; j < 16; ++j) (*pool)[b * B4 + 2 + j] = (uint8_t) byte(rng); - } - } else if (fmt == 1) { - kq.resize(rows * HD); vq.resize(rows * HD); ks.resize(rows * 4); vs.resize(rows * 4); - for (auto& x : kq) x = (int8_t) code(rng); - for (auto& x : vq) x = (int8_t) code(rng); - for (auto& x : ks) x = f2h(sc(rng)); - for (auto& x : vs) x = f2h(sc(rng)); - } else { - kh.resize(rows * HD); vh.resize(rows * HD); - for (auto& x : kh) x = f2h(nd(rng) * 1.5f); - for (auto& x : vh) x = f2h(nd(rng)); - } - std::vector table(pages); - for (int64_t i = 0; i < pages; ++i) table[i] = (int32_t) i; - std::shuffle(table.begin(), table.end(), rng); - // queries at positions ctx - nq .. ctx - 1 - const int64_t cap = k::qsa_selection_width(ctx, s); - std::vector ids((size_t) (nq * cap), 0), steps((size_t) (nq * k::kStepCount), 0); - std::vector q((size_t) (nq * NH * HD)); - for (auto& x : q) x = nd(rng) * 2.0f; - std::vector old_cells; - for (int64_t i = 0; i < nq; ++i) { - const int64_t pos = ctx - nq + i, nkv = pos + 1; - const int64_t w = k::qsa_selection_width(nkv, s); - int32_t* sel = ids.data() + i * cap; - steps[i * k::kStepCount + k::kStepWidth] = (int32_t) w; - if (w == nkv) { - for (int64_t c = 0; c < w; ++c) sel[c] = (int32_t) c; - continue; - } - const int64_t recent = 512, older = w - recent; - if ((int64_t) old_cells.size() != older) { // the older cells: a set that drifts ~3% per query - std::vector all((size_t) (nkv - recent)); - for (int64_t c = 0; c < nkv - recent; ++c) all[c] = (int32_t) c; - std::shuffle(all.begin(), all.end(), rng); - old_cells.assign(all.begin(), all.begin() + older); - } else { - std::uniform_int_distribution pick(0, older - 1), any(0, nkv - recent - 1); - for (int r = 0; r < older / 32; ++r) { - const int32_t c = (int32_t) any(rng); - if (std::find(old_cells.begin(), old_cells.end(), c) == old_cells.end()) old_cells[pick(rng)] = c; - } - } - std::vector v(old_cells); - for (int64_t c = nkv - recent; c < nkv; ++c) v.push_back((int32_t) c); - std::sort(v.begin(), v.end()); - std::copy(v.begin(), v.end(), sel); - } - k::QsaAttnPools pl; - if (fmt == 2) { pl.k_q4 = up(k4); pl.v_q4 = up(v4); } - else if (fmt == 1) { pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs); } - else { pl.k_pool = up(kh); pl.v_pool = up(vh); } - // a q4_0 value: block d / 32 of the row, element j = d % 32 in the low nibble of byte j (j < 16), else the high - // nibble of byte j - 16, minus 8, times the block's scale - auto q4v = [&](const std::vector& pool, int64_t row, int64_t d) { - const uint8_t* blk = pool.data() + row * ROW4 + (d / 32) * B4; - uint16_t sc; - std::memcpy(&sc, blk, 2); - const int j = (int) (d % 32); - const int code = j < 16 ? (blk[2 + j] & 0x0F) : (blk[2 + j - 16] >> 4); - return (double) (code - 8) * h2f(sc); - }; - pl.page_table = up(table); - const int32_t* d_ids = up(ids); - const int32_t* d_steps = up(steps); - const float* d_q = up(q); - float *d_old = nullptr, *d_new = nullptr, *scratch = nullptr; - const int64_t batch = 32; - ck(cudaMalloc(&d_old, nq * NH * HD * 4), "malloc"); - ck(cudaMalloc(&d_new, nq * NH * HD * 4), "malloc"); - ck(cudaMalloc(&scratch, batch * k::qsa_decode_attn_scratch_floats(cap, s) * 4), "malloc"); - auto old_run = [&]() { - for (int64_t t0 = 0; t0 < nq; t0 += batch) - k::qsa_decode_attn_batch(d_q + t0 * NH * HD, pl, d_ids + t0 * cap, d_steps + t0 * k::kStepCount, cap, s, - scratch, d_old + t0 * NH * HD, std::min(batch, nq - t0), nullptr); - }; - auto new_run = [&]() { - if (!k::qsa_prompt_attn_batch(d_q, pl, d_ids, d_steps, cap, s, d_new, nq, nullptr)) { - std::fprintf(stderr, "qsa_prompt_attn_batch refused the pools\n"); - std::exit(2); - } - }; - old_run(); - new_run(); - ck(cudaDeviceSynchronize(), "run"); - std::vector o((size_t) (nq * NH * HD)), nw(o.size()); - ck(cudaMemcpy(o.data(), d_old, o.size() * 4, cudaMemcpyDeviceToHost), "down"); - ck(cudaMemcpy(nw.data(), d_new, nw.size() * 4, cudaMemcpyDeviceToHost), "down"); - // 1. FP64 reference on a sample of queries - double err_old = 0, err_new = 0, ref_scale = 0; - for (int64_t i = 0; i < nq; i += std::max(1, nq / 16)) { - const int64_t w = steps[i * k::kStepCount + k::kStepWidth]; - const int32_t* sel = ids.data() + i * cap; - for (int64_t h = 0; h < NH; ++h) { - const int64_t kvh = h / (NH / NKV); - std::vector sco((size_t) w); - double mx = -1e300; - for (int64_t c = 0; c < w; ++c) { - const int64_t cell = sel[c], row = ((int64_t) table[cell / PS] * NKV + kvh) * PS + cell % PS; - double a = 0; - for (int64_t d = 0; d < HD; ++d) { - const double kv = fmt == 2 ? q4v(k4, row, d) - : fmt == 1 ? (double) kq[row * HD + d] * h2f(ks[row * 4 + d / 64]) : h2f(kh[row * HD + d]); - a += (double) q[(i * NH + h) * HD + d] * kv; - } - sco[c] = a / 16.0; - mx = std::max(mx, sco[c]); - } - double l = 0; - for (auto& x : sco) { x = std::exp(x - mx); l += x; } - for (int64_t d = 0; d < HD; ++d) { - double a = 0; - for (int64_t c = 0; c < w; ++c) { - const int64_t cell = sel[c], row = ((int64_t) table[cell / PS] * NKV + kvh) * PS + cell % PS; - const double vv = fmt == 2 ? q4v(v4, row, d) - : fmt == 1 ? (double) vq[row * HD + d] * h2f(vs[row * 4 + d / 64]) : h2f(vh[row * HD + d]); - a += sco[c] * vv; - } - const double r = a / l; - const size_t at = (size_t) ((i * NH + h) * HD + d); - ref_scale = std::max(ref_scale, std::fabs(r)); - err_old = std::max(err_old, std::fabs(o[at] - r)); - err_new = std::max(err_new, std::fabs(nw[at] - r)); - } - } - } - // 2. new vs old everywhere - double diff = 0, scale = 0; - for (size_t i = 0; i < o.size(); ++i) { - diff = std::max(diff, (double) std::fabs(o[i] - nw[i])); - scale = std::max(scale, (double) std::fabs(o[i])); - } - // 3. speed - cudaEvent_t e0, e1; - cudaEventCreate(&e0); - cudaEventCreate(&e1); - float ms_old = 0, ms_new = 0; - cudaEventRecord(e0); - for (int r = 0; r < reps; ++r) old_run(); - cudaEventRecord(e1); - ck(cudaEventSynchronize(e1), "time"); - cudaEventElapsedTime(&ms_old, e0, e1); - cudaEventRecord(e0); - for (int r = 0; r < reps; ++r) new_run(); - cudaEventRecord(e1); - ck(cudaEventSynchronize(e1), "time"); - cudaEventElapsedTime(&ms_new, e0, e1); - const bool ok1 = err_new <= std::max(4.0 * err_old, 1e-6 * ref_scale); - const bool ok2 = diff <= 1e-4 * scale; - std::printf("%s %s ctx %lld, %lld queries: vs FP64 old %.3g new %.3g (output scale %.3g); new vs old %.3g (%.2g of " - "scale); %.3f -> %.3f ms per chunk (%.2fx)\n", - ok1 && ok2 ? "PASS" : "FAIL", fmt == 2 ? "q4_0" : fmt == 1 ? "int8" : "fp16", (long long) ctx, (long long) nq, err_old, - err_new, ref_scale, diff, diff / scale, ms_old / reps, ms_new / reps, ms_old / ms_new); - cudaFree((void*) d_ids); cudaFree((void*) d_steps); cudaFree((void*) d_q); cudaFree(d_old); cudaFree(d_new); - cudaFree(scratch); - cudaFree((void*) pl.k_q); cudaFree((void*) pl.v_q); cudaFree((void*) pl.k_scale); cudaFree((void*) pl.v_scale); - cudaFree((void*) pl.k_pool); cudaFree((void*) pl.v_pool); cudaFree((void*) pl.page_table); - cudaFree((void*) pl.k_q4); cudaFree((void*) pl.v_q4); - return ok1 && ok2 ? 0 : 1; -} -} // namespace - -int main(int argc, char** argv) { -#if defined(__HIP_PLATFORM_AMD__) - // S6: on AMD the kernel under test is the RDNA4 matrix-core one (opt-in in the engine); other cards skip - { - int dev = 0; - hipDeviceProp_t prop{}; - if (hipGetDevice(&dev) != hipSuccess || hipGetDeviceProperties(&prop, dev) != hipSuccess) return 2; - if (std::strncmp(prop.gcnArchName, "gfx12", 5) != 0) { - std::printf("SKIP: %s is not gfx12 (the matrix-core prompt attention is RDNA4 only)\n", prop.gcnArchName); - return 77; - } -#if defined(_WIN32) - _putenv_s("STRATA_HIP_WMMA", "1"); -#else - setenv("STRATA_HIP_WMMA", "1", 1); -#endif - } -#endif - const int64_t ctx = argc > 1 ? std::atoll(argv[1]) : 32768; - const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 2048; - const int reps = argc > 3 ? std::atoi(argv[3]) : 5; - int fails = 0; - fails += run(1, ctx, nq, reps); -#if !defined(__HIP_PLATFORM_AMD__) - fails += run(0, ctx, nq, reps); // FP16 KV: the RDNA4 kernel takes int8 KV only - fails += run(2, ctx, nq, reps); // Q4_0 KV (mode 4) - fails += run(2, 1500, std::min(nq, 1500), reps); -#endif - fails += run(1, 1500, std::min(nq, 1500), reps); // short context: the selection is every cell - fails += run(1, 2100, std::min(nq, 256), reps); // the identity-to-sparse edge - std::printf("FAILURES: %d\n", fails); - return fails; -} diff --git a/src/kernels/qsa_select_bench.cpp b/src/kernels/qsa_select_bench.cpp deleted file mode 100644 index e4ccd02..0000000 --- a/src/kernels/qsa_select_bench.cpp +++ /dev/null @@ -1,174 +0,0 @@ -// src/kernels/qsa_select_bench.cpp - the prompt path's QSA selection (qsa_select.hpp) timed per stage, block scores -// (the warp kernel and the tensor-core one) and top-k, for a batch of consecutive queries at a given context, and -// the two scorers compared: score difference and how many selections differ (GPU, synthetic, no model). -// Usage: qsa_select_bench [context=131072] [queries=256] [reps=10] [capacity_cells] -// capacity_cells (the engine's --max-context): the score buffers and the top-k dispatch follow the CAPACITY -// (max_blocks = capacity / 4 + 2), the work follows the context. Default: capacity = context (max_blocks = ctx / 4 + 1). -#include "strata/kernels/qsa.hpp" -#include "strata/kernels/qsa_select.hpp" - -#include - -#include -#include -#include -#include -#include -#include - -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(2); } -} -template T* up(const std::vector& h) { - T* d = nullptr; - ck(cudaMalloc(&d, h.size() * sizeof(T) + 64), "malloc"); - ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload"); - return d; -} -} // namespace - -int main(int argc, char** argv) { - const int64_t ctx = argc > 1 ? std::atoll(argv[1]) : 131072; - const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 256; - const int reps = argc > 3 ? std::atoi(argv[3]) : 10; - const k::QsaShapes s = k::qsa_real_shapes(); - const int64_t capacity = argc > 4 ? std::atoll(argv[4]) : 0; - const int64_t max_blocks = capacity > 0 ? capacity / 4 + 2 : ctx / 4 + 1, cap = k::qsa_selection_width(k::kTopkMaxCells, s); - std::mt19937 rng(7); - std::normal_distribution nd(0.f, 1.f); - // keys with a shared direction plus noise, so the scores have a spread like a real indexer's - std::vector dir(128), pooled((size_t) (max_blocks * 128)), dead(128), q((size_t) (nq * 512)); - for (auto& x : dir) x = nd(rng); - for (int64_t b = 0; b < max_blocks; ++b) { - const float a = nd(rng); - for (int d = 0; d < 128; ++d) pooled[(size_t) (b * 128 + d)] = 0.5f * a * dir[d] + nd(rng); - } - for (auto& x : dead) x = nd(rng); - for (int64_t i = 0; i < nq; ++i) - for (int d = 0; d < 512; ++d) q[(size_t) (i * 512 + d)] = 0.2f * dir[d % 128] + 0.1f * nd(rng); - std::vector steps((size_t) (nq * k::kStepCount)); - for (int64_t i = 0; i < nq; ++i) { // qsa_step_fill's arithmetic (kept here so the bench links only qsa_select) - int32_t* st = steps.data() + i * k::kStepCount; - const int64_t pos = ctx - nq + i; - st[k::kStepPos] = (int32_t) pos; - st[k::kStepNKv] = (int32_t) (pos + 1); - st[k::kStepNBid] = (int32_t) ((pos + 1) / s.idx_block); - st[k::kStepWidth] = (int32_t) k::qsa_selection_width(pos + 1, s); - } - const float* d_pooled = up(pooled); - const float* d_dead = up(dead); - const float* d_q = up(q); - const int32_t* d_steps = up(steps); - float *sc_old = nullptr, *sc_new = nullptr; - int32_t *ids_old = nullptr, *ids_new = nullptr; - ck(cudaMalloc(&sc_old, (size_t) (nq * max_blocks) * 4), "malloc"); - ck(cudaMalloc(&sc_new, (size_t) (nq * max_blocks) * 4), "malloc"); - ck(cudaMalloc(&ids_old, (size_t) (nq * cap) * 4), "malloc"); - ck(cudaMalloc(&ids_new, (size_t) (nq * cap) * 4), "malloc"); - const int64_t active = steps[(size_t) ((nq - 1) * k::kStepCount + k::kStepNBid)] + 1; - auto run_old = [&] { k::qsa_block_scores(d_pooled, d_dead, d_q, d_steps, nq, max_blocks, s, sc_old, nullptr, active); }; - // a device without the tensor-core scorer (HIP other than gfx12): time the warp scorer and the top-k only - const bool have_tc = k::qsa_block_scores_tc(d_pooled, d_dead, d_q, d_steps, 1, max_blocks, s, sc_new, nullptr, active); - auto run_new = [&] { - if (!k::qsa_block_scores_tc(d_pooled, d_dead, d_q, d_steps, nq, max_blocks, s, sc_new, nullptr, active)) { - std::fprintf(stderr, "tc scorer refused\n"); - std::exit(2); - } - }; - run_old(); - if (have_tc) run_new(); - else ck(cudaMemcpy(sc_new, sc_old, (size_t) (nq * max_blocks) * 4, cudaMemcpyDeviceToDevice), "copy"); - k::qsa_block_topk_ref(sc_old, d_steps, nq, max_blocks, cap, s, ids_old, nullptr); - k::qsa_block_topk(sc_new, d_steps, nq, max_blocks, cap, s, ids_new, nullptr, active); - int32_t* ids_reg = nullptr; // the register top-k on the OLD scores: must equal the reference exactly - ck(cudaMalloc(&ids_reg, (size_t) (nq * cap) * 4), "malloc"); - k::qsa_block_topk(sc_old, d_steps, nq, max_blocks, cap, s, ids_reg, nullptr, active); - ck(cudaDeviceSynchronize(), "warm"); - // compare - std::vector a((size_t) (nq * max_blocks)), b(a.size()); - std::vector ia((size_t) (nq * cap)), ib(ia.size()); - ck(cudaMemcpy(a.data(), sc_old, a.size() * 4, cudaMemcpyDeviceToHost), "down"); - ck(cudaMemcpy(b.data(), sc_new, b.size() * 4, cudaMemcpyDeviceToHost), "down"); - ck(cudaMemcpy(ia.data(), ids_old, ia.size() * 4, cudaMemcpyDeviceToHost), "down"); - ck(cudaMemcpy(ib.data(), ids_new, ib.size() * 4, cudaMemcpyDeviceToHost), "down"); - std::vector ir(ia.size()); - ck(cudaMemcpy(ir.data(), ids_reg, ir.size() * 4, cudaMemcpyDeviceToHost), "down"); - int64_t reg_same = 0; - for (int64_t i = 0; i < nq; ++i) { - const int64_t w = steps[(size_t) (i * k::kStepCount + k::kStepWidth)]; - reg_same += std::equal(ia.begin() + i * cap, ia.begin() + i * cap + w, ir.begin() + i * cap); - } - double max_rel = 0, sum_rel = 0, n_rel = 0; - int64_t same_sel = 0, cells_diff = 0, cells_all = 0; - for (int64_t i = 0; i < nq; ++i) { - const int32_t* st = steps.data() + i * k::kStepCount; - for (int64_t j = 0; j <= st[k::kStepNBid]; ++j) { - const double x = a[(size_t) (i * max_blocks + j)], y = b[(size_t) (i * max_blocks + j)]; - const double r = std::fabs(x - y) / std::max(1e-6, std::fabs(x)); - max_rel = std::max(max_rel, r); - sum_rel += r; - n_rel += 1; - } - const int64_t w = st[k::kStepWidth]; - std::vector x(ia.begin() + i * cap, ia.begin() + i * cap + w), y(ib.begin() + i * cap, ib.begin() + i * cap + w); - same_sel += x == y; - std::vector d; - std::set_symmetric_difference(x.begin(), x.end(), y.begin(), y.end(), std::back_inserter(d)); - cells_diff += (int64_t) d.size() / 2; - cells_all += w; - } - // accuracy against an FP64 host reference on a sample (blocks below n_bid; the tail block is the warp kernel's own - // arithmetic in both scorers). Gate, as the prompt-attention harness's: the scorer under test is no worse than 4x - // the warp kernel's error, floored at 1e-6 of the score scale. - double err_old = 0, err_new = 0, scale = 0; - { - std::mt19937 srng(11); - const int64_t nqs = std::min(nq, 32); - for (int64_t qs = 0; qs < nqs; ++qs) { - const int64_t i = qs * nq / nqs; - const int64_t nbid = steps[(size_t) (i * k::kStepCount + k::kStepNBid)]; - if (nbid <= 0) continue; - for (int sidx = 0; sidx < 1024; ++sidx) { - const int64_t j = sidx < 64 ? std::min(nbid - 1, sidx) : (int64_t) (srng() % (uint64_t) nbid); - double ref = 0; - for (int h = 0; h < 4; ++h) { - double d = 0; - for (int c = 0; c < 128; ++c) d += (double) q[(size_t) (i * 512 + h * 128 + c)] * (double) pooled[(size_t) (j * 128 + c)]; - ref += d > 0 ? d : 0; - } - scale = std::max(scale, std::fabs(ref)); - err_old = std::max(err_old, std::fabs(ref - (double) a[(size_t) (i * max_blocks + j)])); - err_new = std::max(err_new, std::fabs(ref - (double) b[(size_t) (i * max_blocks + j)])); - } - } - } - const bool acc_ok = !have_tc || err_new <= std::max(4.0 * err_old, 1e-6 * scale); - // time - cudaEvent_t e0, e1; - cudaEventCreate(&e0); cudaEventCreate(&e1); - auto timed = [&](auto f) { - cudaEventRecord(e0); - for (int r = 0; r < reps; ++r) f(); - cudaEventRecord(e1); - ck(cudaEventSynchronize(e1), "time"); - float ms = 0; - cudaEventElapsedTime(&ms, e0, e1); - return ms / reps; - }; - const float t_old = timed(run_old), t_new = have_tc ? timed(run_new) : t_old; - const float t_tk = timed([&] { k::qsa_block_topk_ref(sc_old, d_steps, nq, max_blocks, cap, s, ids_old, nullptr); }); - const float t_tk2 = timed([&] { k::qsa_block_topk(sc_old, d_steps, nq, max_blocks, cap, s, ids_reg, nullptr, active); }); - std::printf("top-k %.3f -> %.3f ms (%.1fx), register top-k identical to the reference %lld/%lld\n", t_tk, t_tk2, - t_tk / t_tk2, (long long) reg_same, (long long) nq); - std::printf("%s accuracy vs FP64 (score scale %.3g): warp kernel max err %.3g, tensor-core max err %.3g (%.2g of scale)\n", - !have_tc ? "SKIP" : acc_ok ? "PASS" : "FAIL", scale, err_old, err_new, scale > 0 ? err_new / scale : 0.0); - if (!have_tc) std::printf("tensor-core scorer not available on this device: warp scorer %.3f ms, top-k %.3f ms (%.0f%% of the two)\n", t_old, t_tk2, 100.0 * t_tk2 / (t_old + t_tk2)); - std::printf("ctx %lld, %lld queries x %lld blocks: scores %.3f -> %.3f ms (%.1fx), top-k %.3f ms; score rel diff " - "mean %.2g max %.2g; selections identical %lld/%lld, cells differing %.4f%%\n", (long long) ctx, - (long long) nq, (long long) active, t_old, t_new, t_old / t_new, t_tk, sum_rel / std::max(1.0, n_rel), - max_rel, (long long) same_sel, (long long) nq, cells_all ? 100.0 * (double) cells_diff / (double) cells_all : 0.0); - return acc_ok && reg_same == nq ? 0 : 1; -} diff --git a/src/kernels/qsa_topk_active_parity.cpp b/src/kernels/qsa_topk_active_parity.cpp deleted file mode 100644 index 031c0d7..0000000 --- a/src/kernels/qsa_topk_active_parity.cpp +++ /dev/null @@ -1,95 +0,0 @@ -// Capacity 262144, live prefill up to the register boundary, and the legacy fallbacks. -// Compare selected IDs only: unused output padding is not part of the API contract. -#include "strata/kernels/qsa.hpp" -#include "strata/kernels/qsa_select.hpp" -#include -#include -#include -#include -#include -#include - -namespace k = strata::kernels; -namespace { -void ck(cudaError_t e) { - if (e != cudaSuccess) { - std::fprintf(stderr, "CUDA: %s\n", cudaGetErrorString(e)); - std::exit(2); - } -} -struct Case { int64_t ctx, queries; int mode; }; -bool check(Case c) { - constexpr int64_t stride = 262144 / 4 + 2; - const auto s = k::qsa_real_shapes(); - const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s); - std::vector steps((size_t)(c.queries * k::kStepCount)); - std::vector scores((size_t)(c.queries * stride), -999.f); - std::mt19937 rng(742913); - std::uniform_real_distribution random(0.f, 200.f); - for (int64_t i = 0; i < c.queries; ++i) { - auto* st = steps.data() + i * k::kStepCount; - const int64_t pos = c.ctx - c.queries + i; - st[k::kStepPos] = (int32_t)pos; - st[k::kStepNKv] = (int32_t)(pos + 1); - st[k::kStepNBid] = (int32_t)((pos + 1) / s.idx_block); - st[k::kStepWidth] = (int32_t)k::qsa_selection_width(pos + 1, s); - for (int64_t j = 0; j <= st[k::kStepNBid]; ++j) - scores[(size_t)(i * stride + j)] = c.mode == 1 ? 0.f : c.mode == 2 ? float(j % 7) : random(rng); - if ((pos + 1) % s.idx_block) - scores[(size_t)(i * stride + st[k::kStepNBid])] += 1e9f; - } - int64_t active = steps[(size_t)((c.queries - 1) * k::kStepCount + k::kStepNBid)] + 1; - if (c.mode == 3) active = 0; - if (c.mode == 4) active = stride + 1; - float* ds = nullptr; - int32_t *dt = nullptr, *da = nullptr, *db = nullptr; - ck(cudaMalloc(&ds, scores.size() * sizeof(float))); - ck(cudaMalloc(&dt, steps.size() * sizeof(int32_t))); - ck(cudaMalloc(&da, (size_t)(c.queries * cap) * sizeof(int32_t))); - ck(cudaMalloc(&db, (size_t)(c.queries * cap) * sizeof(int32_t))); - ck(cudaMemcpy(ds, scores.data(), scores.size() * sizeof(float), cudaMemcpyHostToDevice)); - ck(cudaMemcpy(dt, steps.data(), steps.size() * sizeof(int32_t), cudaMemcpyHostToDevice)); - // No bound: the exact capacity-based dispatch used by captured decode. - k::qsa_block_topk(ds, dt, c.queries, stride, cap, s, da, nullptr); - k::qsa_block_topk(ds, dt, c.queries, stride, cap, s, db, nullptr, active); - ck(cudaDeviceSynchronize()); - std::vector a((size_t)(c.queries * cap)), b(a.size()); - ck(cudaMemcpy(a.data(), da, a.size() * sizeof(int32_t), cudaMemcpyDeviceToHost)); - ck(cudaMemcpy(b.data(), db, b.size() * sizeof(int32_t), cudaMemcpyDeviceToHost)); - bool ok = true; - for (int64_t i = 0; i < c.queries; ++i) { - const int64_t w = steps[(size_t)(i * k::kStepCount + k::kStepWidth)]; - if (!std::equal(a.begin() + i * cap, a.begin() + i * cap + w, b.begin() + i * cap)) { - std::fprintf(stderr, "FAIL ctx=%lld queries=%lld mode=%d row=%lld\n", - (long long)c.ctx, (long long)c.queries, c.mode, (long long)i); - ok = false; - break; - } - } - ck(cudaFree(ds)); ck(cudaFree(dt)); ck(cudaFree(da)); ck(cudaFree(db)); - return ok; -} -} - -int main() { - int devices = 0; - if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) { - std::puts("SKIP: no CUDA device"); - return 77; - } - // the active-bound dispatch is Turing's in the engine; forced here so every CUDA card checks it -#if defined(_WIN32) - _putenv_s("STRATA_TOPK_ACTIVE_ANY", "1"); -#else - setenv("STRATA_TOPK_ACTIVE_ANY", "1", 1); -#endif - const Case cases[] = { - {1111, 256, 0}, {8192, 256, 0}, {32768, 256, 0}, {131072, 256, 0}, - {131075, 255, 0}, {135164, 256, 0}, {135168, 256, 0}, {250022, 256, 0}, - {262144, 256, 0}, {131072, 1, 0}, {131072, 8, 0}, {131072, 257, 0}, - {131072, 256, 1}, {131072, 256, 2}, {131072, 256, 3}, {131072, 256, 4}, - }; - for (const auto c : cases) if (!check(c)) return 1; - std::puts("PASS: 16 top-k active-bound cases, selected IDs bitwise identical"); - return 0; -} diff --git a/src/kernels/qsa_topk_parity.cpp b/src/kernels/qsa_topk_parity.cpp deleted file mode 100644 index d14af3e..0000000 --- a/src/kernels/qsa_topk_parity.cpp +++ /dev/null @@ -1,139 +0,0 @@ -// src/kernels/qsa_topk_parity.cpp - the QSA top-k the engine dispatches (qsa_block_topk) against the original kernel -// (qsa_block_topk_ref): the selected cells must be identical (GPU, synthetic, no model). -// -// A case is a context under a capacity (the engine's --max-context; max_blocks = capacity / 4 + 2, and without an -// active-block count the dispatch follows it), with consecutive queries at the context's end so that the tail block -// holds 0 to 3 cells. Three score sets per case: continuous, 64 levels (many ties at the threshold) and all equal -// (the rule's ties go to the lowest index). The dispatch is called as a decode window calls it (no block count) and as -// the prompt path does (with the call's largest block count). The reference and the dispatched kernel are also timed. -// -// Usage: qsa_topk_parity --selftest -// qsa_topk_parity CONTEXT [QUERIES=256] [REPS=10] [CAPACITY=CONTEXT] [COUNT=1] (COUNT=0: no block count) -#include "strata/kernels/qsa.hpp" -#include "strata/kernels/qsa_select.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include - -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(2); } -} - -bool run_case(int64_t ctx, int64_t nq, int reps, int64_t capacity, bool counted) { - const k::QsaShapes s = k::qsa_real_shapes(); - const int64_t max_blocks = capacity / s.idx_block + 2, cap = k::qsa_selection_width(k::kTopkMaxCells, s); - std::vector steps((size_t) (nq * k::kStepCount)); - for (int64_t i = 0; i < nq; ++i) { - int32_t* st = steps.data() + i * k::kStepCount; - const int64_t pos = ctx - nq + i; - st[k::kStepPos] = (int32_t) pos; - st[k::kStepNKv] = (int32_t) (pos + 1); - st[k::kStepNBid] = (int32_t) ((pos + 1) / s.idx_block); - st[k::kStepWidth] = (int32_t) k::qsa_selection_width(pos + 1, s); - } - std::mt19937 rng((uint32_t) (ctx * 31 + capacity)); - std::normal_distribution nd(0.f, 1.f); - std::vector scores((size_t) (nq * max_blocks)), tied(scores.size()), equal(scores.size(), 0.25f); - for (int64_t i = 0; i < nq; ++i) { - const int32_t* st = steps.data() + i * k::kStepCount; - float* row = scores.data() + i * max_blocks; - for (int64_t b = 0; b < max_blocks; ++b) row[b] = nd(rng); - // the tail block as the scorers leave it: far above the others when it holds cells - if (st[k::kStepNKv] % s.idx_block != 0) row[st[k::kStepNBid]] += 1e9f; - for (int64_t b = 0; b < max_blocks; ++b) - tied[(size_t) (i * max_blocks + b)] = row[b] > 1e8f ? row[b] : std::floor(row[b] * 8.0f) / 8.0f; // ~64 levels - } - int32_t *d_steps = nullptr, *ids_ref = nullptr, *ids_new = nullptr; - float* d_scores = nullptr; - ck(cudaMalloc(&d_steps, steps.size() * 4), "malloc"); - ck(cudaMalloc(&d_scores, scores.size() * 4), "malloc"); - ck(cudaMalloc(&ids_ref, (size_t) (nq * cap) * 4), "malloc"); - ck(cudaMalloc(&ids_new, (size_t) (nq * cap) * 4), "malloc"); - ck(cudaMemcpy(d_steps, steps.data(), steps.size() * 4, cudaMemcpyHostToDevice), "upload"); - const int64_t active = counted ? steps[(size_t) ((nq - 1) * k::kStepCount + k::kStepNBid)] + 1 : -1; - std::vector a((size_t) (nq * cap)), b(a.size()); - auto same = [&](const std::vector& sc) -> int64_t { - ck(cudaMemcpy(d_scores, sc.data(), sc.size() * 4, cudaMemcpyHostToDevice), "upload"); - ck(cudaMemset(ids_ref, 0xff, a.size() * 4), "memset"); - ck(cudaMemset(ids_new, 0xff, a.size() * 4), "memset"); - k::qsa_block_topk_ref(d_scores, d_steps, nq, max_blocks, cap, s, ids_ref, nullptr); - k::qsa_block_topk(d_scores, d_steps, nq, max_blocks, cap, s, ids_new, nullptr, active); - ck(cudaDeviceSynchronize(), "sync"); - ck(cudaMemcpy(a.data(), ids_ref, a.size() * 4, cudaMemcpyDeviceToHost), "down"); - ck(cudaMemcpy(b.data(), ids_new, b.size() * 4, cudaMemcpyDeviceToHost), "down"); - int64_t n = 0; - for (int64_t i = 0; i < nq; ++i) { - const int64_t w = steps[(size_t) (i * k::kStepCount + k::kStepWidth)]; - n += std::equal(a.begin() + i * cap, a.begin() + i * cap + w, b.begin() + i * cap); - } - return n; - }; - const int64_t same_tied = same(tied), same_equal = same(equal), same_cont = same(scores); // d_scores: continuous - cudaEvent_t e0, e1; - ck(cudaEventCreate(&e0), "event"); - ck(cudaEventCreate(&e1), "event"); - auto timed = [&](auto f) { - ck(cudaEventRecord(e0), "record"); - for (int r = 0; r < reps; ++r) f(); - ck(cudaEventRecord(e1), "record"); - ck(cudaEventSynchronize(e1), "time"); - float ms = 0; - ck(cudaEventElapsedTime(&ms, e0, e1), "elapsed"); - return ms / (float) reps; - }; - const float t_ref = timed([&] { k::qsa_block_topk_ref(d_scores, d_steps, nq, max_blocks, cap, s, ids_ref, nullptr); }); - const float t_new = timed([&] { k::qsa_block_topk(d_scores, d_steps, nq, max_blocks, cap, s, ids_new, nullptr, active); }); - cudaEventDestroy(e0); cudaEventDestroy(e1); - cudaFree(d_steps); cudaFree(d_scores); cudaFree(ids_ref); cudaFree(ids_new); - const bool ok = same_cont == nq && same_tied == nq && same_equal == nq; - std::printf("%s context %lld under a capacity of %lld (%lld blocks), %lld queries %s: reference %.3f ms, " - "dispatched %.3f ms (%.1fx); identical ids: continuous %lld/%lld, 64 levels %lld/%lld, equal scores " - "%lld/%lld\n", ok ? "PASS" : "FAIL", (long long) ctx, (long long) capacity, (long long) max_blocks, - (long long) nq, counted ? "with their block count" : "without a block count", t_ref, t_new, t_ref / t_new, - (long long) same_cont, (long long) nq, (long long) same_tied, - (long long) nq, (long long) same_equal, (long long) nq); - return ok; -} -} // namespace - -int main(int argc, char** argv) { - if (argc > 1 && std::strcmp(argv[1], "--selftest") == 0) { - // {context, capacity}: both sides of the register kernel's reach (33,792 blocks = 135,168 cells), short - // contexts under a long capacity (fewer blocks than the kernel's threads; a prompt batch below the dispatch's - // 4,608 blocks), and the long contexts themselves - const int64_t cases[][2] = {{9000, 9000}, {135160, 135160}, {135176, 135176}, {2100, 262144}, - {9000, 262144}, {32768, 262144}, {262144, 262144}, {300001, 524288}, - {524288, 524288}}; - bool ok = true; - for (const auto& c : cases) { - ok = run_case(c[0], 8, 3, c[1], false) && ok; // a decode window's call - ok = run_case(c[0], 64, 3, c[1], true) && ok; // the prompt path's - } - std::printf("%s\n", ok ? "qsa_topk_parity: PASS" : "qsa_topk_parity: FAIL"); - return ok ? 0 : 1; - } - if (argc < 2) { - std::fprintf(stderr, "usage: qsa_topk_parity --selftest | CONTEXT [QUERIES=256] [REPS=10] [CAPACITY=CONTEXT] " - "[COUNT=1]\n"); - return 2; - } - const int64_t ctx = std::atoll(argv[1]); - const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 256; - const int reps = argc > 3 ? std::atoi(argv[3]) : 10; - const int64_t capacity = argc > 4 ? std::atoll(argv[4]) : ctx; - if (ctx < nq || nq <= 0 || reps <= 0 || capacity < ctx) { - std::fprintf(stderr, "qsa_topk_parity: CONTEXT >= QUERIES > 0, REPS > 0, CAPACITY >= CONTEXT\n"); - return 2; - } - return run_case(ctx, nq, reps, capacity, argc <= 5 || std::atoi(argv[5]) != 0) ? 0 : 1; -} diff --git a/src/kernels/quantize_act_parity.cpp b/src/kernels/quantize_act_parity.cpp deleted file mode 100644 index b2cd7ee..0000000 --- a/src/kernels/quantize_act_parity.cpp +++ /dev/null @@ -1,407 +0,0 @@ -// src/kernels/quantize_act_parity.cpp - P2.S2's parity test for the Q8_0 activation quantizer. -// -// THE CHECK IS ON THE BYTES, not on the round-tripped values. `ref/quant.py::q8_0`'s central finding is that -// dividing by the fp16-rounded scale instead of the fp32 one changed 18 of 80 blocks' quantized integers -// while leaving the dequantized values within a rounding step - so a comparison of VALUES would have passed -// and the engine would still have disagreed with ggml. Comparing the 34-byte block catches that directly. -// -// The reference is a host transcription of `ref/quant.py::q8_0`: -// -// d32 = amax / 127.0f (f32) -// d16 = fp16(d32) (stored, and used to DEQUANTIZE) -// q = clip(rint(x / (double)d32), -128, 127) -// round trip = q * d16 -#include "strata/kernels/quantize_act.hpp" -#include "strata/kernels/f16_bits.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { - -void check(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -// THE CONVERSIONS COME FROM `f16_bits.hpp`, and this test used to carry its own. The private `f16_bits_to_f32` -// below flushed fp16 SUBNORMALS to zero, and the private encoder returned NaN for finite fp16 overflow - both -// invisible with the O(1) fixture this file has. Round 198 validated the shared pair against 395 numpy -// float16 vectors and all 65,536 reverse patterns, so the test now shares the implementation it is checking -// instead of guessing at it independently. Thin aliases keep the body below unchanged. -using strata::kernels::f16_from_f32; -using strata::kernels::f32_from_f16; -inline uint16_t f32_to_f16_bits(float f) { return f16_from_f32(f); } -inline float f16_bits_to_f32(uint16_t h) { return f32_from_f16(h); } - -void reference_q8_0(const float* x, long long n, std::vector& blocks, std::vector& back) { - blocks.assign((size_t) (n / 32) * 34, 0); - back.assign((size_t) n, 0.0f); - for (long long b = 0; b < n / 32; ++b) { - const float* xb = x + b * 32; - float amax = 0.0f; - for (int i = 0; i < 32; ++i) amax = std::fmax(amax, std::fabs(xb[i])); - uint8_t* out = &blocks[(size_t) b * 34]; - if (amax == 0.0f) continue; - const float d32 = amax / 127.0f; - const uint16_t dbits = f32_to_f16_bits(d32); - out[0] = (uint8_t) (dbits & 0xFF); - out[1] = (uint8_t) (dbits >> 8); - const float d16 = f16_bits_to_f32(dbits); - for (int i = 0; i < 32; ++i) { - double q = std::rint((double) xb[i] / (double) d32); - if (q > 127.0) q = 127.0; - if (q < -128.0) q = -128.0; - out[2 + i] = (uint8_t) (int8_t) q; - back[(size_t) (b * 32 + i)] = (float) (int8_t) out[2 + i] * d16; - } - } -} - -int run_case(const char* name, const std::vector& x, bool check_bytes) { - const long long n = (long long) x.size(); - std::vector r_blocks, g_blocks((size_t) (n / 32) * 34); - std::vector r_back, g_back((size_t) n); - reference_q8_0(x.data(), n, r_blocks, r_back); - - float* d_x = nullptr; - uint8_t* d_b = nullptr; - float* d_back = nullptr; - check(cudaMalloc(&d_x, (size_t) n * sizeof(float)), "malloc x"); - check(cudaMalloc(&d_b, g_blocks.size()), "malloc blocks"); - check(cudaMalloc(&d_back, (size_t) n * sizeof(float)), "malloc back"); - check(cudaMemcpy(d_x, x.data(), (size_t) n * sizeof(float), cudaMemcpyHostToDevice), "copy x"); - // PROBE: does the DEVICE hold what the host thinks it sent? The scale byte differs with the SAME - // exponent and a zeroed mantissa, which says the kernel's amax differs from the host's on identical - // input - so the first thing to rule out is the copy itself. - { - std::vector rt((size_t) n); - check(cudaMemcpy(rt.data(), d_x, (size_t) n * sizeof(float), cudaMemcpyDeviceToHost), "probe copy back"); - long long diff = 0; - for (long long i = 0; i < n; ++i) if (std::memcmp(&rt[(size_t) i], &x[(size_t) i], 4) != 0) ++diff; - if (diff) std::printf(" PROBE: device x differs from host x in %lld of %lld elements\n", diff, n); - } - strata::kernels::quantize_q8_0(d_x, d_b, n, nullptr); - strata::kernels::dequant_q8_0(d_b, d_back, n, nullptr); - check(cudaMemcpy(g_blocks.data(), d_b, g_blocks.size(), cudaMemcpyDeviceToHost), "back blocks"); - check(cudaMemcpy(g_back.data(), d_back, (size_t) n * sizeof(float), cudaMemcpyDeviceToHost), "back vals"); - - long long byte_bad = 0, val_bad = 0; - if (check_bytes) { - for (size_t i = 0; i < g_blocks.size(); ++i) if (g_blocks[i] != r_blocks[i]) ++byte_bad; - } - for (long long i = 0; i < n; ++i) { - const float a = r_back[(size_t) i], b = g_back[(size_t) i]; - // the round trip is `q * d16`: both sides use the SAME fp16 d, so this is exact when q agrees - if (std::memcmp(&a, &b, sizeof(float)) != 0) ++val_bad; - } - if (byte_bad && check_bytes) { - for (size_t i = 0; i < g_blocks.size(); ++i) { - if (g_blocks[i] != r_blocks[i]) { - const size_t blk = i / 34; - const float amax = [&] { float m = 0; for (int k = 0; k < 32; ++k) m = std::fmax(m, std::fabs(x[(size_t)(blk*32+k)])); return m; }(); - std::printf(" first bad byte: block %zu offset %zu amax %.9g d32 %.9g\n", blk, i % 34, amax, amax/127.0f); - std::printf(" ref scale bytes %02x %02x got %02x %02x\n", r_blocks[blk*34], r_blocks[blk*34+1], g_blocks[blk*34], g_blocks[blk*34+1]); - std::printf(" ref[0..9]:"); for (int k = 0; k < 10; ++k) std::printf(" %02x", r_blocks[blk*34+k]); - std::printf("\n got[0..9]:"); for (int k = 0; k < 10; ++k) std::printf(" %02x", g_blocks[blk*34+k]); - std::printf("\n ref[10..17]:"); for (int k = 10; k < 18; ++k) std::printf(" %02x", r_blocks[blk*34+k]); - std::printf("\n got[10..17]:"); for (int k = 10; k < 18; ++k) std::printf(" %02x", g_blocks[blk*34+k]); - std::printf("\n x[0..3] = %.9g %.9g %.9g %.9g\n", (double)x[(size_t)(blk*32)], (double)x[(size_t)(blk*32+1)], (double)x[(size_t)(blk*32+2)], (double)x[(size_t)(blk*32+3)]); - break; - } - } - } - std::printf(" %-26s blocks %s (%lld bad bytes) round trip %s (%lld differ)\n", name, - !check_bytes ? "not compared" : (byte_bad ? "*** WRONG ***" : "byte-exact"), byte_bad, - val_bad ? "*** WRONG ***" : "bit-exact", val_bad); - cudaFree(d_x); - cudaFree(d_b); - cudaFree(d_back); - return (int) (byte_bad + val_bad); -} - -// A host transcription of ggml's `quantize_row_q8_K_ref` (ggml-quants.c L2768), including `nearest_int`. -// -// NOTE WHICH REFERENCE THIS IS. `ref/quant.py::q8_K` is the numpy transcription and it multiplies in -// FLOAT64 (`iscale * blk.astype(np.float64)`), while ggml multiplies in FLOAT32 before `nearest_int`. The -// oracle is ggml, so this follows ggml. The two agree except where an f32 product lands exactly on a tie or -// a rounding boundary, which is exactly the regime the "exact ties" case below constructs. -int nearest_int_host(float fval) { - const float val = fval + 12582912.0f; - int i; - std::memcpy(&i, &val, 4); - return (i & 0x007fffff) - 0x00400000; -} - -void reference_q8_K(const float* x, long long n, std::vector& blocks, std::vector& back, - float scale_num) { - const int QK = 256; - blocks.assign((size_t) (n / QK) * 292, 0); - back.assign((size_t) n, 0.0f); - for (long long b = 0; b < n / QK; ++b) { - const float* xb = x + b * QK; - uint8_t* out = &blocks[(size_t) b * 292]; - float max = 0.0f, amax = 0.0f; - for (int j = 0; j < QK; ++j) { - const float ax = std::fabs(xb[j]); - if (ax > amax) { amax = ax; max = xb[j]; } // STRICTLY greater: ties keep the FIRST maximum - } - if (amax == 0.0f) continue; // d = 0, qs = 0, bsums = 0 (see the kernel note) - const float iscale = scale_num / max; // -127 by default; -128 is the rival reading - int8_t* qs = (int8_t*) (out + 4); - for (int j = 0; j < QK; ++j) { - const int v = nearest_int_host(iscale * xb[j]); - qs[j] = (int8_t) std::min(127, v); - } - int16_t* bsums = (int16_t*) (out + 4 + QK); - for (int j = 0; j < QK / 16; ++j) { - int sum = 0; - for (int ii = 0; ii < 16; ++ii) sum += qs[j * 16 + ii]; - bsums[j] = (int16_t) sum; - } - const float d = 1.0f / iscale; - std::memcpy(out, &d, 4); - for (int j = 0; j < QK; ++j) back[(size_t) (b * QK + j)] = (float) qs[j] * d; - } -} - -int run_case_k(const char* name, const std::vector& x, bool check_bytes, float scale_num = -127.0f) { - const long long n = (long long) x.size(); - std::vector r_blocks, g_blocks((size_t) (n / 256) * 292); - std::vector r_back, g_back((size_t) n); - reference_q8_K(x.data(), n, r_blocks, r_back, scale_num); - - float* d_x = nullptr; - uint8_t* d_b = nullptr; - float* d_back = nullptr; - check(cudaMalloc(&d_x, (size_t) n * sizeof(float)), "malloc x"); - check(cudaMalloc(&d_b, g_blocks.size()), "malloc blocks"); - check(cudaMalloc(&d_back, (size_t) n * sizeof(float)), "malloc back"); - check(cudaMemcpy(d_x, x.data(), (size_t) n * sizeof(float), cudaMemcpyHostToDevice), "copy x"); - strata::kernels::quantize_q8_K(d_x, d_b, n, nullptr); - strata::kernels::dequant_q8_K(d_b, d_back, n, nullptr); - check(cudaMemcpy(g_blocks.data(), d_b, g_blocks.size(), cudaMemcpyDeviceToHost), "back blocks"); - check(cudaMemcpy(g_back.data(), d_back, (size_t) n * sizeof(float), cudaMemcpyDeviceToHost), "back vals"); - - long long byte_bad = 0, val_bad = 0, first_bad = -1; - if (check_bytes) - for (size_t i = 0; i < g_blocks.size(); ++i) - if (g_blocks[i] != r_blocks[i]) { if (first_bad < 0) first_bad = (long long) i; ++byte_bad; } - for (long long i = 0; i < n; ++i) - if (std::memcmp(&r_back[(size_t) i], &g_back[(size_t) i], 4) != 0) ++val_bad; - std::printf(" %-26s blocks %s (%lld bad bytes) round trip %s (%lld differ)\n", name, - !check_bytes ? "not compared" : (byte_bad ? "*** WRONG ***" : "byte-exact"), byte_bad, - val_bad ? "*** WRONG ***" : "bit-exact", val_bad); - if (first_bad >= 0) { - // Say WHERE and WHAT, because "1 element in 524288" is the signature of a rounding boundary and not - // of a wrong formula - and the two need completely different responses. - const size_t blk = (size_t) first_bad / 292, off = (size_t) first_bad % 292; - const char* where = off < 4 ? "d (the f32 scale)" : (off < 260 ? "qs (the quants)" : "bsums"); - std::printf(" first bad byte: block %zu offset %zu = %s ref %02x got %02x\n", blk, off, - where, r_blocks[(size_t) first_bad], g_blocks[(size_t) first_bad]); - if (off >= 4 && off < 260) { - const int j = (int) off - 4; - const float xv = x[(size_t) (blk * 256 + j)]; - float mx = 0.0f; - for (int k = 0; k < 256; ++k) { const float ax = std::fabs(x[(size_t) (blk * 256 + k)]); if (ax > std::fabs(mx)) mx = x[(size_t) (blk * 256 + k)]; } - const float isc = -127.0f / mx; - const float prod = isc * xv; - std::printf(" element %d: x %.9g max %.9g iscale %.9g iscale*x %.9g (frac %.6f)\n", - j, (double) xv, (double) mx, (double) isc, (double) prod, (double) (prod - std::floor(prod))); - } else if (off < 4) { - float rd, gd; - std::memcpy(&rd, &r_blocks[(size_t) (blk * 292)], 4); - std::memcpy(&gd, &g_blocks[(size_t) (blk * 292)], 4); - std::printf(" d: ref %.9g got %.9g\n", (double) rd, (double) gd); - } - } - cudaFree(d_x); - cudaFree(d_b); - cudaFree(d_back); - return (int) (byte_bad + val_bad); -} - -} // namespace - -int main(int argc, char** argv) { - bool selftest = false; - for (int i = 1; i < argc; ++i) { - if (std::string(argv[i]) == "--selftest") selftest = true; - else { std::fprintf(stderr, "usage: quantize_act_parity [--selftest]\n"); return 2; } - } - std::mt19937 rng(7); - std::normal_distribution gauss(0.0f, 1.0f); - int bad = 0; - const long long N = 32 * 4096; - - // ---- ordinary activations - std::vector a((size_t) N); - for (auto& v : a) v = gauss(rng); - bad += run_case("random normal", a, true); - - // ---- an activation with a very small dynamic range, where d32 is tiny and the fp16 rounding of d is a - // LARGE relative change - this is where dividing by d16 instead of d32 would show up in the bytes - std::vector b((size_t) N); - for (auto& v : b) v = gauss(rng) * 1e-6f; - bad += run_case("small magnitude (1e-6)", b, true); - - // ---- an all-zero block must produce a zeroed block, not a division by zero - std::vector c((size_t) N, 0.0f); - bad += run_case("all zero", c, true); - - // ---- values that land exactly on .5 boundaries, where rint's half-to-even and a float division's - // rounding both decide the result - std::vector d((size_t) N); - for (long long i = 0; i < N; ++i) { - // construct so that x / d32 is very close to a .5 boundary: d32 = amax/127, so pick amax = 127.0 and - // x = k + 0.5 for integer k - d[(size_t) i] = ((i % 200) - 100) + 0.5f; - } - d[0] = 127.0f; - bad += run_case("exact .5 boundaries", d, true); - - // ---- a single extreme value in each block, so d32 is set by it and every other quant is small - std::vector e((size_t) N, 0.0f); - for (long long blk = 0; blk < N / 32; ++blk) e[(size_t) (blk * 32)] = 1000.0f + (float) (blk % 7); - bad += run_case("one extreme per block", e, true); - - std::printf("\nquantize_q8_0: %d failures over 5 distributions x %lld elements\n", bad, N); - - // ============================== Q8_K ============================== - // - // The K-quants' activation: 2.89 GiB of dense weights - the attention projections and `ssm_out`. The - // oracle here is GGML's C reference, and the traps are the two the source comments warn about. - // ============================== the fp16 conversion itself ============================== - // - // REGRESSION CHECK FOR A BUG THAT SHIPPED. The private encoder in `quantize_act.cu` - and the identical - // one in `shared_expert.cu` - tested `if (exp >= 31)` to catch an out-of-range exponent, which conflates - // an f32 INF/NAN (raw exponent 255) with a FINITE value too large for fp16. Every finite overflow came - // back as a NaN instead of saturating to inf. **Neither file's fixture could see it, because every value - // in both is O(1)** - the Q8_0 case above scales by a max that is never near 65504. Round 198's - // numpy-generated oracle caught it on the first run. - // - // The decoder in this same test had the matching defect in the other direction: it flushed fp16 - // SUBNORMALS to zero, so 0x0001 decoded as 0.0 instead of 2^-24. - // - // These are the exact values, asserted against what numpy's float16 says. They are here rather than - // only in `qsa_parity` because this is the file that OWNS the Q8_0/Q8_K scales, and a scale that is NaN - // poisons a whole block silently. - { - struct F16Case { float in; uint16_t want; const char* what; }; - const F16Case cases[] = { - {1e30f, 0x7C00u, "1e30 -> +inf (finite overflow)"}, - {-1e30f, 0xFC00u, "-1e30 -> -inf"}, - {65536.0f, 0x7C00u, "65536 -> +inf (just past fp16 max)"}, - // FLT_MAX is 3.4028235e38, so `1e45f` is not even a legal literal; 3e38 is the largest finite - // f32 that still overflows fp16, which is what this case is for. - {3.0e38f, 0x7C00u, "3e38 (near FLT_MAX) -> +inf"}, - {65504.0f, 0x7BFFu, "65504 -> the largest finite fp16, NOT inf"}, - // The boundary, checked against numpy: 65520.0 is the exact tie between 65504 and the - // "next" fp16 (65536 = inf) and rounds to EVEN, i.e. to inf; 65519.996 is below it and stays - // finite. The first version of this table asserted inf for 65519.996 - the FIXTURE was wrong and - // the kernel was right, which is why the expected bits are quoted from numpy rather than reasoned. - {65519.996f, 0x7BFFu, "65519.996 -> just below the boundary, still finite"}, - {65520.0f, 0x7C00u, "65520.0 -> the exact tie, rounds to even = inf"}, - {65536.0f, 0x7C00u, "65536 -> past fp16 max"}, - {5.9604645e-8f, 0x0001u, "2^-24 -> the smallest subnormal, NOT zero"}, - {1.0f, 0x3C00u, "1.0"}, - {0.0f, 0x0000u, "0.0"}, - }; - int fp16_bad = 0; - for (const F16Case& c : cases) { - const uint16_t got = strata::kernels::f16_from_f32(c.in); - if (got != c.want) { - std::printf(" *** %s: want 0x%04X got 0x%04X\n", c.what, c.want, got); - ++fp16_bad; - } - } - // and the reverse direction on the pattern that was flushed - const float sub = strata::kernels::f32_from_f16(0x0001u); - const bool sub_ok = (sub == 5.9604645e-8f); - std::printf(" %-44s %s (%d of %d wrong)\n", "f32->f16 overflow saturates, not NaN", - fp16_bad ? "*** NO ***" : "yes", fp16_bad, (int) (sizeof cases / sizeof cases[0])); - std::printf(" %-44s %s (0x0001 -> %.9g, want 2^-24)\n", "f16->f32 keeps subnormals", - sub_ok ? "yes" : "*** NO ***", (double) sub); - if (fp16_bad) bad += fp16_bad; - if (!sub_ok) ++bad; - } - - std::printf("\nQ8_K (ggml block_q8_K: 292 bytes / 256 elements, {f32 d; i8 qs[256]; i16 bsums[16]})\n"); - int bad_k = 0; - const long long NK = 256 * 2048; - - std::vector ka((size_t) NK); - for (auto& v : ka) v = gauss(rng); - bad_k += run_case_k("random normal", ka, true); - - std::vector kb((size_t) NK); - for (auto& v : kb) v = gauss(rng) * 1e-7f; // tiny: the scale is far from fp16-representable - bad_k += run_case_k("small magnitude (1e-7)", kb, true); - - std::vector kc((size_t) NK, 0.0f); - bad_k += run_case_k("all zero", kc, true); - - // EXACT TIES. `nearest_int` is round-half-to-EVEN (the 12582912.0f magic number); `roundf` is - // half-AWAY-FROM-ZERO. They differ only when `iscale*x` is exactly k+0.5, which never happens on real - // data - so this fixture MANUFACTURES it: with max = 127.0 and iscale = -1.0, x = -(k+0.5) gives exactly - // k+0.5, and the two rules disagree for every EVEN k. - std::vector kd((size_t) NK, 0.0f); - for (long long blk = 0; blk < NK / 256; ++blk) - for (int j = 0; j < 256; ++j) kd[(size_t) (blk * 256 + j)] = -(float) ((j % 100) + 0.5f); - for (long long blk = 0; blk < NK / 256; ++blk) kd[(size_t) (blk * 256)] = 127.0f; // fixes max = 127 - bad_k += run_case_k("exact .5 ties (half-to-even)", kd, true); - { - // assert the tie fixture can SEE the difference before trusting the comparison above - std::vector rb; - std::vector rback; - reference_q8_K(kd.data(), NK, rb, rback, -127.0f); - long long ties = 0, differ = 0; - for (long long i = 0; i < NK; ++i) { - const float t = -kd[(size_t) i]; - if (t - std::floor(t) == 0.5f) { - ++ties; - const int even = nearest_int_host(t); - const int away = (int) std::round(t); - if (even != away) ++differ; - } - } - std::printf(" %-26s %lld ties, %lld where half-to-even != half-away (%.1f%%)\n", - " tie fixture discriminates", ties, differ, ties ? 100.0 * (double) differ / ties : 0.0); - if (differ < ties / 3) { std::printf(" *** the tie fixture cannot see the rounding rule ***\n"); ++bad_k; } - } - - // THE -127 TRAP. ggml uses `-127/max`; the `-128` version sits COMMENTED OUT in the source, and using it - // is a 0.79% scaling error that leaves a working-looking activation. Computed with the rival constant - // and required to differ. - { - std::vector r127, r128; - std::vector b127, b128; - reference_q8_K(ka.data(), NK, r127, b127, -127.0f); - reference_q8_K(ka.data(), NK, r128, b128, -128.0f); - double d = 0, m = 0; - long long qdiffer = 0; - for (long long i = 0; i < NK; ++i) { d += std::fabs(b127[(size_t) i] - b128[(size_t) i]); m += std::fabs(b127[(size_t) i]); } - for (size_t i = 4; i < r127.size(); ++i) if (r127[i] != r128[i]) ++qdiffer; - // The expected size of the effect is exactly (1 - 127/128) = 0.78% of the magnitude, so the floor is - // 0.5% - below what the rival constant must produce and far above any noise. The byte count is the - // blunter evidence and is reported alongside it: 172,017 bytes differ, i.e. a third of the quants. - std::printf(" %-26s %-4s (%.3f%% of magnitude, %lld bytes differ)\n", "-127 vs -128 scale observable", - d / m > 0.005 ? "yes" : "*** NO ***", 100.0 * d / m, qdiffer); - if (!(d / m > 0.005)) ++bad_k; - } - - std::printf("\nquantize_act: %d failures over 5 Q8_0 + 4 Q8_K distributions\n", bad + bad_k); - if (bad + bad_k) return 1; - if (selftest) std::printf("quantize_act_parity OK\n"); - return 0; -} diff --git a/src/kernels/qwen36_seam_parity.cpp b/src/kernels/qwen36_seam_parity.cpp deleted file mode 100644 index 3352cb5..0000000 --- a/src/kernels/qwen36_seam_parity.cpp +++ /dev/null @@ -1,526 +0,0 @@ -// src/kernels/qwen36_seam_parity.cpp - Qwen3.6 step 3 (GDN, router, shared expert): the engine's DECODE kernels -// held to the numpy oracle's seams, by llama.cpp's cb() names, on the synthetic fixture. -// -// qwen36_seam_parity 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 - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -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& a, const std::vector& 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(a, a + n), std::vector(b, b + n)); -} - -std::vector 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 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 -T* dev(const std::vector& 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 -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 -std::vector host(const T* d, size_t n, const char* what) { - std::vector 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 bytes; - std::vector ne; - uint32_t type = 0; - const float* f32() const { return (const float*) bytes.data(); } - std::vector floats() const { return std::vector(f32(), f32() + bytes.size() / 4); } -}; -Tensor tensor(const strata::GgufFile& g, const std::string& name, const std::vector& 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 to_bf16(const std::vector& f) { - std::vector 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 oracle_state_to_engine(const std::vector& o) { - std::vector 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 conv_w, ssm_norm, ssm_a, dt, alpha_w, beta_w; - std::vector alpha_bf16, beta_bf16, ginp_bf16; - std::vector sh_gate, sh_up, sh_down; - // oracle inputs and seams - std::vector 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((size_t) C * (DC - 1), "hist"); - d.state = dev_zero((size_t) S * HV * S, "state"); - d.qkv_t = dev_zero(C, "qkv"); - d.conv_out = dev_zero(C, "conv_out"); - d.h = dev_zero(C, "h"); - d.alpha = dev_zero(HV, "alpha"); - d.beta = dev_zero(HV, "beta"); - d.gate = dev_zero(HV, "gate"); - d.o = dev_zero(V, "o"); - d.z_t = dev_zero(V, "z"); - d.y = dev_zero(V, "y"); - d.x_t = dev_zero(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 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((size_t) T * C, "h_all"); - float* gate_all = dev_zero((size_t) T * HV, "gate_all"); - float* beta_all = dev_zero((size_t) T * HV, "beta_all"); - float* y_all = dev_zero((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 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 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((size_t) T * K, "ids"); - float* d_w = dev_zero((size_t) T * K, "w"); - strata::kernels::router_top10(d_l, T, E, K, d_ids, d_w, nullptr); - const std::vector ids = host(d_ids, (size_t) T * K, "ids"); - const std::vector 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((size_t) T * N, "x_bf16"); - f32_to_bf16_bulk(d_x, d_xb, (int64_t) T * N, cs); - float* d_scratch = dev_zero(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(q81, "q8_1"); - float* d_out = dev_zero((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 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((size_t) kVerifyMaxT * FF_SH, "g"); - float* d_u = dev_zero((size_t) kVerifyMaxT * FF_SH, "u"); - float* d_s = dev_zero(kVerifyMaxT, "s"); - float* d_out2 = dev_zero((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 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 \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; -} diff --git a/src/kernels/rope_parity.cpp b/src/kernels/rope_parity.cpp deleted file mode 100644 index 39ba116..0000000 --- a/src/kernels/rope_parity.cpp +++ /dev/null @@ -1,442 +0,0 @@ -// src/kernels/rope_parity.cpp - P2.S2's parity test for NEOX partial RoPE. -// -// TWO CHECKS, deliberately separated so each can be tight: -// -// 1. THE TABLE against the float64 reference - `theta ** (-2i/n_rot)`, `pos * inv`, `cos`/`sin`, all in -// double exactly as `ref/qsa.py::rope_freqs` does. Compared as float32 after the cast, so a mismatch -// here is a real arithmetic difference and not a formatting one. -// 2. THE ROTATION against a host rotation written from `ref/qsa.py::rope_neox`, using the SAME table the -// kernel is given. Both sides then perform identical float32 operations, so this is BIT-EXACT - and a -// bit-exact rotation plus a table that matches the reference means the composition matches too. -// -// A single end-to-end comparison would have had to carry one loose tolerance for both, and the interesting -// failure - the NEOX pairing being wrong - is a PERMUTATION that a loose tolerance over all 256 dims would -// happily accept. -// -// Check 4 extends the same discipline to the SCALED tables (rope scaling: none/linear/YaRN). The rotation -// kernel cannot see scaling - it lives in the table contents - so each variant's TABLE is held to a float64 -// transcription of ggml's `rope_yarn` spec (the ramp helper is shared, the `rope_neox_pair` convention), and -// the two properties a tolerance could never fake get their own structural checks: at position 0 every pair's -// angle is 0, so YaRN's mscale stands naked in cos_tab[0], and at a far position the first pair must match -// EXTRAPOLATION while the last matches INTERPOLATION. An observability assertion closes it: if the scaled -// and unscaled tables were indistinguishable, every green number above would be vacuous. -// -// Check 5 holds the TWO PATHS together: the table path's float64 host trig and the native path's float32 -// fast-math device trig must answer to the same `RopeScaling`, yarn and none alike, so one cache never -// mixes two rotations. -#include "strata/kernels/rope.hpp" -#include "strata/kernels/native_rope.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace { - -void check(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -} // namespace - -int main(int argc, char** argv) { - bool selftest = false; - for (int i = 1; i < argc; ++i) { - if (std::string(argv[i]) == "--selftest") selftest = true; - else { std::fprintf(stderr, "usage: rope_parity [--selftest]\n"); return 2; } - } - - const int n_rot = 64; // the artifact's rope.dimension_count - const double theta = 1.0e7; // rope.freq_base - const int head_dim = 256; - const int rows = 24 * 8; // 24 heads over 8 positions, so several positions exercise the table - const int max_pos = 32; - const int half = n_rot / 2; - int bad = 0; - - // ---- 1. the table against the float64 reference - std::vector hcos((size_t) max_pos * half), hsin((size_t) max_pos * half); - strata::kernels::build_rope_table(n_rot, theta, max_pos, hcos.data(), hsin.data()); - long long table_bad = 0; - double table_worst = 0.0; - for (int p = 0; p < max_pos; ++p) { - for (int i = 0; i < half; ++i) { - const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot); - const double ang = (double) p * inv; - const float rc = (float) std::cos(ang), rs = (float) std::sin(ang); - if (std::memcmp(&rc, &hcos[(size_t) p * half + i], 4) != 0) ++table_bad; - if (std::memcmp(&rs, &hsin[(size_t) p * half + i], 4) != 0) ++table_bad; - table_worst = std::max(table_worst, - std::fabs((double) rc - (double) hcos[(size_t) p * half + i])); - } - } - std::printf(" rope table vs float64 reference %s (%lld of %d entries differ, worst %.1e)\n", - table_bad ? "*** WRONG ***" : "bit-exact", table_bad, max_pos * half * 2, table_worst); - bad += (int) table_bad; - - // ---- 2. the rotation, against the same spec in float32 with the SAME table - std::mt19937 rng(11); - std::normal_distribution gauss(0.0f, 1.0f); - std::vector x((size_t) rows * head_dim); - for (auto& v : x) v = gauss(rng); - std::vector pos((size_t) rows); - for (int r = 0; r < rows; ++r) pos[(size_t) r] = r % max_pos; - - std::vector ref(x.size()); - for (int r = 0; r < rows; ++r) { - const float* xr = &x[(size_t) r * head_dim]; - float* orow = &ref[(size_t) r * head_dim]; - for (int d = 0; d < head_dim; ++d) orow[d] = xr[d]; // the tail passes through - for (int i = 0; i < half; ++i) { - const float c = hcos[(size_t) pos[(size_t) r] * half + i]; - const float s = hsin[(size_t) pos[(size_t) r] * half + i]; - const float a = xr[i], b = xr[half + i]; - orow[i] = a * c - b * s; - orow[half + i] = a * s + b * c; - } - } - - float *d_x = nullptr, *d_out = nullptr, *d_cos = nullptr, *d_sin = nullptr; - int* d_pos = nullptr; - check(cudaMalloc(&d_x, x.size() * sizeof(float)), "malloc x"); - check(cudaMalloc(&d_out, ref.size() * sizeof(float)), "malloc out"); - check(cudaMalloc(&d_cos, hcos.size() * sizeof(float)), "malloc cos"); - check(cudaMalloc(&d_sin, hsin.size() * sizeof(float)), "malloc sin"); - check(cudaMalloc(&d_pos, pos.size() * sizeof(int)), "malloc pos"); - check(cudaMemcpy(d_x, x.data(), x.size() * sizeof(float), cudaMemcpyHostToDevice), "copy x"); - check(cudaMemcpy(d_cos, hcos.data(), hcos.size() * sizeof(float), cudaMemcpyHostToDevice), "copy cos"); - check(cudaMemcpy(d_sin, hsin.data(), hsin.size() * sizeof(float), cudaMemcpyHostToDevice), "copy sin"); - check(cudaMemcpy(d_pos, pos.data(), pos.size() * sizeof(int), cudaMemcpyHostToDevice), "copy pos"); - strata::kernels::rope_neox_apply(d_x, d_out, rows, head_dim, n_rot, d_cos, d_sin, d_pos, nullptr); - std::vector got(ref.size()); - check(cudaMemcpy(got.data(), d_out, got.size() * sizeof(float), cudaMemcpyDeviceToHost), "back"); - - // A RELATIVE TOLERANCE, NOT BIT EQUALITY. *c - b*s is one of the expressions the compiler is free to - // contract into an FMA, and the host and device compilers choose differently - so a handful of values - // differ in the last bit. Round 167 established this the hard way: a bit-equality expectation that a - // kernel cannot meet is a test that reports a correct kernel as broken. The residual is reported, and if - // it were structural (a wrong pairing, a wrong table entry) it would be O(1), not O(1 ULP). - long long rot_bad = 0; - double worst = 0.0; - long long first_bad = -1; - // The denominator is the ROW'S INPUT MAGNITUDE, not the element's own value. *c - b*s cancels, so an - // element whose result is near zero reports a large relative error for a 1-ULP absolute one - which is the - // same metric mistake round 169 found on Q4_K's dot products, where the fix was to measure against - // sum|term| instead of the result. Here the natural scale of the computation is the largest input in the - // row, because every output element is a combination of two inputs with |cos|,|sin| <= 1. - std::vector row_scale((size_t) rows, 0.0); - for (int r = 0; r < rows; ++r) { - double m = 0; - for (int d = 0; d < head_dim; ++d) m = std::max(m, (double) std::fabs(x[(size_t) r * head_dim + d])); - row_scale[(size_t) r] = m > 1e-30 ? m : 1e-30; - } - for (size_t i = 0; i < ref.size(); ++i) { - const double a = ref[i], b = got[i]; - const double rel = std::fabs(a - b) / row_scale[i / (size_t) head_dim]; - if (!(rel <= worst)) worst = rel; - if (!(rel <= 1e-6)) { if (first_bad < 0) first_bad = (long long) i; ++rot_bad; } - } - std::printf(" rope rotation vs host reference %s (%lld of %zu over 1e-6, worst rel %.3e)\n", - rot_bad ? "*** WRONG ***" : "agrees", rot_bad, ref.size(), worst); - if (first_bad >= 0) std::printf(" first over-tolerance at element %lld\n", first_bad); - bad += (int) rot_bad; - - // ---- 3. THE PAIRING, asserted structurally rather than as a tolerance. NEOX pairs (i, i+half); the - // adjacent-pair convention would pair (2i, 2i+1). Feed an input that is 1 at dim 0 and 0 elsewhere, and - // check WHICH dims move: under NEOX only dims 0 and half may change, under the adjacent convention only - // dims 0 and 1 may. A tolerance over all 256 dims cannot tell the two apart. - { - std::vector e((size_t) head_dim, 0.0f); - e[0] = 1.0f; - std::vector o((size_t) head_dim, 0.0f); - check(cudaMemcpy(d_x, e.data(), e.size() * sizeof(float), cudaMemcpyHostToDevice), "copy e"); - // position 7, NOT position 0: at pos 0 sin is exactly 0, so dim half legitimately does not move and - // the check would report the correct kernel as wrong. The first version made exactly that mistake. - int p7 = 7; - check(cudaMemcpy(d_pos, &p7, sizeof(int), cudaMemcpyHostToDevice), "copy p7"); - strata::kernels::rope_neox_apply(d_x, d_out, 1, head_dim, n_rot, d_cos, d_sin, d_pos, nullptr); - check(cudaMemcpy(o.data(), d_out, o.size() * sizeof(float), cudaMemcpyDeviceToHost), "back e"); - int moved[4] = {0, 0, 0, 0}; // dims 0, 1, half, half+1 - const float* chk[4] = {&e[0], &e[1], &e[half], &e[half + 1]}; - (void) chk; - moved[0] = (o[0] != 0.0f || o[half] != 0.0f) ? 1 : 0; - const bool adjacent_moved = (o[1] != 0.0f); - const bool neox_moved = (o[half] != 0.0f); - std::printf(" pairing: dim 0 set -> NEOX moves dim %d (o[half]=%.6f), adjacent would move dim 1 " - "(o[1]=%.6f) %s\n", half, (double) o[half], (double) o[1], - (neox_moved && !adjacent_moved) ? "NEOX confirmed" : "*** WRONG CONVENTION ***"); - if (!(neox_moved && !adjacent_moved)) ++bad; - } - - // ---- 4. THE SCALED TABLES (rope_scaling.hpp). Scaling lives in the table contents, so each variant is - // a table check: a float64 transcription of the ggml spec, bit-exact after the float32 cast, plus the - // structural and observability checks the tolerances cannot cover. - { - // 4a. type None IS the five-argument builder above - bit for bit. - std::vector nc((size_t) max_pos * half), ns((size_t) max_pos * half); - strata::kernels::RopeScaling none; - none.freq_base = theta; - strata::kernels::build_rope_table(n_rot, none, max_pos, nc.data(), ns.data()); - const long long none_bad = - (long long) (std::memcmp(nc.data(), hcos.data(), nc.size() * 4) != 0) + - (long long) (std::memcmp(ns.data(), hsin.data(), ns.size() * 4) != 0); - std::printf(" scaled table, None vs unscaled builder %s\n", none_bad ? "*** WRONG ***" : "bit-identical"); - bad += (int) none_bad; - - // 4b. LINEAR, factor 4: `ang = p * inv / 4` in float64. The factor is a power of two on purpose - - // dividing by it is exact, so no multiplication-order rounding can sneak between spec and builder. - strata::kernels::RopeScaling lin; - lin.type = strata::kernels::RopeScalingType::Linear; - lin.freq_base = theta; - lin.factor = 4.0; - std::vector lc((size_t) max_pos * half), ls((size_t) max_pos * half); - strata::kernels::build_rope_table(n_rot, lin, max_pos, lc.data(), ls.data()); - long long lin_bad = 0; - for (int p = 0; p < max_pos; ++p) { - for (int i = 0; i < half; ++i) { - const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot); - const double ang = (double) p * inv / 4.0; - const float rc = (float) std::cos(ang), rs = (float) std::sin(ang); - if (std::memcmp(&rc, &lc[(size_t) p * half + i], 4) != 0) ++lin_bad; - if (std::memcmp(&rs, &ls[(size_t) p * half + i], 4) != 0) ++lin_bad; - } - } - std::printf(" scaled table, linear factor 4 %s (%lld of %d entries differ)\n", - lin_bad ? "*** WRONG ***" : "bit-exact", lin_bad, max_pos * half * 2); - bad += (int) lin_bad; - - // 4c. THE INTERPOLATION CLAIM ITSELF: linear(4) at position p is `none` at p/4 - the same table row, - // bit for bit, at every position divisible by the factor. - std::vector wc((size_t) 4 * max_pos * half), ws((size_t) 4 * max_pos * half); - strata::kernels::build_rope_table(n_rot, lin, 4 * max_pos, wc.data(), ws.data()); - long long equiv_bad = 0; - for (int p = 0; p < 4 * max_pos; p += 4) { - for (int i = 0; i < half; ++i) { - if (std::memcmp(&wc[(size_t) p * half + i], &hcos[(size_t) (p / 4) * half + i], 4) != 0) ++equiv_bad; - if (std::memcmp(&ws[(size_t) p * half + i], &hsin[(size_t) (p / 4) * half + i], 4) != 0) ++equiv_bad; - } - } - std::printf(" linear(4) @ p == none @ p/4 %s (%lld of %d rows differ)\n", - equiv_bad ? "*** WRONG ***" : "bit-identical", equiv_bad, max_pos); - bad += (int) equiv_bad; - - // 4d. YARN vs a float64 transcription of ggml's rope_yarn (factor 4, the default correction knobs). - // The ramp helper is shared with the builder (the rope_neox_pair convention: one definition, not two - // transcriptions of it); the interpolation mix and the mscale formula are written here from the ggml - // source lines, which is the spec being tested. - strata::kernels::RopeScaling yarn; - yarn.type = strata::kernels::RopeScalingType::YaRN; - yarn.freq_base = theta; - yarn.factor = 4.0; - yarn.ext_factor = 1.0; - std::vector yc((size_t) max_pos * half), ys((size_t) max_pos * half); - strata::kernels::build_rope_table(n_rot, yarn, max_pos, yc.data(), ys.data()); - const double fs = yarn.freq_scale(); // 0.25 - const double ms = yarn.mscale(); // attn_factor * (1 + 0.1*ln(4)) - double cd[2]; - yarn.corr_dims(n_rot, cd); - long long yarn_bad = 0; - for (int p = 0; p < max_pos; ++p) { - for (int i = 0; i < half; ++i) { - const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot); - const double extrap = (double) p * inv; - const double interp = fs * extrap; - const double ramp = (double) strata::kernels::rope_yarn_ramp((float) cd[0], (float) cd[1], i) * - yarn.ext_factor; - const double ang = interp * (1.0 - ramp) + extrap * ramp; - const float rc = (float) (std::cos(ang) * ms), rs = (float) (std::sin(ang) * ms); - if (std::memcmp(&rc, &yc[(size_t) p * half + i], 4) != 0) ++yarn_bad; - if (std::memcmp(&rs, &ys[(size_t) p * half + i], 4) != 0) ++yarn_bad; - } - } - std::printf(" scaled table, yarn factor 4 %s (%lld of %d entries differ)\n", - yarn_bad ? "*** WRONG ***" : "bit-exact", yarn_bad, max_pos * half * 2); - bad += (int) yarn_bad; - - // 4e. THE STRUCTURE a tolerance cannot fake. At position 0 every pair's angle is 0, so YaRN's whole - // magnitude correction stands naked: cos_tab[0] == mscale. At the far end of the table the first - // pair (the highest trained frequency) must match EXTRAPOLATION and the last INTERPOLATION. The two - // halves need different observables: at the first pair cos separates the hypotheses outright, but at - // the last they differ by ~4 microradians here, invisible to cos near 1 - sin sees it, because near - // zero sin IS the angle. That asymmetry is the YaRN design: interpolation happens where angles are - // small. Both hypotheses go through the same mix formula the builder uses, so the bit comparison is - // spec against spec, not shortcut against implementation. - { - const float msv = (float) ms; - const bool zero_ok = std::memcmp(&msv, &yc[0], 4) == 0 && ys[0] == 0.0f; - const int far = max_pos - 1; - const double inv_f = 1.0; // pair 0: theta ** 0 - const double extrap_f = (double) far * inv_f, interp_f = fs * extrap_f; - const double inv_l = std::pow(theta, -2.0 * (double) (half - 1) / (double) n_rot); - const double extrap_l = (double) far * inv_l, interp_l = fs * extrap_l; - const float ef = (float) (std::cos(interp_f * (1.0 - 1.0) + extrap_f * 1.0) * ms); - const float itf = (float) (std::cos(interp_f * (1.0 - 0.0) + extrap_f * 0.0) * ms); - const float sl_e = (float) (std::sin(interp_l * (1.0 - 1.0) + extrap_l * 1.0) * ms); - const float sl_i = (float) (std::sin(interp_l * (1.0 - 0.0) + extrap_l * 0.0) * ms); - const float got_f = yc[(size_t) far * half], got_l = ys[(size_t) far * half + (half - 1)]; - const bool first_extrapolates = std::memcmp(&got_f, &ef, 4) == 0; - const bool last_interpolates = std::memcmp(&got_l, &sl_i, 4) == 0; - const bool distinguishable = std::fabs((double) ef - (double) itf) > 1e-3 && - std::fabs((double) sl_e - (double) sl_i) > 1e-8; - std::printf(" yarn structure: cos_tab[0]==mscale %.4f, first pair extrapolates, last interpolates " - "%s\n", (double) msv, - zero_ok && first_extrapolates && last_interpolates && distinguishable - ? "confirmed" - : "*** WRONG ***"); - if (!(zero_ok && first_extrapolates && last_interpolates && distinguishable)) ++bad; - } - - // 4f. THE OBSERVABILITY assertion: the fixtures must SEE scaling. If the builder ignored its config, - // linear(2) would equal `none` everywhere and 4b-4e would be green on a broken builder. - { - strata::kernels::RopeScaling lin2; - lin2.type = strata::kernels::RopeScalingType::Linear; - lin2.freq_base = theta; - lin2.factor = 2.0; - std::vector l2c((size_t) 101 * half), l2s((size_t) 101 * half); - strata::kernels::build_rope_table(n_rot, lin2, 101, l2c.data(), l2s.data()); - const float c_none = (float) std::cos(100.0); // pair 0, position 100, unscaled: ang = 100 - const float c_lin = l2c[(size_t) 100 * half]; // pair 0, position 100, linear(2): ang = 50 - const bool sees = std::fabs((double) c_none - (double) c_lin) > 1e-3; - std::printf(" observability: none vs linear(2) at position 100 %s (|%.4f - %.4f|)\n", - sees ? "visible" : "*** VACUUM ***", (double) c_none, (double) c_lin); - if (!sees) ++bad; - } - - // 4g. THE ROTATION under a scaled table. The kernel is table-agnostic and must not know or care: - // the host reference is the same rope_neox_pair walk as check 2, over the YaRN table. - std::vector ref2(x.size()); - for (int r = 0; r < rows; ++r) { - const float* xr = &x[(size_t) r * head_dim]; - float* orow = &ref2[(size_t) r * head_dim]; - for (int d = 0; d < head_dim; ++d) orow[d] = xr[d]; - for (int i = 0; i < half; ++i) { - float c = yc[(size_t) pos[(size_t) r] * half + i], s = ys[(size_t) pos[(size_t) r] * half + i]; - strata::kernels::rope_neox_pair(xr[i], xr[half + i], c, s, orow[i], orow[half + i]); - } - } - check(cudaMemcpy(d_x, x.data(), x.size() * sizeof(float), cudaMemcpyHostToDevice), "copy x"); - check(cudaMemcpy(d_cos, yc.data(), yc.size() * sizeof(float), cudaMemcpyHostToDevice), "copy ycos"); - check(cudaMemcpy(d_sin, ys.data(), ys.size() * sizeof(float), cudaMemcpyHostToDevice), "copy ysin"); - check(cudaMemcpy(d_pos, pos.data(), pos.size() * sizeof(int), cudaMemcpyHostToDevice), "copy pos"); - strata::kernels::rope_neox_apply(d_x, d_out, rows, head_dim, n_rot, d_cos, d_sin, d_pos, nullptr); - std::vector got2(ref2.size()); - check(cudaMemcpy(got2.data(), d_out, got2.size() * sizeof(float), cudaMemcpyDeviceToHost), "back"); - long long rot2_bad = 0; - double worst2 = 0.0; - for (size_t i = 0; i < ref2.size(); ++i) { - const double a = ref2[i], b = got2[i]; - const double rel = std::fabs(a - b) / row_scale[i / (size_t) head_dim]; - worst2 = std::max(worst2, rel); - if (!(rel <= 1e-6)) ++rot2_bad; - } - std::printf(" rope rotation over the yarn table %s (%lld of %zu over 1e-6, worst rel %.3e)\n", - rot2_bad ? "*** WRONG ***" : "agrees", rot2_bad, ref2.size(), worst2); - bad += (int) rot2_bad; - } - - // ---- 5. THE TWO PATHS MUST AGREE. The table path (the default) computes cos/sin on the host in float64; - // the native path (`--native-rope`) computes the same angles on device in float32 under `--use_fast_math`. - // They answer to ONE config - `RopeScaling` - and a disagreement between them would put differently-rotated - // K into the cache depending on which path ran. The tolerance is NOT the 1e-6 of checks 2/4g: the device - // side takes fast-math trig at angles up to ~2048 rad, where the fp32 range reduction alone is worth ~1e-4, - // so the bar is the row-magnitude-relative 3e-3 and the test keeps the positions where that holds. (The - // engine's default is the table path precisely because float64 host trig has no such floor.) - { - const int npos = 2048; - strata::kernels::RopeScaling yarn; - yarn.type = strata::kernels::RopeScalingType::YaRN; - yarn.factor = 2.0; - yarn.ext_factor = 1.0; - std::vector sc((size_t) npos * half), ss((size_t) npos * half); - strata::kernels::build_rope_table(n_rot, yarn, npos, sc.data(), ss.data()); - std::mt19937 rng2(23); - std::normal_distribution gauss2(0.0f, 1.0f); - const int nrows = 24 * 16; // 16 positions spread over the table's range - std::vector x2((size_t) nrows * head_dim); - for (auto& v : x2) v = gauss2(rng2); - std::vector pos2((size_t) nrows); - for (int r = 0; r < nrows; ++r) pos2[(size_t) r] = (r * 127) % npos; - - float *d_x2 = nullptr, *d_t2 = nullptr, *d_n2 = nullptr, *d_c2 = nullptr, *d_s2 = nullptr; - int* d_p2 = nullptr; - check(cudaMalloc(&d_x2, x2.size() * sizeof(float)), "malloc x2"); - check(cudaMalloc(&d_t2, x2.size() * sizeof(float)), "malloc t2"); - check(cudaMalloc(&d_n2, x2.size() * sizeof(float)), "malloc n2"); - check(cudaMalloc(&d_c2, sc.size() * sizeof(float)), "malloc c2"); - check(cudaMalloc(&d_s2, ss.size() * sizeof(float)), "malloc s2"); - check(cudaMalloc(&d_p2, pos2.size() * sizeof(int)), "malloc p2"); - check(cudaMemcpy(d_x2, x2.data(), x2.size() * sizeof(float), cudaMemcpyHostToDevice), "copy x2"); - check(cudaMemcpy(d_c2, sc.data(), sc.size() * sizeof(float), cudaMemcpyHostToDevice), "copy c2"); - check(cudaMemcpy(d_s2, ss.data(), ss.size() * sizeof(float), cudaMemcpyHostToDevice), "copy s2"); - check(cudaMemcpy(d_p2, pos2.data(), pos2.size() * sizeof(int), cudaMemcpyHostToDevice), "copy p2"); - // The native path demands an explicit stream - a null one is refused by validation, not defaulted. - cudaStream_t cs5 = nullptr; - check(cudaStreamCreate(&cs5), "stream5"); - strata::kernels::rope_neox_apply(d_x2, d_t2, nrows, head_dim, n_rot, d_c2, d_s2, d_p2, nullptr); - strata::kernels::native_rope_apply(d_x2, d_n2, nrows, head_dim, n_rot, yarn, d_p2, cs5); - check(cudaStreamSynchronize(cs5), "sync5"); - std::vector got_t(x2.size()), got_n(x2.size()); - check(cudaMemcpy(got_t.data(), d_t2, got_t.size() * sizeof(float), cudaMemcpyDeviceToHost), "back t2"); - check(cudaMemcpy(got_n.data(), d_n2, got_n.size() * sizeof(float), cudaMemcpyDeviceToHost), "back n2"); - long long agree_bad = 0; - double worst = 0.0; - for (int r = 0; r < nrows; ++r) { - double m = 0; - for (int d = 0; d < head_dim; ++d) m = std::max(m, (double) std::fabs(x2[(size_t) r * head_dim + d])); - const double scale = m > 1e-30 ? m : 1e-30; - for (int d = 0; d < head_dim; ++d) { - const double rel = std::fabs((double) got_t[(size_t) r * head_dim + d] - - (double) got_n[(size_t) r * head_dim + d]) / scale; - worst = std::max(worst, rel); - if (!(rel <= 3e-3)) ++agree_bad; - } - } - std::printf(" native path vs table path, yarn factor 2 %s (%lld of %d over 3e-3, worst rel %.3e)\n", - agree_bad ? "*** WRONG ***" : "agrees", agree_bad, nrows * head_dim, worst); - bad += (int) agree_bad; - - // and the None config: the native path against the UNSCALED table - the identity this feature must - // not disturb. - strata::kernels::RopeScaling none5; // all defaults: type None, freq_scale 1, mscale 1 - strata::kernels::native_rope_apply(d_x2, d_n2, nrows, head_dim, n_rot, none5, d_p2, cs5); - check(cudaStreamSynchronize(cs5), "sync5b"); - check(cudaMemcpy(got_n.data(), d_n2, got_n.size() * sizeof(float), cudaMemcpyDeviceToHost), "back n2b"); - std::vector nc5((size_t) npos * half), ns5((size_t) npos * half); - strata::kernels::build_rope_table(n_rot, none5, npos, nc5.data(), ns5.data()); - check(cudaMemcpy(d_c2, nc5.data(), nc5.size() * sizeof(float), cudaMemcpyHostToDevice), "copy c2b"); - check(cudaMemcpy(d_s2, ns5.data(), ns5.size() * sizeof(float), cudaMemcpyHostToDevice), "copy s2b"); - strata::kernels::rope_neox_apply(d_x2, d_t2, nrows, head_dim, n_rot, d_c2, d_s2, d_p2, nullptr); - check(cudaMemcpy(got_t.data(), d_t2, got_t.size() * sizeof(float), cudaMemcpyDeviceToHost), "back t2b"); - long long none_bad5 = 0; - double worst5 = 0.0; - for (int r = 0; r < nrows; ++r) { - double m = 0; - for (int d = 0; d < head_dim; ++d) m = std::max(m, (double) std::fabs(x2[(size_t) r * head_dim + d])); - const double scale = m > 1e-30 ? m : 1e-30; - for (int d = 0; d < head_dim; ++d) { - const double rel = std::fabs((double) got_t[(size_t) r * head_dim + d] - - (double) got_n[(size_t) r * head_dim + d]) / scale; - worst5 = std::max(worst5, rel); - if (!(rel <= 3e-3)) ++none_bad5; - } - } - std::printf(" native path vs table path, none %s (%lld of %d over 3e-3, worst rel %.3e)\n", - none_bad5 ? "*** WRONG ***" : "agrees", none_bad5, nrows * head_dim, worst5); - bad += (int) none_bad5; - } - - std::printf("\nrope: %d failures\n", bad); - if (bad) return 1; - if (selftest) std::printf("rope_parity OK\n"); - return 0; -} diff --git a/src/kernels/route_window_parity.cpp b/src/kernels/route_window_parity.cpp deleted file mode 100644 index bb0d6b9..0000000 --- a/src/kernels/route_window_parity.cpp +++ /dev/null @@ -1,75 +0,0 @@ -// route_window_parity - the verify window's batched routing against the per-token calls, bit for bit. -// -// `moe_route_window` replaces n per-token (projection + top-k) pairs by one multi-column BF16 projection and one -// n-token top-k. Speculative decoding is exact only if a token's route does not depend on how many tokens share -// its window, so both batched kernels must equal their one-token forms exactly - this checks that on random data -// shaped like the router (2560 -> 256, top-10) and like the shared-expert gate (2560 -> 1). -#include "strata/kernels/bf16_gemv.hpp" -#include "strata/kernels/router_top10.hpp" - -#include - -#include -#include -#include -#include -#include - -namespace { -void ck(cudaError_t e, const char* what) { - if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(2); } -} -uint16_t bf16(float f) { uint32_t i; std::memcpy(&i, &f, 4); return (uint16_t) ((i + ((i >> 16) & 1u) + 0x7FFFu) >> 16); } -} // namespace - -int main() { - const int N = 2560, E = 256, K = 10; - int bad = 0; - std::mt19937 rng(7); - std::normal_distribution nd(0.0f, 1.0f); - for (int n_out : {E, 1}) { - for (int T : {2, 3, 4, 6}) { - std::vector w((size_t) n_out * N); - std::vector x((size_t) T * N); - for (auto& v : w) v = bf16(nd(rng) * 0.05f); - for (auto& v : x) v = nd(rng); - uint16_t* dw; float *dx, *dy1, *dyn; - ck(cudaMalloc(&dw, w.size() * 2), "w"); ck(cudaMalloc(&dx, x.size() * 4), "x"); - ck(cudaMalloc(&dy1, (size_t) T * n_out * 4), "y1"); ck(cudaMalloc(&dyn, (size_t) T * n_out * 4), "yn"); - ck(cudaMemcpy(dw, w.data(), w.size() * 2, cudaMemcpyHostToDevice), "up w"); - ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "up x"); - for (int t = 0; t < T; ++t) - strata::kernels::bf16_gemv_fp32_mmvf(dx + (size_t) t * N, dw, dy1 + (size_t) t * n_out, N, n_out, nullptr); - strata::kernels::bf16_gemv_fp32_mmvf_cols(dx, dw, dyn, N, n_out, T, nullptr); - ck(cudaDeviceSynchronize(), "sync"); - std::vector y1((size_t) T * n_out), yn((size_t) T * n_out); - ck(cudaMemcpy(y1.data(), dy1, y1.size() * 4, cudaMemcpyDeviceToHost), "down 1"); - ck(cudaMemcpy(yn.data(), dyn, yn.size() * 4, cudaMemcpyDeviceToHost), "down n"); - const bool same = std::memcmp(y1.data(), yn.data(), y1.size() * 4) == 0; - std::printf(" mmvf cols n_out %3d T %d %s\n", n_out, T, same ? "bit-identical" : "*** DIFFERS ***"); - if (!same) ++bad; - if (n_out == E) { - int *i1, *in_; float *w1, *wn; - ck(cudaMalloc(&i1, (size_t) T * K * 4), "i1"); ck(cudaMalloc(&in_, (size_t) T * K * 4), "in"); - ck(cudaMalloc(&w1, (size_t) T * K * 4), "w1"); ck(cudaMalloc(&wn, (size_t) T * K * 4), "wn"); - for (int t = 0; t < T; ++t) - strata::kernels::router_top10(dy1 + (size_t) t * E, 1, E, K, i1 + t * K, w1 + t * K, nullptr); - strata::kernels::router_top10(dy1, T, E, K, in_, wn, nullptr); - ck(cudaDeviceSynchronize(), "sync top"); - std::vector a((size_t) T * K), b((size_t) T * K); - std::vector fa((size_t) T * K), fb((size_t) T * K); - ck(cudaMemcpy(a.data(), i1, a.size() * 4, cudaMemcpyDeviceToHost), "ids1"); - ck(cudaMemcpy(b.data(), in_, b.size() * 4, cudaMemcpyDeviceToHost), "idsn"); - ck(cudaMemcpy(fa.data(), w1, fa.size() * 4, cudaMemcpyDeviceToHost), "w1"); - ck(cudaMemcpy(fb.data(), wn, fb.size() * 4, cudaMemcpyDeviceToHost), "wn"); - const bool s2 = a == b && std::memcmp(fa.data(), fb.data(), fa.size() * 4) == 0; - std::printf(" top10 n T %d %s\n", T, s2 ? "bit-identical" : "*** DIFFERS ***"); - if (!s2) ++bad; - cudaFree(i1); cudaFree(in_); cudaFree(w1); cudaFree(wn); - } - cudaFree(dw); cudaFree(dx); cudaFree(dy1); cudaFree(dyn); - } - } - std::printf(bad ? "route_window_parity: %d FAILURES\n" : "route_window_parity OK\n", bad); - return bad ? 1 : 0; -} diff --git a/src/kernels/router_top10_parity.cpp b/src/kernels/router_top10_parity.cpp deleted file mode 100644 index 6bc77ba..0000000 --- a/src/kernels/router_top10_parity.cpp +++ /dev/null @@ -1,186 +0,0 @@ -// src/kernels/router_top10_parity.cpp - P2.S2's parity test for the MoE router. -// -// The reference here is a HOST implementation of `ref/moe.py::router` written from the same specification the -// kernel was written from - so this checks the kernel against the spec independently of the kernel, which is -// the strongest thing available without running llama.cpp. It is NOT a check against llama.cpp itself, and -// that gap is stated rather than implied. -// -// WHAT THE TEST CAN AND CANNOT SEE. It compares expert IDs exactly and weights to a tolerance, on several -// 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 - -#include -#include -#include -#include -#include -#include -#include - -namespace { - -void check(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -constexpr double RENORM_CLAMP = 6.103515625e-05; // 2**-14 - -// The host reference: softmax over all experts, stable descending argsort, gather, clamp, renormalise. -void reference(const float* logits, int n_expert, int k, int* ids, float* w) { - double mx = logits[0]; - for (int e = 1; e < n_expert; ++e) mx = std::max(mx, (double) logits[e]); - double sum = 0; - std::vector p((size_t) n_expert); - for (int e = 0; e < n_expert; ++e) { - p[(size_t) e] = std::exp((double) logits[e] - mx); - sum += p[(size_t) e]; - } - for (int e = 0; e < n_expert; ++e) p[(size_t) e] /= sum; - - // stable descending: std::stable_sort with a strict greater-than keeps equal elements in index order - std::vector idx((size_t) n_expert); - std::iota(idx.begin(), idx.end(), 0); - std::stable_sort(idx.begin(), idx.end(), - [&](int a, int b) { return p[(size_t) a] > p[(size_t) b]; }); - double s = 0; - for (int i = 0; i < k; ++i) { - ids[i] = idx[(size_t) i]; - w[i] = (float) p[(size_t) idx[(size_t) i]]; - s += p[(size_t) idx[(size_t) i]]; - } - s = std::max(s, RENORM_CLAMP); - for (int i = 0; i < k; ++i) w[i] = (float) ((double) w[i] / s); -} - -int run_case(const char* name, const std::vector& logits, int n_tokens, int n_expert, int k, - double tol) { - std::vector h_ids((size_t) n_tokens * k); - std::vector h_w((size_t) n_tokens * k); - std::vector r_ids((size_t) n_tokens * k); - std::vector r_w((size_t) n_tokens * k); - for (int t = 0; t < n_tokens; ++t) { - reference(&logits[(size_t) t * n_expert], n_expert, k, &r_ids[(size_t) t * k], &r_w[(size_t) t * k]); - } - - float* d_l = nullptr; - int* d_ids = nullptr; - float* d_w = nullptr; - check(cudaMalloc(&d_l, logits.size() * sizeof(float)), "malloc logits"); - check(cudaMalloc(&d_ids, h_ids.size() * sizeof(int)), "malloc ids"); - check(cudaMalloc(&d_w, h_w.size() * sizeof(float)), "malloc w"); - check(cudaMemcpy(d_l, logits.data(), logits.size() * sizeof(float), cudaMemcpyHostToDevice), "copy"); - strata::kernels::router_top10(d_l, n_tokens, n_expert, k, d_ids, d_w, nullptr); - check(cudaMemcpy(h_ids.data(), d_ids, h_ids.size() * sizeof(int), cudaMemcpyDeviceToHost), "back ids"); - check(cudaMemcpy(h_w.data(), d_w, h_w.size() * sizeof(float), cudaMemcpyDeviceToHost), "back w"); - - long long id_bad = 0, w_bad = 0; - double worst = 0; - for (size_t i = 0; i < h_ids.size(); ++i) { - if (h_ids[i] != r_ids[i]) ++id_bad; - const double rel = std::fabs((double) h_w[i] - (double) r_w[i]) / - (std::fabs((double) r_w[i]) > 1e-30 ? std::fabs((double) r_w[i]) : 1e-30); - worst = std::max(worst, rel); - if (!(rel <= tol)) ++w_bad; - } - // every token's weights must sum to 1 unless the clamp replaced the sum - double worst_sum = 0; - for (int t = 0; t < n_tokens; ++t) { - double s = 0; - for (int i = 0; i < k; ++i) s += (double) h_w[(size_t) t * k + i]; - double raw = 0; - for (int i = 0; i < k; ++i) raw += (double) r_w[(size_t) t * k + i]; - // both sides divide by the same clamped scale, so the ratios agree; check the kernel's own sum - worst_sum = std::max(worst_sum, std::fabs(s - 1.0)); - } - std::printf(" %-26s ids %s (%lld bad) weights worst rel %.3e (%lld over tol) |sum-1| %.1e\n", name, - id_bad ? "*** WRONG ***" : "exact", id_bad, worst, w_bad, worst_sum); - cudaFree(d_l); - cudaFree(d_ids); - cudaFree(d_w); - return (int) (id_bad + w_bad); -} - -} // namespace - -int main(int argc, char** argv) { - bool selftest = false; - for (int i = 1; i < argc; ++i) { - if (std::string(argv[i]) == "--selftest") selftest = true; - else { std::fprintf(stderr, "usage: router_top10_parity [--selftest]\n"); return 2; } - } - - const int NT = 64; - std::mt19937 rng(2024); - std::normal_distribution 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 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 b((size_t) NT * NE, 0.5f); - bad += run_case("all equal (ties)", b, NT, NE, K, 1e-5); - - // ---- a few exact ties among otherwise distinct values, WIDER than k: which k of the 12 is index order - std::vector c((size_t) NT * NE); - for (int t = 0; t < NT; ++t) { - for (int e = 0; e < NE; ++e) c[(size_t) t * NE + e] = (e < 12) ? 2.0f : gauss(rng); - } - bad += run_case("12-way exact tie", c, NT, NE, K, 1e-5); - - // ---- a tie of EXACTLY k experts at the top, scattered through the index range (not the first k): the whole - // selection is the tie, in index order, and every weight is the same 1/k - std::vector ck((size_t) NT * NE); - for (int t = 0; t < NT; ++t) { - for (int e = 0; e < NE; ++e) ck[(size_t) t * NE + e] = gauss(rng) - 4.0f; - for (int i = 0; i < K; ++i) ck[(size_t) t * NE + (size_t) ((t * 7 + i * (NE / K)) % NE)] = 3.0f; - } - char name[32]; - std::snprintf(name, sizeof name, "%d-way (= k) exact tie", K); - bad += run_case(name, ck, NT, NE, K, 1e-5); - - // ---- one dominant expert: the top-1 must be that expert and its weight must dominate - std::vector 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 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; -} diff --git a/src/kernels/s2_expert_grouped_parity.cpp b/src/kernels/s2_expert_grouped_parity.cpp deleted file mode 100644 index 901681f..0000000 --- a/src/kernels/s2_expert_grouped_parity.cpp +++ /dev/null @@ -1,679 +0,0 @@ -// src/kernels/s2_expert_grouped_parity.cpp - the rewritten expert kernels against the previous ones, -// BITWISE (GPU, synthetic, no model). -// -// build/s2_expert_grouped_parity the checks below; exit 1 on any difference -// build/s2_expert_grouped_parity --bench previous vs new kernel timings on engine-like shapes -// -// Random Q2_0 expert blobs (random codes, fp16 scales in a realistic range) and random Q8_0 activations. Every entry -// point of `s2_expert_grouped.hpp` that gained a new kernel runs twice from identical inputs and sentinel-filled -// outputs - `moe_grouped_select_old(1)`, then `(0)` - and the two runs are compared byte for byte: -// 1. `moe_hit_grouped_s2` per hit, host count; with fp32 activation scales and with the blocks' fp16 `d` -// 2. `moe_hit_grouped_s2_dev` device count below the capacity (the rows past it must stay untouched) -// 3. `moe_hit_grouped_s2_multi` verify window: each hit reads its own token's activation row -// 4. `moe_grouped_s2` host-built groups of 1..8 entries, one of them a mapped HOST blob (the PCIe -// share), and more group capacity than groups -// 5. `moe_group_resident` + `moe_grouped_s2` the MTP layer's shape, with and without fp32 scales -// 6. an activation row that is only 2-byte aligned: the new path must fall back to the previous kernels -// 7. a slot stride that is not a multiple of 8 (BLOB + 4), and 8. an arena 4 bytes past an aligned address: the -// per-hit path must fall back as well (its codes are read as uint2) -// Every run asks `moe_grouped_last_path` which kernels it launched, so a new path that silently declined cannot pass -// as "the previous kernels against themselves": forced new must report the new kernels, and 6-8 the previous ones. -// (A misaligned scratch is not exercised: the previous kernels store floats there, so it is not a legal input.) -// The output AND the scratch (gate/up, the quantized intermediate and its scales) are compared, so a failure names -// the projection. Bitwise equality with the previous kernels is the contract; on top of it a double-precision -// host reference of every up row and every down row checks that the fixture computes an expert at all - two -// kernels agreeing on garbage would otherwise pass. -#include "strata/kernels/f16_bits.hpp" -#include "strata/kernels/s2_expert_grouped.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace k = strata::kernels; - -namespace { -// The blob geometry, `cpu/expert.hpp`'s (restated as in the kernel). -constexpr int H = 2560, FF = 640, NCH_GU = H / 32, NCH_D = FF / 32; -constexpr size_t ROW_GU = H / 4, ROW_D = FF / 4, SC_GU = H / 64, SC_D = FF / 64; -constexpr size_t O_D_CODES = 2ull * FF * ROW_GU; -constexpr size_t O_GU_SCALES = O_D_CODES + (size_t) H * ROW_D; -constexpr size_t O_D_SCALES = O_GU_SCALES + 2ull * FF * SC_GU * 2; -constexpr size_t BLOB = O_D_SCALES + (size_t) H * SC_D * 2; -static_assert(BLOB == 1382400, "the Q2_0 expert blob is 1,382,400 bytes"); -constexpr size_t XROW = (size_t) NCH_GU * 34; // one token's activation row of block_q8_0 - -int g_fail = 0; - -void ck(cudaError_t e, const char* w) { - if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } -} -template T* dalloc(size_t n) { - T* p = nullptr; - ck(cudaMalloc(&p, n * sizeof(T) + 256), "malloc"); - ck(cudaMemset(p, 0, n * sizeof(T) + 256), "memset"); - return p; -} -template void up(T* d, const std::vector& h) { - ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "h2d"); -} -template std::vector down(const T* d, size_t n) { - std::vector h(n); - ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "d2h"); - return h; -} - -float f16f(const uint8_t* p) { return k::f32_from_f16((uint16_t) (p[0] | (p[1] << 8))); } -void put16(uint8_t* p, float f) { - const uint16_t h = k::f16_from_f32(f); - p[0] = (uint8_t) h; - p[1] = (uint8_t) (h >> 8); -} - -// Random codes; fp16 scales of either sign in [1e-3, 3e-2] (a real pack's range, so no overflow downstream). -void fill_blob(uint8_t* b, std::mt19937& rng) { - for (size_t i = 0; i < O_GU_SCALES; ++i) b[i] = (uint8_t) rng(); - std::uniform_real_distribution mag(1e-3f, 3e-2f); - for (size_t i = O_GU_SCALES; i < BLOB; i += 2) put16(b + i, (rng() & 1 ? -1.0f : 1.0f) * mag(rng)); -} - -// `n_tok` activation rows: per 32-chunk an fp16 `d` then 32 int8 in [-127, 127] (what `quantize_q8_0` writes), -// plus the fp32 scales `quantize_q8_0_scaled` would pass alongside. Some chunks are saturated on purpose. -void fill_x(std::vector& x, std::vector& xs, int n_tok, std::mt19937& rng) { - x.assign((size_t) n_tok * XROW, 0); - xs.assign((size_t) n_tok * NCH_GU, 0.0f); - std::uniform_real_distribution sc(2e-3f, 5e-2f); - for (size_t c = 0; c < (size_t) n_tok * NCH_GU; ++c) { - uint8_t* b = x.data() + c * 34; - xs[c] = sc(rng); - put16(b, xs[c]); - const int mode = (int) (rng() % 16); - for (int j = 0; j < 32; ++j) { - const int v = mode == 0 ? 127 : mode == 1 ? -127 : (int) (rng() % 255) - 127; - b[2 + j] = (uint8_t) (int8_t) v; - } - } -} - -// Double-precision reference of one row against one activation row: sum_c dw * dx * sum_e (code_e - 1) * x_e. -// `mag` receives sum |term|, the scale the tolerance is relative to. -double row_ref(const uint8_t* codes, const uint8_t* scales, const uint8_t* xrow, const float* xs, int n_chunks, - double* mag) { - double acc = 0.0, a = 0.0; - for (int c = 0; c < n_chunks; ++c) { - const uint8_t* xb = xrow + (size_t) c * 34; - const double dx = xs ? (double) xs[c] : (double) f16f(xb); - const double dw = (double) f16f(scales + (size_t) (c >> 1) * 2); - int s = 0; - for (int e = 0; e < 32; ++e) { - const int code = (codes[(size_t) c * 8 + e / 4] >> (2 * (e % 4))) & 3; - s += (code - 1) * (int) (int8_t) xb[2 + e]; - } - const double t = dw * dx * (double) s; - acc += t; - a += std::fabs(t); - } - *mag = a; - return acc; -} - -bool close_to(float got, double ref, double mag) { - return std::isfinite(got) && std::fabs((double) got - ref) <= 4e-5 * mag + 1e-30; -} - -struct Scratch { - void* p = nullptr; - uint64_t bytes = 0; - int64_t cap = 0; - uint64_t gu_bytes() const { return ((uint64_t) cap * 2 * FF * 4 + 15) & ~15ull; } - uint64_t q8_bytes() const { return ((uint64_t) cap * NCH_D * 34 + 15) & ~15ull; } -}; - -// One entry point, run with the previous kernels then with the new ones from identical sentinel-filled buffers; -// every differing float of the output and byte of the scratch is counted. `keep` receives the new run. -struct Run { - std::vector out; - std::vector scratch; -}; - -bool twice(const char* name, float* d_out, size_t out_floats, const Scratch& s, - const std::function& call, Run* keep, bool expect_new = true) { - Run r[2]; - for (int old = 1; old >= 0; --old) { - ck(cudaMemset(d_out, 0xA5, out_floats * 4), "sentinel out"); - ck(cudaMemset(s.p, 0x5A, s.bytes), "sentinel scratch"); - k::moe_grouped_select_old(old); - (void) k::moe_grouped_last_path(); // clear - call(); - const int path = k::moe_grouped_last_path(); - const int want = old ? 0 : (expect_new ? 1 : 0); - if (path != want) { - std::printf(" %-44s forced %s: launched %s kernels, expected %s\n", name, old ? "previous" : "new", - path == 1 ? "the new" : path == 0 ? "the previous" : "no", want ? "the new" : "the previous"); - ++g_fail; - } - ck(cudaGetLastError(), name); - ck(cudaDeviceSynchronize(), name); - Run& x = r[old ? 0 : 1]; - x.out = down(d_out, out_floats); - x.scratch = down((const uint8_t*) s.p, (size_t) s.bytes); - } - k::moe_grouped_select_old(-1); - const uint64_t gu = s.gu_bytes(), q8 = s.q8_bytes(); - size_t diff_out = 0, diff_gu = 0, diff_q8 = 0, diff_hs = 0; - for (size_t i = 0; i < out_floats; ++i) - diff_out += std::memcmp(&r[0].out[i], &r[1].out[i], 4) != 0; - for (size_t i = 0; i < (size_t) s.bytes; ++i) { - if (r[0].scratch[i] == r[1].scratch[i]) continue; - if (i < gu) ++diff_gu; - else if (i < gu + q8) ++diff_q8; - else ++diff_hs; - } - const bool ok = diff_out + diff_gu + diff_q8 + diff_hs == 0; - std::printf(" %-44s %s", name, ok ? "bitwise identical" : "DIFFERS"); - if (!ok) - std::printf(" (out %zu floats, gate/up %zu B, intermediate %zu B, its scales %zu B)", diff_out, diff_gu, - diff_q8, diff_hs); - std::printf("\n"); - if (!ok) ++g_fail; - if (keep) *keep = std::move(r[1]); - return ok; -} - -// The host reference on a finished run: every up row (the second half of gate/up, which the swiglu leaves alone) -// against the activation row it read, and every written down row against the intermediate the run produced. -struct Entry { - const uint8_t* blob; // host copy of the entry's blob - int tok; // activation row it reads - int dst; // output row it writes -}; -void reference(const char* name, const Run& r, const Scratch& s, const std::vector& ent, - const std::vector& x, const std::vector* xs) { - const float* gu = (const float*) r.scratch.data(); - const uint8_t* hq = r.scratch.data() + s.gu_bytes(); - const float* hs = (const float*) (r.scratch.data() + s.gu_bytes() + s.q8_bytes()); - long checked = 0, bad = 0; - double worst = 0.0; - for (size_t e = 0; e < ent.size(); ++e) { - const uint8_t* b = ent[e].blob; - const uint8_t* xrow = x.data() + (size_t) ent[e].tok * XROW; - const float* xsr = xs ? xs->data() + (size_t) ent[e].tok * NCH_GU : nullptr; - for (int rr = 0; rr < FF; rr += 7) { // up row rr = row-slot 2rr + 1 - double mag; - const double ref = row_ref(b + (size_t) (2 * rr + 1) * ROW_GU, b + O_GU_SCALES + (size_t) (2 * rr + 1) * SC_GU * 2, - xrow, xsr, NCH_GU, &mag); - const float got = gu[(size_t) s.cap * FF + e * FF + (size_t) rr]; - ++checked; - if (!close_to(got, ref, mag)) ++bad; - if (mag > 0) worst = std::max(worst, std::fabs((double) got - ref) / mag); - } - const uint8_t* hrow = hq + e * (size_t) NCH_D * 34; - const float* hsr = xs ? hs + e * (size_t) NCH_D : nullptr; - for (int rr = 0; rr < H; rr += 13) { - double mag; - const double ref = row_ref(b + O_D_CODES + (size_t) rr * ROW_D, b + O_D_SCALES + (size_t) rr * SC_D * 2, - hrow, hsr, NCH_D, &mag); - const float got = r.out[(size_t) ent[e].dst * H + (size_t) rr]; - ++checked; - if (!close_to(got, ref, mag)) ++bad; - if (mag > 0) worst = std::max(worst, std::fabs((double) got - ref) / mag); - } - } - std::printf(" %-44s host reference: %ld rows, %ld outside tolerance, worst %.2e of sum|term|\n", name, checked, - bad, worst); - if (bad || checked == 0) ++g_fail; -} - -struct Fixture { - int nb = 0; - std::vector h; // nb blobs - uint8_t* d = nullptr; - const uint8_t* hb(int i) const { return h.data() + (size_t) i * BLOB; } -}; - -Fixture make_blobs(int nb, std::mt19937& rng) { - Fixture f; - f.nb = nb; - f.h.resize((size_t) nb * BLOB); - for (int i = 0; i < nb; ++i) fill_blob(f.h.data() + (size_t) i * BLOB, rng); - f.d = dalloc((size_t) nb * BLOB); - up(f.d, f.h); - return f; -} - -Scratch make_scratch(int64_t cap) { - Scratch s; - s.cap = cap; - s.bytes = k::moe_hit_grouped_scratch_bytes(cap, H, FF); - s.p = dalloc(s.bytes); - return s; -} - -// ---------------------------------------------------------------- the checks -void check_all() { - std::mt19937 rng(20260928); - const Fixture fx = make_blobs(12, rng); - constexpr int K = 10; - - // Activations for up to 8 tokens, device copies with and without the fp32 scales. - std::vector x; - std::vector xs; - fill_x(x, xs, 8, rng); - uint8_t* d_x = dalloc(x.size()); - float* d_xs = dalloc(xs.size()); - up(d_x, x); - up(d_xs, xs); - - // ---- 1. moe_hit_grouped_s2: 9 hits of 10 routed rows, slots and destinations shuffled - { - const int n_hits = 9; - std::vector slot(n_hits), dst(K); - for (int i = 0; i < n_hits; ++i) slot[i] = (int32_t) ((i * 5 + 3) % fx.nb); - std::iota(dst.begin(), dst.end(), 0); - std::shuffle(dst.begin(), dst.end(), rng); - dst.resize(n_hits); - int32_t* d_slot = dalloc(n_hits); - int32_t* d_dst = dalloc(n_hits); - up(d_slot, slot); - up(d_dst, dst); - const Scratch s = make_scratch(n_hits); - float* d_out = dalloc((size_t) K * H); - std::vector ent; - for (int i = 0; i < n_hits; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]}); - for (int scaled = 1; scaled >= 0; --scaled) { - Run r; - const std::string name = std::string("moe_hit_grouped_s2") + (scaled ? " (fp32 scales)" : " (fp16 d)"); - twice(name.c_str(), d_out, (size_t) K * H, s, [&] { - k::moe_hit_grouped_s2(fx.d, d_slot, d_dst, n_hits, (int64_t) BLOB, d_x, s.p, d_out, nullptr, - scaled ? d_xs : nullptr); - }, &r); - reference(name.c_str(), r, s, ent, x, scaled ? &xs : nullptr); - } - } - - // ---- 2. moe_hit_grouped_s2_dev: capacity 10, device count 7 - { - const int cap = 10, count = 7; - std::vector slot(cap), dst(cap); - for (int i = 0; i < cap; ++i) slot[i] = (int32_t) ((i * 7 + 1) % fx.nb); - std::iota(dst.begin(), dst.end(), 0); - std::shuffle(dst.begin(), dst.end(), rng); - int32_t* d_slot = dalloc(cap); - int32_t* d_dst = dalloc(cap); - int32_t* d_count = dalloc(1); - up(d_slot, slot); - up(d_dst, dst); - up(d_count, std::vector{count}); - const Scratch s = make_scratch(cap); - float* d_out = dalloc((size_t) K * H); - std::vector ent; - for (int i = 0; i < count; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]}); - Run r; - twice("moe_hit_grouped_s2_dev (count 7 of 10)", d_out, (size_t) K * H, s, [&] { - k::moe_hit_grouped_s2_dev(fx.d, d_slot, d_dst, d_count, cap, (int64_t) BLOB, d_x, s.p, d_out, nullptr, - d_xs); - }, &r); - reference("moe_hit_grouped_s2_dev (count 7 of 10)", r, s, ent, x, &xs); - // the rows of the hits past the count keep the sentinel - long touched = 0; - for (int i = count; i < cap; ++i) - for (int c = 0; c < H; ++c) { - uint32_t v; - std::memcpy(&v, &r.out[(size_t) dst[i] * H + c], 4); - touched += v != 0xA5A5A5A5u; - } - std::printf(" %-44s rows past the count written: %ld\n", "moe_hit_grouped_s2_dev (count 7 of 10)", touched); - if (touched) ++g_fail; - } - - // ---- 3. moe_hit_grouped_s2_multi: 4 tokens x 10 routed entries, 29 hits - { - const int T = 4, n = T * K, count = 29; - std::vector ent_ids(n); - std::iota(ent_ids.begin(), ent_ids.end(), 0); - std::shuffle(ent_ids.begin(), ent_ids.end(), rng); - std::vector slot(n), dst(n); - for (int i = 0; i < n; ++i) { - dst[i] = ent_ids[i]; - slot[i] = (int32_t) (rng() % fx.nb); - } - std::sort(dst.begin(), dst.begin() + count); // hit order is routing order, as `moe_hit_select_multi` makes it - int32_t* d_slot = dalloc(n); - int32_t* d_dst = dalloc(n); - int32_t* d_count = dalloc(1); - up(d_slot, slot); - up(d_dst, dst); - up(d_count, std::vector{count}); - const Scratch s = make_scratch(n); - float* d_out = dalloc((size_t) n * H); - std::vector ent; - for (int i = 0; i < count; ++i) ent.push_back({fx.hb(slot[i]), dst[i] / K, dst[i]}); - Run r; - twice("moe_hit_grouped_s2_multi (4 tokens, 29 hits)", d_out, (size_t) n * H, s, [&] { - k::moe_hit_grouped_s2_multi(fx.d, d_slot, d_dst, d_count, n, (int64_t) BLOB, d_x, d_xs, K, s.p, d_out, - nullptr); - }, &r); - reference("moe_hit_grouped_s2_multi (4 tokens, 29 hits)", r, s, ent, x, &xs); - } - - // ---- 4. moe_grouped_s2: 8 tokens x 10 entries in groups of 1..8, one group on a mapped host blob - { - const int T = 8, n = T * K; - uint8_t* h_host = nullptr; - uint8_t* d_host = nullptr; - ck(cudaHostAlloc((void**) &h_host, BLOB, cudaHostAllocMapped), "host blob"); - std::memcpy(h_host, fx.hb(fx.nb - 1), BLOB); - ck(cudaHostGetDevicePointer((void**) &d_host, h_host, 0), "host blob ptr"); - // group sizes: 8, 1, 5, 2, 7, 3, 1, 6, 4, ... up to n entries - const int sizes[] = {8, 1, 5, 2, 7, 3, 1, 6, 4, 8, 1, 2, 3, 4, 5, 6, 7, 1, 1, 5}; - std::vector order(n); // the output rows, in group order - std::iota(order.begin(), order.end(), 0); - std::shuffle(order.begin(), order.end(), rng); - std::vector gptr; - std::vector gstart{0}, edst, etok; - std::vector ent; - int at = 0, gi = 0; - while (at < n) { - const int sz = std::min(sizes[gi % 20], n - at); - const bool host = gi == 3; - const int b = gi % (fx.nb - 1); - gptr.push_back((unsigned long long) (host ? d_host : fx.d + (size_t) b * BLOB)); - for (int j = 0; j < sz; ++j, ++at) { - edst.push_back(order[at]); - etok.push_back(order[at] / K); - ent.push_back({host ? h_host : fx.hb(b), order[at] / K, order[at]}); - } - gstart.push_back(at); - ++gi; - } - const int n_groups = gi, cap_groups = n_groups + 3; - gstart.resize((size_t) cap_groups + 1, at); - gptr.resize((size_t) cap_groups, gptr[0]); - unsigned long long* d_gptr = dalloc(gptr.size()); - int32_t* d_gstart = dalloc(gstart.size()); - int32_t* d_ng = dalloc(1); - int32_t* d_edst = dalloc(n); - int32_t* d_etok = dalloc(n); - up(d_gptr, gptr); - up(d_gstart, gstart); - up(d_ng, std::vector{n_groups}); - up(d_edst, edst); - up(d_etok, etok); - const Scratch s = make_scratch(n); - float* d_out = dalloc((size_t) n * H); - for (int scaled = 1; scaled >= 0; --scaled) { - Run r; - const std::string name = std::string("moe_grouped_s2 (") + std::to_string(n_groups) + " groups" + - (scaled ? ", fp32 scales)" : ", fp16 d)"); - twice(name.c_str(), d_out, (size_t) n * H, s, [&] { - k::moe_grouped_s2(d_gptr, d_gstart, d_ng, d_edst, d_etok, cap_groups, n, d_x, scaled ? d_xs : nullptr, - s.p, d_out, nullptr); - }, &r); - reference(name.c_str(), r, s, ent, x, scaled ? &xs : nullptr); - } - ck(cudaFreeHost(h_host), "free host blob"); - } - - // ---- 5. moe_group_resident + moe_grouped_s2: the MTP layer (experts resident at base + id * BLOB) - { - const int T = 5, n = T * K; - std::vector ids(n); - for (int t = 0; t < T; ++t) { // distinct within a token, shared across tokens - std::vector pick(fx.nb); - std::iota(pick.begin(), pick.end(), 0); - std::shuffle(pick.begin(), pick.end(), rng); - for (int j = 0; j < K; ++j) ids[(size_t) t * K + j] = pick[j]; - } - int32_t* d_ids = dalloc(n); - up(d_ids, ids); - unsigned long long* d_gptr = dalloc(n); - int32_t* d_gstart = dalloc(n + 1); - int32_t* d_counts = dalloc(2); - int32_t* d_edst = dalloc(n); - int32_t* d_etok = dalloc(n); - k::moe_group_resident(d_ids, n, K, fx.d, (int64_t) BLOB, d_gptr, d_gstart, d_counts, d_edst, d_etok, nullptr); - ck(cudaDeviceSynchronize(), "group_resident"); - const std::vector edst = down(d_edst, n), etok = down(d_etok, n); - std::vector ent(n); // entry e: dst = routing index, blob = its expert - for (int e = 0; e < n; ++e) ent[e] = {fx.hb(ids[(size_t) edst[e]]), etok[e], edst[e]}; - const Scratch s = make_scratch(n); - float* d_out = dalloc((size_t) n * H); - for (int scaled = 1; scaled >= 0; --scaled) { - Run r; - const std::string name = std::string("moe_group_resident + moe_grouped_s2") + (scaled ? " (fp32)" : " (fp16)"); - twice(name.c_str(), d_out, (size_t) n * H, s, [&] { - k::moe_grouped_s2(d_gptr, d_gstart, d_counts, d_edst, d_etok, n, n, d_x, scaled ? d_xs : nullptr, s.p, - d_out, nullptr); - }, &r); - reference(name.c_str(), r, s, ent, x, scaled ? &xs : nullptr); - } - } - - // ---- 6. a 2-byte aligned activation row: the new path must decline and the previous kernels run - { - uint8_t* d_x2 = dalloc(x.size() + 2); - ck(cudaMemcpy(d_x2 + 2, x.data(), XROW, cudaMemcpyHostToDevice), "x2"); - const int n_hits = 3; - std::vector slot{2, 5, 7}, dst{4, 0, 9}; - int32_t* d_slot = dalloc(n_hits); - int32_t* d_dst = dalloc(n_hits); - up(d_slot, slot); - up(d_dst, dst); - const Scratch s = make_scratch(n_hits); - float* d_out = dalloc((size_t) K * H); - std::vector ent; - for (int i = 0; i < n_hits; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]}); - Run r; - twice("moe_hit_grouped_s2 (2-byte aligned x)", d_out, (size_t) K * H, s, [&] { - k::moe_hit_grouped_s2(fx.d, d_slot, d_dst, n_hits, (int64_t) BLOB, d_x2 + 2, s.p, d_out, nullptr, d_xs); - }, &r, /*expect_new=*/false); - reference("moe_hit_grouped_s2 (2-byte aligned x)", r, s, ent, x, &xs); - } - - // ---- 7. slots BLOB + 4 bytes apart, and 8. an arena at an address that is 4 mod 8: per-hit fallback - { - constexpr size_t STRIDE = BLOB + 4; - static_assert(STRIDE % 8 != 0, "the stride must defeat the uint2 code loads"); - const int nb = 8; - uint8_t* d_arena = dalloc((size_t) nb * STRIDE + 8); - const int n_hits = 4; - std::vector slot{6, 1, 3, 0}, dst{2, 7, 5, 8}; - int32_t* d_slot = dalloc(n_hits); - int32_t* d_dst = dalloc(n_hits); - up(d_slot, slot); - up(d_dst, dst); - const Scratch s = make_scratch(n_hits); - float* d_out = dalloc((size_t) K * H); - std::vector ent; - for (int i = 0; i < n_hits; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]}); - // One allocation for both layouts: the BLOB + 4 strided copies first, then the same blobs BLOB apart from - // `d_arena + 4` over them. - for (int i = 0; i < nb; ++i) - ck(cudaMemcpy(d_arena + (size_t) i * STRIDE, fx.hb(i), BLOB, cudaMemcpyHostToDevice), "arena"); - { - Run r; - twice("moe_hit_grouped_s2 (slot stride BLOB + 4)", d_out, (size_t) K * H, s, [&] { - k::moe_hit_grouped_s2(d_arena, d_slot, d_dst, n_hits, (int64_t) STRIDE, d_x, s.p, d_out, nullptr, - d_xs); - }, &r, /*expect_new=*/false); - reference("moe_hit_grouped_s2 (slot stride BLOB + 4)", r, s, ent, x, &xs); - } - for (int i = 0; i < nb; ++i) - ck(cudaMemcpy(d_arena + 4 + (size_t) i * BLOB, fx.hb(i), BLOB, cudaMemcpyHostToDevice), "arena"); - { - Run r; - twice("moe_hit_grouped_s2 (arena 4 mod 8)", d_out, (size_t) K * H, s, [&] { - k::moe_hit_grouped_s2(d_arena + 4, d_slot, d_dst, n_hits, (int64_t) BLOB, d_x, s.p, d_out, nullptr, - d_xs); - }, &r, /*expect_new=*/false); - reference("moe_hit_grouped_s2 (arena 4 mod 8)", r, s, ent, x, &xs); - } - } -} - -// ---------------------------------------------------------------- --bench -// Engine-like shapes with the blobs cycled through a set larger than the L2, so each call reads its codes from -// DRAM as the engine's do. Reports microseconds per call and the codes' effective bandwidth. -void bench() { - int dev = 0; - cudaDeviceProp prop{}; - ck(cudaGetDevice(&dev), "dev"); - ck(cudaGetDeviceProperties(&prop, dev), "props"); - const int nb = std::max(48, (int) (3ull * (size_t) prop.l2CacheSize / BLOB) + 8); - std::printf("bench: %s, L2 %d MB, %d blobs (%.0f MB) cycled\n", prop.name, prop.l2CacheSize >> 20, nb, - nb * (double) BLOB / 1e6); - std::mt19937 rng(7); - Fixture fx; - fx.nb = nb; - fx.d = dalloc((size_t) nb * BLOB); - { - std::vector b(BLOB); - for (int i = 0; i < nb; ++i) { - fill_blob(b.data(), rng); - ck(cudaMemcpy(fx.d + (size_t) i * BLOB, b.data(), BLOB, cudaMemcpyHostToDevice), "blob"); - } - } - std::vector x; - std::vector xs; - fill_x(x, xs, 8, rng); - uint8_t* d_x = dalloc(x.size()); - float* d_xs = dalloc(xs.size()); - up(d_x, x); - up(d_xs, xs); - constexpr int K = 10, ITERS = 200, SETS = 16; - cudaEvent_t e0, e1; - ck(cudaEventCreate(&e0), "ev"); - ck(cudaEventCreate(&e1), "ev"); - auto time = [&](const std::function& call) { - call(0); - ck(cudaDeviceSynchronize(), "warm"); - ck(cudaEventRecord(e0), "rec"); - for (int i = 0; i < ITERS; ++i) call(i % SETS); - ck(cudaEventRecord(e1), "rec"); - ck(cudaEventSynchronize(e1), "sync"); - float ms = 0; - ck(cudaEventElapsedTime(&ms, e0, e1), "elapsed"); - return 1000.0 * ms / ITERS; - }; - auto ab = [&](const char* name, double blobs_per_call, const std::function& call) { - double us[2]; - for (int old = 1; old >= 0; --old) { - k::moe_grouped_select_old(old); - us[old ? 0 : 1] = time(call); - } - k::moe_grouped_select_old(-1); - const double gb = blobs_per_call * (double) BLOB / 1e3; // bytes / us = MB/s ... / 1e3 -> GB/s - std::printf(" %-40s previous %8.1f us (%6.0f GB/s) new %8.1f us (%6.0f GB/s) x%.2f\n", name, us[0], - gb / us[0], us[1], gb / us[1], us[0] / us[1]); - }; - - // per-hit path, decode: 9 hits of 10 (5090-like residency), 5 of 10, and the low-residency 1-3 hits, where the - // new kernels' grid (80 gate/up blocks per hit) is below one block per SM - see `STRATA_GROUPED_PAIR_MIN_HITS` - for (const int n_hits : {9, 5, 3, 2, 1}) { - std::vector slots((size_t) SETS * n_hits), dst(K); - for (auto& v : slots) v = (int32_t) (rng() % nb); - std::iota(dst.begin(), dst.end(), 0); - int32_t* d_slots = dalloc(slots.size()); - int32_t* d_dst = dalloc(K); - up(d_slots, slots); - up(d_dst, dst); - const Scratch s = make_scratch(n_hits); - float* d_out = dalloc((size_t) K * H); - const std::string name = "moe_hit_grouped_s2, " + std::to_string(n_hits) + " hits"; - ab(name.c_str(), n_hits, [&](int set) { - k::moe_hit_grouped_s2(fx.d, d_slots + (size_t) set * n_hits, d_dst, n_hits, (int64_t) BLOB, d_x, s.p, - d_out, nullptr, d_xs); - }); - } - // grouped path, verify window: T tokens x 10, routed with `share` = the chance an entry reuses an expert already - // routed by an earlier token of the window - struct Shape { int T; double share; const char* what; }; - for (const Shape sh : {Shape{4, 0.0, "4 tokens, no sharing"}, Shape{4, 0.3, "4 tokens, 30% shared"}, - Shape{8, 0.3, "8 tokens, 30% shared"}, Shape{8, 1.0, "8 tokens, all shared (ne 8)"}}) { - const int n = sh.T * K; - std::vector gptr((size_t) SETS * n); - std::vector gstart((size_t) SETS * (n + 1)), ng(SETS), edst((size_t) SETS * n), etok((size_t) SETS * n); - double groups = 0; - std::uniform_real_distribution u(0, 1); - for (int set = 0; set < SETS; ++set) { - std::vector> g; // per group: routing indices - std::vector gexp; // per group: blob - for (int t = 0; t < sh.T; ++t) { - std::vector used(g.size(), 0); - for (int j = 0; j < K; ++j) { - int pick = -1; - if (t > 0 && u(rng) < sh.share) - for (size_t q = 0; q < g.size(); ++q) - if (!used[q] && (int) g[q].size() < 8) { pick = (int) q; break; } - if (pick < 0) { - pick = (int) g.size(); - g.emplace_back(); - gexp.push_back((int) (rng() % nb)); - used.push_back(0); - } - used[(size_t) pick] = 1; - g[(size_t) pick].push_back(t * K + j); - } - } - int at = 0; - for (size_t q = 0; q < g.size(); ++q) { - gptr[(size_t) set * n + q] = (unsigned long long) (fx.d + (size_t) gexp[q] * BLOB); - gstart[(size_t) set * (n + 1) + q] = at; - for (int e : g[q]) { - edst[(size_t) set * n + at] = e; - etok[(size_t) set * n + at] = e / K; - ++at; - } - } - for (size_t q = g.size(); q <= (size_t) n; ++q) gstart[(size_t) set * (n + 1) + q] = at; - ng[set] = (int32_t) g.size(); - groups += (double) g.size() / SETS; - } - unsigned long long* d_gptr = dalloc(gptr.size()); - int32_t* d_gstart = dalloc(gstart.size()); - int32_t* d_ng = dalloc(SETS); - int32_t* d_edst = dalloc(edst.size()); - int32_t* d_etok = dalloc(etok.size()); - up(d_gptr, gptr); - up(d_gstart, gstart); - up(d_ng, ng); - up(d_edst, edst); - up(d_etok, etok); - const Scratch s = make_scratch(n); - float* d_out = dalloc((size_t) n * H); - char name[96]; - std::snprintf(name, sizeof name, "moe_grouped_s2, %s (%.0f groups)", sh.what, groups); - ab(name, groups, [&](int set) { - k::moe_grouped_s2(d_gptr + (size_t) set * n, d_gstart + (size_t) set * (n + 1), d_ng + set, - d_edst + (size_t) set * n, d_etok + (size_t) set * n, n, n, d_x, d_xs, s.p, d_out, - nullptr); - }); - } -} -} // namespace - -int main(int argc, char** argv) { - bool do_bench = false; - for (int i = 1; i < argc; ++i) { - if (std::strcmp(argv[i], "--bench") == 0) do_bench = true; - else if (std::strcmp(argv[i], "--selftest") != 0) { - std::fprintf(stderr, "usage: s2_expert_grouped_parity [--selftest] [--bench]\n"); - return 2; - } - } - std::printf("s2_expert_grouped_parity: new expert kernels vs the previous ones, bitwise\n"); - check_all(); - if (do_bench) bench(); - std::printf("s2_expert_grouped_parity: %d failures\n%s\n", g_fail, g_fail ? "FAIL" : "PASS"); - return g_fail ? 1 : 0; -} diff --git a/src/kernels/s2_gemv_parity.cpp b/src/kernels/s2_gemv_parity.cpp deleted file mode 100644 index ab69379..0000000 --- a/src/kernels/s2_gemv_parity.cpp +++ /dev/null @@ -1,173 +0,0 @@ -// src/kernels/s2_gemv_parity.cpp - P2.S2's parity test for the S2 GEMV. -// -// The reference is the same CHAIN as the decode test: `strata::dequantize_q2_0` is a scalar transcription that -// `bench/micro/dequant_xcheck` checks against **ggml's own** dequantizer, so comparing the GPU GEMV against a -// dot product built on that scalar decode compares against ggml through one proven hop. -// -// WHY A TOLERANCE AND NOT BIT EQUALITY. The decode test is bit-exact because S2's decode is exact -// integer-to-float arithmetic. A dot product is not: the compiler is free to contract `a*b + acc` into an -// FMA, which changes the result in the last bits, and nvcc does. So this asserts a RELATIVE error, measures -// what it actually is, and prints the number - the phase spec allows 1e-3 for FP16 paths, and if the measured -// error were near that the tolerance would be hiding something rather than bounding rounding. -#include "strata/artifact/dequant.hpp" -#include "strata/kernels/s2_gemv.hpp" - -#include - -#include -#include -#include -#include -#include -#include - -namespace { - -constexpr int QK = 64; - -void check(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -// FP16 patterns, and they are deliberately NOT all powers of two. -// -// The first version of this table was {1.0, 0.5, 0.25, ...} - every value a power of two. The test then -// reported a worst relative error of EXACTLY zero, which is not a property of the kernel: (code-1) is in -// {-1,0,1,2} and a power-of-two times an fp16 is exact, so every product was exact and no rounding could -// occur in either implementation. A test whose arithmetic cannot round cannot exercise its own tolerance, and -// it would have hidden an accumulation-order or contraction bug for ever. -// -// The added patterns have full 11-bit mantissas, so products round and the two implementations' -// rounding/contraction behaviour actually matters. -const uint16_t kScales[] = { - 0x3C00, 0x3800, 0x3400, 0x3000, 0x2C00, 0x2800, 0x2000, // 1, 0.5, 0.25, ... powers of two - 0xBC00, 0xB800, 0xB400, 0xB000, 0xAC00, 0x1800, 0x1400, - 0x3E00, 0x3555, 0x3C01, 0x4248, 0x4123, 0x2AAA, 0x4A2B, // 1.75, 0.333.., 1.0009765625, ... - 0xBE00, 0xB555, 0xC248, 0x2AAB, 0x4A2C, 0x2AAB}; - -} // namespace - -int main(int argc, char** argv) { - long long n_in = 2560; // the real n_embd, so the row length is the engine's - long long n_out = 640; // the real expert intermediate width - double tol = 1e-5; - bool selftest = false; - for (int i = 1; i < argc; ++i) { - if (std::strcmp(argv[i], "--selftest") == 0) selftest = true; - else if (std::strcmp(argv[i], "--n-in") == 0 && i + 1 < argc) n_in = std::atoll(argv[++i]); - else if (std::strcmp(argv[i], "--n-out") == 0 && i + 1 < argc) n_out = std::atoll(argv[++i]); - else if (std::strcmp(argv[i], "--tol") == 0 && i + 1 < argc) tol = std::atof(argv[++i]); - else { - std::fprintf(stderr, "usage: s2_gemv_parity [--selftest] [--n-in N] [--n-out N] [--tol T]\n"); - return 2; - } - } - if (n_in % QK != 0) { std::fprintf(stderr, "--n-in must be a multiple of %d\n", QK); return 2; } - const long long nb = n_in / QK; - - std::mt19937 rng(999); - const int n_scales = (int) (sizeof(kScales) / sizeof(kScales[0])); - - // FP16 activations. Patterns are drawn from the same finite/exact table as the decode test, because a - // random 16-bit pattern can be NaN and a NaN makes the comparison fail for the wrong reason. - std::vector x((size_t) n_in); - for (long long i = 0; i < n_in; ++i) x[(size_t) i] = kScales[rng() % n_scales]; - - // S2 weight planes for an [n_in, n_out] matrix: row o occupies a contiguous run of nb blocks. - std::vector codes((size_t) n_out * nb * 16); - std::vector scales((size_t) n_out * nb); - for (size_t i = 0; i < codes.size(); ++i) codes[i] = (uint8_t) (rng() & 0xFF); - for (size_t i = 0; i < scales.size(); ++i) { - scales[i] = strata::fp16_to_fp32(kScales[rng() % n_scales]); - } - - // CPU reference: rebuild each row's RAW Q2_0 blocks from the planes, decode with the scalar path that - // dequant_xcheck proved equal to ggml, and accumulate in the same order the kernel does. - std::vector ref((size_t) n_out, 0.0f); - std::vector raw(18); - std::vector dec(QK); - for (long long o = 0; o < n_out; ++o) { - float acc = 0.0f; - for (long long b = 0; b < nb; ++b) { - const float d = scales[(size_t) (o * nb + b)]; - // write `d` back as the fp16 pattern the plane came from: the plane stores a WIDENED fp16, so - // re-narrowing is exact and the scalar decoder sees the same value the kernel does - const uint16_t d_bits = (uint16_t) [&] { - for (uint16_t c : kScales) { - if (strata::fp16_to_fp32(c) == d) return c; - } - return (uint16_t) 0x3C00; - }(); - raw[0] = (uint8_t) (d_bits & 0xFF); - raw[1] = (uint8_t) (d_bits >> 8); - std::memcpy(&raw[2], &codes[(size_t) ((o * nb + b) * 16)], 16); - strata::dequantize_q2_0(raw.data(), dec.data()); - for (int j = 0; j < QK; ++j) { - acc += dec[(size_t) j] * strata::fp16_to_fp32(x[(size_t) (b * QK + j)]); - } - } - ref[(size_t) o] = acc; - } - - uint16_t* d_x = nullptr; - uint8_t* d_codes = nullptr; - float *d_scales = nullptr, *d_y = nullptr; - check(cudaMalloc(&d_x, x.size() * sizeof(uint16_t)), "cudaMalloc x"); - check(cudaMalloc(&d_codes, codes.size()), "cudaMalloc codes"); - check(cudaMalloc(&d_scales, scales.size() * sizeof(float)), "cudaMalloc scales"); - check(cudaMalloc(&d_y, (size_t) n_out * sizeof(float)), "cudaMalloc y"); - check(cudaMemcpy(d_x, x.data(), x.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "copy x"); - check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "copy codes"); - check(cudaMemcpy(d_scales, scales.data(), scales.size() * sizeof(float), cudaMemcpyHostToDevice), - "copy scales"); - - strata::kernels::s2_gemv(d_x, d_codes, d_scales, d_y, n_in, n_out); - - std::vector got((size_t) n_out); - check(cudaMemcpy(got.data(), d_y, got.size() * sizeof(float), cudaMemcpyDeviceToHost), "copy back"); - - long long bad = 0, first_bad = -1; - double worst = 0.0; - for (long long o = 0; o < n_out; ++o) { - const double a = ref[(size_t) o], b = got[(size_t) o]; - const double denom = std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30; - const double rel = std::fabs(a - b) / denom; - if (!(rel <= worst)) worst = rel; - if (!(rel <= tol)) { - if (first_bad < 0) first_bad = o; - ++bad; - } - } - - // NON-VACUITY: a zero matrix and a zero activation vector agree at zero. The reference must actually vary - // and its magnitudes must be non-trivial, or the comparison cannot distinguish anything. - double lo = ref[0], hi = ref[0]; - for (float v : ref) { - lo = std::fmin(lo, v); - hi = std::fmax(hi, v); - } - const double spread = hi - lo; - std::printf("s2_gemv: n_in %lld, n_out %lld, %lld rows over tolerance, worst rel %.3e (tol %.1e)\n", n_in, - n_out, bad, worst, tol); - std::printf(" reference spread [%.4g, %.4g]\n", lo, hi); - if (spread <= 0.0) { - std::fprintf(stderr, "VACUOUS: the reference is constant, so agreement proves nothing\n"); - return 1; - } - if (bad) { - std::printf(" first bad row %lld: ref %.9g got %.9g\n", first_bad, (double) ref[(size_t) first_bad], - (double) got[(size_t) first_bad]); - return 1; - } - std::printf(" agrees with the scalar decode that dequant_xcheck proved equal to ggml\n"); - if (selftest) std::printf("s2_gemv_parity OK\n"); - - cudaFree(d_x); - cudaFree(d_codes); - cudaFree(d_scales); - cudaFree(d_y); - return 0; -} diff --git a/src/kernels/s2_gemv_q8_parity.cpp b/src/kernels/s2_gemv_q8_parity.cpp deleted file mode 100644 index 833e751..0000000 --- a/src/kernels/s2_gemv_q8_parity.cpp +++ /dev/null @@ -1,181 +0,0 @@ -// src/kernels/s2_gemv_q8_parity.cpp - the Q8_0-activation GEMV, and the size of the gap it closes. -// -// THREE CHECKS: -// 1. The quantized-activation GEMV matches a host reference that quantizes the activation exactly as -// `ref/quant.py::q8_0` does and then dots it against the same weights. -// 2. **The gap is REAL and MEASURABLE in this project's own kernels**: the same weights driven by an FP16 -// activation and by a Q8_0 activation must DIFFER, by roughly the activation contract's ~1%. Without this -// the first check would pass on a kernel that quietly used fp16 anyway, and the round-186 gap would look -// fixed without being fixed. -// 3. The measured size of that difference is reported, so the number in the state file is one this test -// produces rather than one quoted from elsewhere. -#include "strata/kernels/quantize_act.hpp" -#include "strata/kernels/s_gemv.hpp" -#include "strata/kernels/s2_gemv_q8.hpp" - -#include - -#include -#include -#include -#include -#include -#include - -namespace { - -void check(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -} // namespace - -int main(int argc, char** argv) { - bool selftest = false; - for (int i = 1; i < argc; ++i) { - if (std::string(argv[i]) == "--selftest") selftest = true; - else { std::fprintf(stderr, "usage: s2_gemv_q8_parity [--selftest]\n"); return 2; } - } - - const long long n_in = 2560, n_out = 64; - const int tpr = 32; - std::mt19937 rng(31); - std::normal_distribution gauss(0.0f, 1.0f); - - std::vector x((size_t) n_in); - for (auto& v : x) v = gauss(rng); - std::vector codes((size_t) n_out * n_in / 4); - for (auto& v : codes) v = (uint8_t) (rng() & 0xFF); - std::vector scales((size_t) n_out * (n_in / 64)); - for (auto& v : scales) v = 0.001f + 0.0001f * (float) (rng() % 100); - - // ---- device buffers - float* d_x = nullptr; - uint8_t* d_act = nullptr; - uint8_t* d_codes = nullptr; - float *d_scales = nullptr, *d_y_fp16 = nullptr, *d_y_q8 = nullptr; - check(cudaMalloc(&d_x, (size_t) n_in * sizeof(float)), "m x"); - check(cudaMalloc(&d_act, (size_t) (n_in / 32) * 34), "m act"); - check(cudaMalloc(&d_codes, codes.size()), "m codes"); - check(cudaMalloc(&d_scales, scales.size() * sizeof(float)), "m scales"); - check(cudaMalloc(&d_y_fp16, (size_t) n_out * sizeof(float)), "m y1"); - check(cudaMalloc(&d_y_q8, (size_t) n_out * sizeof(float)), "m y2"); - check(cudaMemcpy(d_x, x.data(), x.size() * sizeof(float), cudaMemcpyHostToDevice), "c x"); - check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "c codes"); - check(cudaMemcpy(d_scales, scales.data(), scales.size() * sizeof(float), cudaMemcpyHostToDevice), "c scales"); - - strata::kernels::quantize_q8_0(d_x, d_act, n_in, nullptr); - - // ---- host reference: quantize the activation with the project's own rule, then dot - std::vector h_act((size_t) (n_in / 32) * 34); - check(cudaMemcpy(h_act.data(), d_act, h_act.size(), cudaMemcpyDeviceToHost), "c act back"); - auto act_val = [&](long long i) { - const uint8_t* blk = &h_act[(size_t) (i / 32) * 34]; - const uint16_t dbits = (uint16_t) (blk[0] | (blk[1] << 8)); - // fp16 -> f32 without a CUDA header: 0x3C00 = 1.0, and the block scales here are normal - float d; - const uint32_t sign = (uint32_t) (dbits & 0x8000) << 16; - uint32_t ex = (dbits >> 10) & 0x1F, man = dbits & 0x3FF; - uint32_t out; - if (ex == 0) { out = sign; } - else { out = sign | ((ex - 15 + 127) << 23) | (man << 13); } - std::memcpy(&d, &out, 4); - return (float) ((int8_t) blk[2 + (i % 32)]) * d; - }; - std::vector ref((size_t) n_out, 0.0f); - for (long long o = 0; o < n_out; ++o) { - float acc = 0.0f; - for (long long g = 0; g < n_in / 64; ++g) { - const float d = scales[(size_t) (o * (n_in / 64) + g)]; - for (int j = 0; j < 64; ++j) { - const long long i = g * 64 + j; - const uint8_t byte = codes[(size_t) (o * (n_in / 4) + i / 4)]; - const int code = (byte >> ((i % 4) * 2)) & 3; - acc += (float) (code - 1) * d * act_val(i); - } - } - ref[(size_t) o] = acc; - } - strata::kernels::s2_gemv_q8(d_act, d_codes, d_scales, d_y_q8, n_in, n_out, tpr, nullptr); - std::vector got((size_t) n_out); - check(cudaMemcpy(got.data(), d_y_q8, got.size() * sizeof(float), cudaMemcpyDeviceToHost), "c y2"); - - int bad = 0; - double worst = 0.0, sum_abs = 0.0; - for (long long o = 0; o < n_out; ++o) { - const double a = ref[(size_t) o], b = got[(size_t) o]; - sum_abs += std::fabs(a); - // relative to the row magnitude is not needed here - these rows are not cancelling - but the metric is - // stated because round 169 and round 189 both showed the wrong denominator reads as a wrong kernel - const double rel = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30); - if (!(rel <= worst)) worst = rel; - // 1e-4, not 1e-5: the measured worst is 1.479e-05, which is FMA contraction over 2560 terms rather - // than a structural error, and a threshold that passes 62 of 64 by luck is not a threshold. The phase - // allows 1e-3 for FP16 paths, so this is ten times tighter than the spec and ten times looser than the - // measurement. - if (!(rel <= 1e-4)) ++bad; - } - std::printf(" %-38s %s (%d of %lld over 1e-4, worst rel %.3e, mean |ref| %.3f)\n", - "q8-activation GEMV vs host reference", bad ? "*** WRONG ***" : "matches", bad, n_out, worst, - sum_abs / (double) n_out); - - // ---- CHECK 2: the gap is real. The SAME weights driven by an fp16 activation must differ. - // The fp16 path wants fp16 activations, and `x` is f32, so it is converted exactly (the values are normal - // and small), which keeps the comparison about the ACTIVATION FORMAT and nothing else. - // A REAL fp32 -> fp16 conversion. The first version wrote `0x3C00 + (int)(x*64)`, which adds to the raw - // BITS and therefore changes the EXPONENT - x = 2.0 became 0x3C80 = 1.25 - so the two paths were driven by - // unrelated activations and the comparison reported 2770%. The number was a symptom of the fixture, and - // the fixture is what the check exists to be able to trust. - auto f32_to_f16 = [](float f) -> uint16_t { - uint32_t b; - std::memcpy(&b, &f, 4); - const uint32_t sign = (b >> 16) & 0x8000u; - int exp = (int) ((b >> 23) & 0xFF) - 127 + 15; - uint32_t man = b & 0x7FFFFFu; - if (exp >= 31) return (uint16_t) (sign | 0x7C00u | (man ? 0x200u : 0u)); - if (exp <= 0) { - if (exp < -10) return (uint16_t) sign; - man |= 0x800000u; - const uint32_t sh = (uint32_t) (14 - exp); - uint32_t h = (man >> sh) & 0x3FFu; - const uint32_t rem = man & ((1u << sh) - 1u); - if (rem > (1u << (sh - 1)) || (rem == (1u << (sh - 1)) && (h & 1u))) ++h; - return (uint16_t) (sign | h); - } - uint16_t h = (uint16_t) (sign | ((uint32_t) exp << 10) | (man >> 13)); - const uint32_t rem = man & 0x1FFFu; - if (rem > 0x1000u || (rem == 0x1000u && (h & 1u))) ++h; - return h; - }; - std::vector hx((size_t) n_in); - for (long long i = 0; i < n_in; ++i) hx[(size_t) i] = f32_to_f16(x[(size_t) i]); - uint16_t* d_hx = nullptr; - check(cudaMalloc(&d_hx, hx.size() * sizeof(uint16_t)), "m hx"); - check(cudaMemcpy(d_hx, hx.data(), hx.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "c hx"); - strata::kernels::SForm form{2, -1, 64, strata::kernels::Codebook::Affine, false}; - strata::kernels::s_gemv_split(d_hx, d_codes, d_scales, nullptr, d_y_fp16, n_in, n_out, form, tpr); - std::vector y16((size_t) n_out); - check(cudaMemcpy(y16.data(), d_y_fp16, y16.size() * sizeof(float), cudaMemcpyDeviceToHost), "c y1"); - - double diff = 0.0; - for (long long o = 0; o < n_out; ++o) { - diff += std::fabs((double) y16[(size_t) o] - (double) got[(size_t) o]); - } - const double rel_gap = diff / (sum_abs > 1e-30 ? sum_abs : 1e-30); - std::printf(" %-38s %.4f%% of the reference magnitude\n", "fp16-activation vs q8-activation", rel_gap * 100); - if (rel_gap < 1e-4) { - std::fprintf(stderr, - "the two activation paths agree to %.2e, so this test CANNOT see the difference it exists " - "to measure - either the q8 path silently used fp16, or the fixture is degenerate\n", - rel_gap); - ++bad; - } - - std::printf("\ns2_gemv_q8: %d failures\n", bad); - if (bad) return 1; - if (selftest) std::printf("s2_gemv_q8_parity OK\n"); - return 0; -} diff --git a/src/kernels/s_gemv_parity.cpp b/src/kernels/s_gemv_parity.cpp deleted file mode 100644 index 5c0bed5..0000000 --- a/src/kernels/s_gemv_parity.cpp +++ /dev/null @@ -1,634 +0,0 @@ -// src/kernels/s_gemv_parity.cpp - P2.S2's parity test for the S-family GEMV. -// -// Four source types, chosen to cover every branch the kernel has: -// -// S2 Q2_0 2-bit, bias -1, group 64 affine -// S4 Q4_0 4-bit, bias -8, group 32 affine -// S4 IQ4_NL 4-bit, bias 0, group 32 CODEBOOK (non-linear, no bias can express it) -// S8 Q8_0 8-bit, bias -128, group 32 affine -// -// That is all three template instantiations, both codebooks, and four different biases. The offset branch -// (`has_offset`, only Q4_K and Q5_K) is NOT exercised here and the test prints that fact rather than leaving a -// green result to imply otherwise - Q4_K's canonicalisation needs the packed 6-bit scale/min pairs, and the -// honest move is to say so than to half-build it. -// -// THE REFERENCE IS THE CHAIN: for each type the CPU side reconstructs the RAW GGUF block from the canonical -// planes and decodes it with that type's scalar dequantizer from include/strata/artifact/dequant.hpp - the -// ones `bench/micro/dequant_xcheck` checks against **ggml's own** dequantizers. Reconstructing raw from -// canonical is the inverse of what the packer does, and it is written here independently of the packer so the -// two are not the same code. -#include "strata/artifact/dequant.hpp" -#include "strata/kernels/s_gemv.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { - -void check(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -// Finite, exactly representable fp16 patterns WITH full mantissas. Not powers of two: with only powers of -// two every product is exact and the comparison cannot round, which is how the first version of s2_gemv's test -// managed a worst error of exactly zero without proving anything. -const uint16_t kScales[] = {0x3E00, 0x3555, 0x3C01, 0x4248, 0x4123, 0x2AAA, 0x4A2B, 0x3800, - 0xBE00, 0xB555, 0xC248, 0x2AAB, 0x4A2C, 0x2AAB, 0xB800}; - -struct Case { - const char* name; - strata::kernels::SForm form; - int raw_bytes; // one block - // Reconstruct the raw GGUF block for one group from the canonical codes/scales, and return the number of - // elements the block decodes to (which may exceed group_elems: Q8_0's block IS one group, Q2_0's too). - int (*to_raw)(const uint8_t* codes, size_t code_off, const uint16_t* scale_bits, size_t scale_off, uint8_t* raw); - double (*dequant)(const uint8_t* raw, float* out); -}; - -// ---- Q2_0: raw = { fp16 d ; uint8 qs[16] }, 64 elements, code i at byte i/4 bits (i%4)*2 - identical to the -// canonical plane, so this is a straight copy plus the scale. -int q2_0_to_raw(const uint8_t* codes, size_t co, const uint16_t* scale_bits, size_t so, uint8_t* raw) { - const uint16_t d = scale_bits[so]; - raw[0] = (uint8_t) (d & 0xFF); - raw[1] = (uint8_t) (d >> 8); - // `codes` is one code PER ELEMENT (64 of them); a Q2_0 block stores them PACKED, 4 per byte, element i at - // byte i/4 bits (i%4)*2. The two coincide as a byte layout only if you confuse them, which is exactly the - // mistake the first version of this function made by copying 16 bytes verbatim. - for (int b = 0; b < 16; ++b) { - raw[2 + b] = (uint8_t) ((codes[co + 4 * b + 0] & 3) | ((codes[co + 4 * b + 1] & 3) << 2) | - ((codes[co + 4 * b + 2] & 3) << 4) | ((codes[co + 4 * b + 3] & 3) << 6)); - } - return 64; -} -double q2_0_deq(const uint8_t* raw, float* out) { - strata::dequantize_q2_0(raw, out); - return 64; -} - -// ---- Q4_0: raw = { fp16 d ; uint8 qs[16] }, 32 elements; element j is the LOW nibble of byte j and element -// j+16 the HIGH nibble. The canonical plane stores one code per element, so this re-packs them. -int q4_0_to_raw(const uint8_t* codes, size_t co, const uint16_t* scale_bits, size_t so, uint8_t* raw) { - const uint16_t d = scale_bits[so]; - raw[0] = (uint8_t) (d & 0xFF); - raw[1] = (uint8_t) (d >> 8); - for (int j = 0; j < 16; ++j) raw[2 + j] = (uint8_t) ((codes[co + j] & 0x0F) | (codes[co + 16 + j] << 4)); - return 32; -} -double q4_0_deq(const uint8_t* raw, float* out) { - strata::dequantize_q4_0(raw, out); - return 32; -} - -// ---- IQ4_NL: identical packing to Q4_0, different decode (a table, not a bias). -int iq4_to_raw(const uint8_t* codes, size_t co, const uint16_t* scale_bits, size_t so, uint8_t* raw) { - return q4_0_to_raw(codes, co, scale_bits, so, raw); -} -double iq4_deq(const uint8_t* raw, float* out) { - strata::dequantize_iq4_nl(raw, out); - return 32; -} - -// ---- Q8_0: raw = { fp16 d ; int8 qs[32] }, 32 elements. The canonical code plane is UNSIGNED with bias -// -128 (round 154's fix), so the raw int8 byte is exactly the canonical code reinterpreted - a straight copy, -// which is why this type is the cheapest one to check and the one whose sign bug was found by the pack. -int q8_0_to_raw(const uint8_t* codes, size_t co, const uint16_t* scale_bits, size_t so, uint8_t* raw) { - const uint16_t d = scale_bits[so]; - raw[0] = (uint8_t) (d & 0xFF); - raw[1] = (uint8_t) (d >> 8); - // NOT a straight copy. The canonical code plane is UNSIGNED with bias -128, so canonical code c means the - // value (c - 128); the raw block stores that as an `int8_t`, whose reinterpretation as an unsigned byte is - // `c ^ 0x80` - a SIGN-BIT FLIP, not the identity. Assuming identity is the same family of mistake as the - // round-154 Q8_0 bug that the pack found, and it is why this reconstruction is written out rather than - // memcpy'd. - for (int j = 0; j < 32; ++j) raw[2 + j] = (uint8_t) (codes[co + j] ^ 0x80); - return 32; -} -double q8_0_deq(const uint8_t* raw, float* out) { - strata::dequantize_q8_0(raw, out); - return 32; -} - -// ---- S4/Q4_K: the ONLY canonical form with an offset, and the only one whose scale is an FP32 PRODUCT -// (`fl(d*sc)`) rather than a widened fp16. Both facts make it the case worth having. -// -// There is no `to_raw` for it in the table above because its canonical planes are DERIVED from the raw -// parameters, not the other way round: the packer computes `scale = d*sc` and `offset = -(dmin*m)`, so this -// generates d, dmin and the eight (sc, m) pairs, derives the planes exactly as the packer does, and writes a -// raw block from the SAME parameters. Inverting those products instead would be ambiguous. -void test_q4k(long long n_in, long long n_out, double tol, int* total_bad) { - using strata::kernels::Codebook; - using strata::kernels::SForm; - const SForm form{4, 0, 32, Codebook::Affine, true}; - - std::mt19937 rng(777); - const int n_scales = (int) (sizeof(kScales) / sizeof(kScales[0])); - const long long n_groups = n_in / 32; - const long long codes_per_row = n_in / 2; - - std::vector x((size_t) n_in); - for (long long i = 0; i < n_in; ++i) x[(size_t) i] = kScales[rng() % n_scales]; - - std::vector codes_el((size_t) n_out * n_in); - for (size_t i = 0; i < codes_el.size(); ++i) codes_el[i] = (uint8_t) (rng() & 0x0F); - std::vector codes((size_t) n_out * codes_per_row, 0); - for (size_t i = 0; i < codes_el.size(); ++i) { - const size_t o = i / (size_t) n_in, k = i % (size_t) n_in; - codes[o * (size_t) codes_per_row + k / 2] |= (uint8_t) (codes_el[i] << ((k % 2) * 4)); - } - std::vector scales((size_t) n_out * n_groups), offsets((size_t) n_out * n_groups); - - struct Row { - uint16_t d, dmin; - uint8_t sc[8], m[8]; - }; - std::vector rows((size_t) n_out); - for (long long o = 0; o < n_out; ++o) { - Row& r = rows[(size_t) o]; - r.d = kScales[rng() % n_scales]; - r.dmin = kScales[rng() % n_scales]; - for (int g = 0; g < 8; ++g) { - r.sc[g] = (uint8_t) (rng() & 0x3F); - r.m[g] = (uint8_t) (rng() & 0x3F); - for (long long sb = 0; sb < n_in / 256; ++sb) { - scales[(size_t) (o * n_groups + sb * 8 + g)] = strata::fp16_to_fp32(r.d) * (float) r.sc[g]; - offsets[(size_t) (o * n_groups + sb * 8 + g)] = -(strata::fp16_to_fp32(r.dmin) * (float) r.m[g]); - } - } - } - - std::vector ref((size_t) n_out, 0.0f); - std::vector cond((size_t) n_out, 0.0); - double worst_plane_ref = 0.0; // max |planes - raw block| over every element, on the CPU alone - std::vector blk(144); - std::vector dec(256); - // A Q4_K raw block covers 256 elements, so a 2560-element row is TEN superblocks, each with its own - // 144-byte block. The first version of this loop ran `step < 4` - one superblock, 256 of the row's 2560 - // elements - while the kernel accumulated all of them, and the resulting 29x relative error was the - // reference being short, not the kernel being wrong. - for (long long o = 0; o < n_out; ++o) { - const Row& r = rows[(size_t) o]; - float acc = 0.0f; - double sum_abs = 0.0; // the natural scale of this row's dot product (see the metric below) - double plane_ref_diff = 0.0; // (a) vs (b): planes against the raw block, both on the CPU - for (long long sb = 0; sb < n_in / 256; ++sb) { - // ONE 144-byte block per 256-element SUPERBLOCK, with all four steps' qs bytes filled BEFORE the - // decode. The previous version decoded a fresh block per STEP and then read all 256 elements - // from each, so three quarters of every decode came from zeroed qs - four decodes of a - // quarter-filled block per superblock, which is the whole of the 1.17e4 disagreement. - // `scripts/probe_q4k_groups.cpp` builds it this way and agrees exactly, group by group. - blk.assign(144, 0); - blk[0] = (uint8_t) (r.d & 0xFF); - blk[1] = (uint8_t) (r.d >> 8); - blk[2] = (uint8_t) (r.dmin & 0xFF); - blk[3] = (uint8_t) (r.dmin >> 8); - for (int j = 0; j < 4; ++j) { // the exact inverse of get_scale_min_k4 - blk[4 + j] = (uint8_t) ((r.sc[j] & 0x3F) | ((r.sc[j + 4] >> 4) << 6)); - blk[8 + j] = (uint8_t) ((r.m[j] & 0x3F) | ((r.m[j + 4] >> 4) << 6)); - blk[12 + j] = (uint8_t) ((r.sc[j + 4] & 0x0F) | ((r.m[j + 4] & 0x0F) << 4)); - } - for (int step = 0; step < 4; ++step) { - for (int l = 0; l < 32; ++l) { // elements 0..31 LOW nibbles, 32..63 HIGH - const long long e0 = o * n_in + sb * 256 + step * 64 + l; - const long long e1 = e0 + 32; - blk[16 + step * 32 + l] = - (uint8_t) ((codes_el[(size_t) e0] & 0x0F) | (codes_el[(size_t) e1] << 4)); - } - } - strata::dequantize_q4_K(blk.data(), dec.data()); - for (int j = 0; j < 256; ++j) { - const float term = dec[(size_t) j] * strata::fp16_to_fp32(x[(size_t) (sb * 256 + j)]); - acc += term; - sum_abs += std::fabs((double) term); // the CONDITION of this dot product - - // THE THIRD DECODE. (a) the raw block through the scalar dequantizer, (b) the canonical - // PLANES through `code*scale + offset`, (c) the GPU. If (a) != (b) then this test built - // planes that disagree with its own raw block and the kernel is innocent; if (a) == (b) and - // (c) differs, the kernel is wrong. Without (b) there is no way to tell which. - const long long elem = sb * 256 + j; - const long long g = elem / 32; - const int code = (int) codes_el[(size_t) (o * n_in + elem)]; - const float b_dec = (float) code * scales[(size_t) (o * n_groups + g)] + - offsets[(size_t) (o * n_groups + g)]; - if (std::fabs((double) (b_dec - dec[(size_t) j])) > plane_ref_diff) { - plane_ref_diff = std::fabs((double) (b_dec - dec[(size_t) j])); - } - } - } - ref[(size_t) o] = acc; - cond[(size_t) o] = sum_abs; - if (!(plane_ref_diff <= worst_plane_ref)) worst_plane_ref = plane_ref_diff; - } - - uint16_t* d_x = nullptr; - uint8_t* d_codes = nullptr; - float *d_scales = nullptr, *d_offsets = nullptr, *d_y = nullptr; - check(cudaMalloc(&d_x, x.size() * sizeof(uint16_t)), "cudaMalloc x"); - check(cudaMalloc(&d_codes, codes.size()), "cudaMalloc codes"); - check(cudaMalloc(&d_scales, scales.size() * sizeof(float)), "cudaMalloc scales"); - check(cudaMalloc(&d_offsets, offsets.size() * sizeof(float)), "cudaMalloc offsets"); - check(cudaMalloc(&d_y, (size_t) n_out * sizeof(float)), "cudaMalloc y"); - check(cudaMemcpy(d_x, x.data(), x.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "copy x"); - check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "copy codes"); - check(cudaMemcpy(d_scales, scales.data(), scales.size() * sizeof(float), cudaMemcpyHostToDevice), - "copy scales"); - check(cudaMemcpy(d_offsets, offsets.data(), offsets.size() * sizeof(float), cudaMemcpyHostToDevice), - "copy offsets"); - strata::kernels::s_gemv(d_x, d_codes, d_scales, d_offsets, d_y, n_in, n_out, form); - std::vector got((size_t) n_out); - check(cudaMemcpy(got.data(), d_y, got.size() * sizeof(float), cudaMemcpyDeviceToHost), "copy back"); - - // THE ERROR IS MEASURED AGAINST sum|term|, NOT AGAINST THE RESULT. A dot product of 2560 signed terms - // cancels, so `|ref-got| / |ref|` is a statement about the condition number, not about the kernel: a row - // whose terms are ~1e7 and whose result is ~1e3 reports a relative error of 50 for an absolute error of - // 1e-6 of the terms. `sum_abs` is the natural scale of the computation, and comparing to it is what - // makes a tolerance mean "agrees to within rounding" instead of "did not cancel". - long long bad = 0; - double worst = 0.0, worst_res = 0.0; - for (long long o = 0; o < n_out; ++o) { - const double a = ref[(size_t) o], b = got[(size_t) o]; - const double scale = cond[(size_t) o] > 1e-30 ? cond[(size_t) o] : 1e-30; - const double rel = std::fabs(a - b) / scale; - const double rel_res = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30); - if (!(rel <= worst)) worst = rel; - if (!(rel_res <= worst_res)) worst_res = rel_res; - if (!(rel <= tol)) ++bad; - } - double lo = ref[0], hi = ref[0]; - for (float v : ref) { - lo = std::fmin(lo, v); - hi = std::fmax(hi, v); - } - std::printf(" %-10s %lld rows, %lld over tol, worst rel-to-terms %.3e (rel-to-result %.3e)\n", - "S4/Q4_K", n_out, bad, worst, worst_res); - std::printf(" ref spread [%.4g, %.4g], condition (sum|term|) up to %.4g\n", lo, hi, - *std::max_element(cond.begin(), cond.end())); - std::printf(" CPU planes vs CPU raw block: max |diff| = %.3e -> %s\n", worst_plane_ref, - worst_plane_ref == 0.0 - ? "the test is SELF-CONSISTENT" - : "*** THE TEST DISAGREES WITH ITSELF - fix the reference before believing any GPU result ***"); - if (hi - lo <= 0.0) { - std::fprintf(stderr, "VACUOUS: S4/Q4_K reference is constant\n"); - std::exit(1); - } - *total_bad += (int) bad; - cudaFree(d_x); - cudaFree(d_codes); - cudaFree(d_scales); - cudaFree(d_offsets); - cudaFree(d_y); -} - -} // namespace - - -// ------------------------------------------------------------------ benchmark -// -// P2.S10 wants a first measurement and a ledger entry, and the objective is stated in tokens per second, so -// the useful output is not GiB/s but "milliseconds of expert matvec per token". Warm-up runs are discarded -// (the first launch pays module load and page faults) and the MINIMUM is reported alongside the mean, because -// the minimum is the one not polluted by another process on the machine. -void bench_s2_gemv(long long n_in, long long n_out, int iters, int* split_bad) { - using strata::kernels::Codebook; - using strata::kernels::SForm; - const SForm form{2, -1, 64, Codebook::Affine, false}; - const long long n_groups = n_in / 64; - const long long codes_per_row = n_in / 4; - - std::vector codes((size_t) n_out * codes_per_row, 0xA5); - std::vector scales((size_t) n_out * n_groups, 0.001f); - std::vector x((size_t) n_in, 0x3C00); // 1.0 in fp16 - - uint16_t* d_x = nullptr; - uint8_t* d_codes = nullptr; - float *d_scales = nullptr, *d_y = nullptr; - check(cudaMalloc(&d_x, x.size() * sizeof(uint16_t)), "bench x"); - check(cudaMalloc(&d_codes, codes.size()), "bench codes"); - check(cudaMalloc(&d_scales, scales.size() * sizeof(float)), "bench scales"); - check(cudaMalloc(&d_y, (size_t) n_out * sizeof(float)), "bench y"); - check(cudaMemcpy(d_x, x.data(), x.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "bench copy x"); - check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "bench copy codes"); - check(cudaMemcpy(d_scales, scales.data(), scales.size() * sizeof(float), cudaMemcpyHostToDevice), - "bench copy scales"); - - for (int i = 0; i < 3; ++i) strata::kernels::s_gemv(d_x, d_codes, d_scales, nullptr, d_y, n_in, n_out, form); - - std::vector ms; - for (int i = 0; i < iters; ++i) { - const auto t0 = std::chrono::steady_clock::now(); - strata::kernels::s_gemv(d_x, d_codes, d_scales, nullptr, d_y, n_in, n_out, form); - const auto t1 = std::chrono::steady_clock::now(); - ms.push_back(std::chrono::duration(t1 - t0).count()); - } - std::sort(ms.begin(), ms.end()); - double mean = 0; - for (double v : ms) mean += v; - mean /= (double) ms.size(); - - const double weights = (double) n_in * (double) n_out; - const double bytes = (double) n_out * (double) codes_per_row + (double) n_out * n_groups * 4.0; - std::printf("s2_gemv bench [%lld x %lld] %d iters\n", n_in, n_out, iters); - std::printf(" ms per gemv: min %.4f median %.4f mean %.4f\n", ms.front(), ms[ms.size() / 2], mean); - std::printf(" min -> %.1f G weights/s, %.1f GiB/s of S2 streamed\n", weights / ms.front() / 1e6, - bytes / (1024.0 * 1024 * 1024) / (ms.front() / 1000.0)); - - // The projection the objective is stated against: 48 layers x 10 experts x 3 roles, all of one token's - // experts, at the measured per-role rate. This is the VRAM-resident path only - the CPU expert path and - // the KV/attention work are separate and are NOT included. - const double roles_per_token = 48.0 * 10.0 * 3.0; - const double tok_ms = roles_per_token * ms.front(); - std::printf(" per token: %.0f roles x %.4f ms = %.1f ms -> %.1f tok/s (expert matvec only)\n", - roles_per_token, ms.front(), tok_ms, tok_ms > 0 ? 1000.0 / tok_ms : 0.0); - std::printf(" NOTE: expert matvec ONLY. No attention, no KV, no norm, no router, no sampling, and it\n" - " assumes every expert is already resident in VRAM at zero cost.\n"); - - // The NAIVE kernel's output is the reference for the split one. `s_gemv` is checked against the scalar - // dequantizer by this file's parity cases, so its result here is a validated value, and the split kernel - // sums in a different order - so this is a relative comparison, not bit equality. - strata::kernels::s_gemv(d_x, d_codes, d_scales, nullptr, d_y, n_in, n_out, form); - std::vector ref_naive((size_t) n_out); - check(cudaMemcpy(ref_naive.data(), d_y, ref_naive.size() * sizeof(float), cudaMemcpyDeviceToHost), - "copy naive reference"); - - // ---- the row-split variant, same planes, same process ------------------- - // Swept rather than guessed: more threads per row buys parallelism and costs a deeper reduction. - for (int tpr : {32, 64, 128, 256}) { - if (tpr > n_in) continue; - for (int i = 0; i < 3; ++i) { - strata::kernels::s_gemv_split(d_x, d_codes, d_scales, nullptr, d_y, n_in, n_out, form, tpr); - } - std::vector sms; - for (int i = 0; i < iters; ++i) { - const auto t0 = std::chrono::steady_clock::now(); - strata::kernels::s_gemv_split(d_x, d_codes, d_scales, nullptr, d_y, n_in, n_out, form, tpr); - sms.push_back(std::chrono::duration(std::chrono::steady_clock::now() - t0) - .count()); - } - std::sort(sms.begin(), sms.end()); - - // correctness of the thing being timed - std::vector got((size_t) n_out); - check(cudaMemcpy(got.data(), d_y, got.size() * sizeof(float), cudaMemcpyDeviceToHost), - "copy split result"); - long long bad = 0; - double worst = 0.0; - for (long long o = 0; o < n_out; ++o) { - const double a = ref_naive[(size_t) o], b = got[(size_t) o]; - const double rel = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30); - if (!(rel <= worst)) worst = rel; - if (!(rel <= 1e-4)) ++bad; - } - if (bad) { - std::printf(" split tpr=%-4d *** WRONG *** %lld of %lld rows differ, worst rel %.3e\n", tpr, - bad, n_out, worst); - *split_bad += (int) bad; - } - - // ---- the quad-amortised S2 kernel, timed AND checked against the naive reference ---- - // Only meaningful for S2: it assumes four elements share one code byte, which is true of 2-bit codes. - if (form.code_bits == 2 && (n_in % 64) == 0) { - for (int t2 : {32, 64, 128}) { - for (int i = 0; i < 3; ++i) { - strata::kernels::s2_gemv_quads(d_x, d_codes, d_scales, d_y, n_in, n_out, t2); - } - std::vector qms; - for (int i = 0; i < iters; ++i) { - const auto q0 = std::chrono::steady_clock::now(); - strata::kernels::s2_gemv_quads(d_x, d_codes, d_scales, d_y, n_in, n_out, t2); - qms.push_back(std::chrono::duration( - std::chrono::steady_clock::now() - q0).count()); - } - std::sort(qms.begin(), qms.end()); - check(cudaMemcpy(got.data(), d_y, got.size() * sizeof(float), cudaMemcpyDeviceToHost), - "copy quads result"); - long long qbad = 0; - double qworst = 0.0; - for (long long o = 0; o < n_out; ++o) { - const double a = ref_naive[(size_t) o], b = got[(size_t) o]; - const double rel = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30); - if (rel > qworst) qworst = rel; - if (!(rel <= 1e-4)) ++qbad; - } - if (qbad) *split_bad += (int) qbad; - std::printf(" quads tpr=%-4d min %.4f ms -> %6.1f G weights/s vs naive %.2fx %s\n", t2, - qms.front(), weights / qms.front() / 1e6, ms.front() / qms.front(), - qbad ? "*** WRONG ***" : "checked ok"); - } - } - - // ---- the two-lever kernel, both configurations, timed AND checked ---- - if (form.code_bits == 2 && (n_in % 64) == 0) { - for (int staged = 0; staged < 2; ++staged) { - for (int t3 : {32, 64, 128}) { - for (int i = 0; i < 3; ++i) { - strata::kernels::s2_gemv_fast(d_x, d_codes, d_scales, d_y, n_in, n_out, t3, staged != 0); - } - std::vector fms; - for (int i = 0; i < iters; ++i) { - const auto q0 = std::chrono::steady_clock::now(); - strata::kernels::s2_gemv_fast(d_x, d_codes, d_scales, d_y, n_in, n_out, t3, staged != 0); - fms.push_back(std::chrono::duration( - std::chrono::steady_clock::now() - q0).count()); - } - std::sort(fms.begin(), fms.end()); - check(cudaMemcpy(got.data(), d_y, got.size() * sizeof(float), cudaMemcpyDeviceToHost), - "copy fast result"); - long long fbad = 0; - for (long long o = 0; o < n_out; ++o) { - const double a = ref_naive[(size_t) o], b = got[(size_t) o]; - const double rel = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30); - if (!(rel <= 1e-4)) ++fbad; - } - if (fbad) *split_bad += (int) fbad; - std::printf(" fast %s tpr=%-4d min %.4f ms -> %6.1f G weights/s vs naive %.2fx %s\n", - staged ? "staged" : "global", t3, fms.front(), - weights / fms.front() / 1e6, ms.front() / fms.front(), - fbad ? "*** WRONG ***" : "checked ok"); - } - } - } - - const double sp = ms.front() / sms.front(); - std::printf(" split tpr=%-4d min %.4f ms -> %6.1f G weights/s speedup vs naive %.2fx\n", tpr, - sms.front(), weights / sms.front() / 1e6, sp); - } - - cudaFree(d_x); - cudaFree(d_codes); - cudaFree(d_scales); - cudaFree(d_y); -} - -int main(int argc, char** argv) { - long long n_in = 2560; - long long n_out = 128; - // 1e-4, not 1e-5: the measured worst is ~1e-5 (FMA contraction of a 2560-term f32 accumulation), so a - // 1e-5 threshold would pass by 4% and fail on a different n_in. The phase spec allows 1e-3 for FP16 - // paths; this is 10x tighter than the spec and 10x looser than the measurement. - double tol = 1e-4; - bool selftest = false; - bool bench = false; - int iters = 200; - for (int i = 1; i < argc; ++i) { - const std::string a = argv[i]; - if (a == "--selftest") selftest = true; - else if (a == "--bench") bench = true; - else if (a == "--iters" && i + 1 < argc) iters = std::atoi(argv[++i]); - else if (a == "--n-in" && i + 1 < argc) n_in = std::atoll(argv[++i]); - else if (a == "--n-out" && i + 1 < argc) n_out = std::atoll(argv[++i]); - else { - std::fprintf(stderr, "usage: s_gemv_parity [--selftest] [--n-in N] [--n-out N]\n"); - return 2; - } - } - - using strata::kernels::Codebook; - using strata::kernels::SForm; - std::vector cases; - cases.push_back({"S2/Q2_0", SForm{2, -1, 64, Codebook::Affine, false}, 18, q2_0_to_raw, q2_0_deq}); - cases.push_back({"S4/Q4_0", SForm{4, -8, 32, Codebook::Affine, false}, 18, q4_0_to_raw, q4_0_deq}); - cases.push_back({"S4/IQ4_NL", SForm{4, 0, 32, Codebook::Iq4Nl, false}, 18, iq4_to_raw, iq4_deq}); - cases.push_back({"S8/Q8_0", SForm{8, -128, 32, Codebook::Affine, false}, 34, q8_0_to_raw, q8_0_deq}); - - std::mt19937 rng(4242); - const int n_scales = (int) (sizeof(kScales) / sizeof(kScales[0])); - int total_bad = 0; - - for (const Case& tc : cases) { - const int bits = tc.form.code_bits; - const int per_byte = 8 / bits; - const int G = tc.form.group_elems; - const long long n_groups = n_in / G; - const long long codes_per_row = n_in / per_byte; - - // activations - std::vector x((size_t) n_in); - for (long long i = 0; i < n_in; ++i) x[(size_t) i] = kScales[rng() % n_scales]; - - // Codes are generated ONE PER ELEMENT and then packed into the plane the kernel reads. - // - // The first version of this test generated a random BYTE ARRAY and used it as both, which is the bug - // that made S2 pass and the other three fail by 50x-500x. The two are not the same thing: the kernel - // reads element i from byte i/per_byte at bit (i%per_byte)*bits, while the reference needs one code per - // element to rebuild a raw GGUF block. For S2 (per_byte = 4, which IS Q2_0's own raw layout) treating - // one random array as both happened to agree - and that coincidence is exactly what a test must not - // depend on. - std::vector codes_el((size_t) n_out * n_in); - for (size_t i = 0; i < codes_el.size(); ++i) codes_el[i] = (uint8_t) (rng() & ((1u << bits) - 1)); - std::vector codes((size_t) n_out * codes_per_row, 0); - for (long long o = 0; o < n_out; ++o) { - for (long long i = 0; i < n_in; ++i) { - const long long byi = o * codes_per_row + i / per_byte; - codes[(size_t) byi] |= (uint8_t) (codes_el[(size_t) (o * n_in + i)] - << ((i % per_byte) * bits)); - } - } - std::vector scales((size_t) n_out * n_groups); - std::vector scale_bits((size_t) n_out * n_groups); - for (size_t i = 0; i < scales.size(); ++i) { - scale_bits[i] = kScales[rng() % n_scales]; - scales[i] = strata::fp16_to_fp32(scale_bits[i]); - } - - // CPU reference - std::vector ref((size_t) n_out, 0.0f); - std::vector raw((size_t) tc.raw_bytes); - std::vector dec((size_t) G); - for (long long o = 0; o < n_out; ++o) { - float acc = 0.0f; - for (long long g = 0; g < n_groups; ++g) { - const size_t co = (size_t) o * n_in + (size_t) g * G; // the UNPACKED code array - const size_t so = (size_t) o * n_groups + (size_t) g; - // The raw block carries the scale as fp16 and the canonical plane carries it widened, so the - // block is rebuilt from the PATTERN the plane came from. No float-to-fp16 conversion is - // needed anywhere, and the decoder therefore sees bit-identically what the kernel reads. - const int n = tc.to_raw(codes_el.data(), co, scale_bits.data(), so, raw.data()); - tc.dequant(raw.data(), dec.data()); - for (long long j = 0; j < (long long) n; ++j) { - acc += dec[(size_t) j] * strata::fp16_to_fp32(x[(size_t) (g * G + j)]); - } - } - ref[(size_t) o] = acc; - } - - // GPU - uint16_t* d_x = nullptr; - uint8_t* d_codes = nullptr; - float *d_scales = nullptr, *d_y = nullptr; - check(cudaMalloc(&d_x, x.size() * sizeof(uint16_t)), "cudaMalloc x"); - check(cudaMalloc(&d_codes, codes.size()), "cudaMalloc codes"); - check(cudaMalloc(&d_scales, scales.size() * sizeof(float)), "cudaMalloc scales"); - check(cudaMalloc(&d_y, (size_t) n_out * sizeof(float)), "cudaMalloc y"); - check(cudaMemcpy(d_x, x.data(), x.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "copy x"); - check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "copy codes"); - check(cudaMemcpy(d_scales, scales.data(), scales.size() * sizeof(float), cudaMemcpyHostToDevice), - "copy scales"); - strata::kernels::s_gemv(d_x, d_codes, d_scales, nullptr, d_y, n_in, n_out, tc.form); - std::vector got((size_t) n_out); - check(cudaMemcpy(got.data(), d_y, got.size() * sizeof(float), cudaMemcpyDeviceToHost), "copy back"); - - long long bad = 0; - double worst = 0.0; - for (long long o = 0; o < n_out; ++o) { - const double a = ref[(size_t) o], b = got[(size_t) o]; - const double rel = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30); - if (!(rel <= worst)) worst = rel; - if (!(rel <= tol)) ++bad; - } - double lo = ref[0], hi = ref[0]; - for (float v : ref) { - lo = std::fmin(lo, v); - hi = std::fmax(hi, v); - } - std::printf(" %-10s %lld rows, %lld over tol, worst rel %.3e ref spread [%.4g, %.4g]\n", tc.name, - n_out, bad, worst, lo, hi); - if (hi - lo <= 0.0) { - std::fprintf(stderr, "VACUOUS: %s reference is constant\n", tc.name); - return 1; - } - total_bad += (int) bad; - - cudaFree(d_x); - cudaFree(d_codes); - cudaFree(d_scales); - cudaFree(d_y); - } - - std::printf("s_gemv: %zu type cases, %d rows over tolerance (tol %.1e)\n", cases.size(), total_bad, tol); - // Q4_K IS NOT PART OF THE DEFAULT RUN. It FAILS: 128 of 128 rows, worst error 0.586 of sum|term| - a - // real difference, not cancellation (the condition number is 2.8e7 and the error is 1.6e7). Either the - // kernel's offset handling or this test's reconstruction of a Q4_K block is wrong and the two have not - // been separated yet. Running it by default would turn ctest red and hide regressions in the four cases - // that ARE verified; leaving it out silently would be worse. It is one flag away, and it is recorded as - // OPEN in the project state. - // Q4_K is IN the default run as of round 171. Rounds 169-170 gated it because it FAILED, and the - // failure was this test's own reconstruction of a Q4_K block - four decodes of a quarter-filled block per - // superblock - not the kernel. It now agrees to 2.8e-07 of sum|term|, so the gate goes rather than - // staying as a habit: a gate that outlives its reason is a check that quietly stopped running. - test_q4k(n_in, n_out, tol, &total_bad); - std::printf("s_gemv total: %d rows over tolerance\n", total_bad); - if (bench) { - // the real expert shapes: gate/up are [2560 x 640], down is [640 x 2560] - int split_bad = 0; - bench_s2_gemv(2560, 640, iters, &split_bad); - bench_s2_gemv(640, 2560, iters, &split_bad); - std::printf("split kernel rows disagreeing with the naive reference: %d\n", split_bad); - // accumulated HERE, inside the block that declares it, and it makes the binary FAIL: a kernel that is - // benchmarked but never compared is an unverified kernel being quoted for performance. - total_bad += split_bad; - } - if (total_bad) return 1; - if (selftest) std::printf("s_gemv_parity OK\n"); - return 0; -} diff --git a/src/kernels/s_gemv_q8k_parity.cpp b/src/kernels/s_gemv_q8k_parity.cpp deleted file mode 100644 index 5bfb475..0000000 --- a/src/kernels/s_gemv_q8k_parity.cpp +++ /dev/null @@ -1,343 +0,0 @@ -// src/kernels/s_gemv_q8k_parity.cpp - the Q8_K activation path of `s_gemv`. -// -// THE POINT OF THIS KERNEL IS A CONTRACT, so the test is built around the contract rather than around the -// arithmetic: -// -// 1. the kernel against a host reference that dequantizes the SAME Q8_K bytes and the SAME S-form planes, -// in double - so what is under test is the indexing, not the format; -// 2. the Q8_K activation is produced by the ACTUAL `quantize_q8_K`, which is byte-exact against ggml -// (round 198). Building the activation by hand here would make this a test of two transcriptions; -// 3. **THE Q8_K-vs-FP16 GAP IS MEASURED**, because that is the number the whole activation-contract -// decision rests on and it has only ever been measured on Q2_0 weights (0.6175%) and on BF16 ones -// (0.141-0.156%). A K-quant weight is a third case and it is the one the dense projections use. -#include "strata/kernels/f16_bits.hpp" -#include "strata/kernels/quantize_act.hpp" -#include "strata/kernels/s_gemv.hpp" - -#include - -#include -#include -#include -#include -#include -#include - -namespace { - -using strata::kernels::SForm; -using strata::kernels::Codebook; - -void check(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -/// The host decode, transcribed from `docs/pack-format.md`'s rule: `value = cb[code] * scale + offset`, with -/// the integer bias applied INSIDE the integer domain before the one multiply. -const signed char kIq4Nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113}; - -double weight_at(const std::vector& codes, const std::vector& scales, - const std::vector& offset, const SForm& f, long long n_in, long long o, long long i) { - const int per_byte = 8 / f.code_bits; - const long long codes_per_row = n_in / per_byte; - const long long n_groups = n_in / f.group_elems; - const uint8_t* c = codes.data() + o * codes_per_row; - const int code = (c[i / per_byte] >> ((int) (i % per_byte) * f.code_bits)) & ((1 << f.code_bits) - 1); - const double v = (f.codebook == Codebook::Iq4Nl) ? (double) kIq4Nl[code & 0x0F] - : (double) (code + f.code_bias); - const long long g = i / f.group_elems; - double w = v * (double) scales[(size_t) (o * n_groups + g)]; - if (f.has_offset) w += (double) offset[(size_t) (o * n_groups + g)]; - return w; -} - -/// Dequantize a block_q8_K buffer on the host: 292 bytes per 256 elements. -double q8k_at(const std::vector& x, long long i) { - const uint8_t* blk = x.data() + (size_t) (i / 256) * 292; - float d; - std::memcpy(&d, blk, 4); - const int8_t q = ((const int8_t*) (blk + 4))[i % 256]; - return (double) d * (double) q; -} - -struct Case { - const char* what; - int bits; - int bias; - int group; - Codebook cb; - bool has_offset; -}; - -/// THE RAGGED LAST BLOCK. The split kernels give each warp one row and a block eight warps, so with -/// `n_out % 8 != 0` the last block holds warps that have no row. Those warps used to return BEFORE the -/// codebook barrier - undefined behaviour that every real shape (a multiple of 8) avoided. Here `n_out` is -/// deliberately ragged, every row is checked against the host reference over the same bytes, and a guard -/// band past `n_out` must come back untouched: a warp without a row must neither hang the block nor write. -/// (`compute-sanitizer --tool synccheck` on this binary is the direct check of the barrier itself.) -int ragged_rows(const Case& cs, long long n_out) { - const long long n_in = 512; - const long long guard = 64; - std::mt19937 rng(77 + (unsigned) n_out); - std::normal_distribution g(0.0f, 1.0f); - std::vector xf((size_t) n_in); - for (auto& v : xf) v = g(rng); - SForm f; - f.code_bits = cs.bits; - f.code_bias = cs.bias; - f.group_elems = cs.group; - f.codebook = cs.cb; - f.has_offset = cs.has_offset; - const int per_byte = 8 / cs.bits; - std::vector codes((size_t) (n_out * n_in / per_byte)); - for (auto& v : codes) v = (uint8_t) (rng() & 0xFF); - const long long n_groups = n_in / cs.group; - std::vector scales((size_t) (n_out * n_groups)), offs((size_t) (n_out * n_groups)); - for (auto& v : scales) v = 0.01f + 0.001f * (float) (rng() % 20); - for (auto& v : offs) v = 0.2f * g(rng); - - float* d_xf = nullptr; - uint8_t *d_xk = nullptr, *d_x0 = nullptr, *d_codes = nullptr; - float *d_scales = nullptr, *d_offs = nullptr, *d_y = nullptr; - std::vector xk((size_t) (n_in / 256) * 292), x0((size_t) (n_in / 32) * 34); - check(cudaMalloc(&d_xf, (size_t) n_in * 4), "rxf"); - check(cudaMalloc(&d_xk, xk.size()), "rxk"); - check(cudaMalloc(&d_x0, x0.size()), "rx0"); - check(cudaMalloc(&d_codes, codes.size()), "rcodes"); - check(cudaMalloc(&d_scales, scales.size() * 4), "rscales"); - check(cudaMalloc(&d_offs, offs.size() * 4), "roffs"); - check(cudaMalloc(&d_y, (size_t) (n_out + guard) * 4), "ry"); - check(cudaMemcpy(d_xf, xf.data(), (size_t) n_in * 4, cudaMemcpyHostToDevice), "rcxf"); - check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "rcc"); - check(cudaMemcpy(d_scales, scales.data(), scales.size() * 4, cudaMemcpyHostToDevice), "rcs"); - check(cudaMemcpy(d_offs, offs.data(), offs.size() * 4, cudaMemcpyHostToDevice), "rco"); - strata::kernels::quantize_q8_K(d_xf, d_xk, n_in, nullptr); - strata::kernels::quantize_q8_0(d_xf, d_x0, n_in, nullptr); - check(cudaMemcpy(xk.data(), d_xk, xk.size(), cudaMemcpyDeviceToHost), "rcxk"); - check(cudaMemcpy(x0.data(), d_x0, x0.size(), cudaMemcpyDeviceToHost), "rcx0"); - - int bad = 0; - for (int kind = 0; kind < 2; ++kind) { // 0: Q8_K activation, 1: Q8_0 activation - std::vector want((size_t) n_out); - std::vector mag((size_t) n_out); // sum |w_i a_i| per row: a row whose sum cancels near 0 - for (long long o = 0; o < n_out; ++o) { // must not turn f32 rounding into a relative failure - double acc = 0, am = 0; - for (long long i = 0; i < n_in; ++i) { - double a; - if (kind == 0) { - a = q8k_at(xk, i); - } else { - const uint8_t* blk = x0.data() + (size_t) (i / 32) * 34; - uint16_t dbits; - std::memcpy(&dbits, blk, 2); - a = (double) strata::kernels::f32_from_f16(dbits) * (double) ((const int8_t*) (blk + 2))[i % 32]; - } - const double wa = weight_at(codes, scales, offs, f, n_in, o, i) * a; - acc += wa; - am += std::fabs(wa); - } - want[(size_t) o] = (float) acc; - mag[(size_t) o] = am; - } - // the guard band holds a NaN pattern; any write there shows up as a changed bit - std::vector sentinel((size_t) (n_out + guard), 0x7FC0DEADu); - check(cudaMemcpy(d_y, sentinel.data(), sentinel.size() * 4, cudaMemcpyHostToDevice), "rsent"); - if (kind == 0) - strata::kernels::s_gemv_q8k_split(d_xk, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in, - n_out, f, nullptr); - else - strata::kernels::s_gemv_q8_0_split(d_x0, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in, - n_out, f, nullptr); - check(cudaDeviceSynchronize(), "ragged split"); - std::vector got_bits(sentinel.size()); - check(cudaMemcpy(got_bits.data(), d_y, got_bits.size() * 4, cudaMemcpyDeviceToHost), "rcy"); - double m = 0, d = 0; - for (long long o = 0; o < n_out; ++o) { - float v; - std::memcpy(&v, &got_bits[(size_t) o], 4); - m += mag[(size_t) o]; - d += std::fabs((double) want[(size_t) o] - (double) v); - } - long long touched = 0; - for (long long o = n_out; o < n_out + guard; ++o) touched += got_bits[(size_t) o] != 0x7FC0DEADu; - const double rel = d / (m > 1e-30 ? m : 1e-30); - const bool ok = rel <= 1e-5 && touched == 0; - std::printf(" %-28s %s n_out %3lld: rel %.3e, guard words written %lld %s\n", cs.what, - kind == 0 ? "Q8_K" : "Q8_0", n_out, rel, touched, ok ? "ok" : "*** WRONG ***"); - if (!ok) ++bad; - } - cudaFree(d_xf); cudaFree(d_xk); cudaFree(d_x0); cudaFree(d_codes); cudaFree(d_scales); cudaFree(d_offs); - cudaFree(d_y); - return bad; -} - -} // namespace - -int main(int argc, char** argv) { - bool selftest = false; - for (int i = 1; i < argc; ++i) { - if (std::string(argv[i]) == "--selftest") selftest = true; - else { std::fprintf(stderr, "usage: s_gemv_q8k_parity [--selftest]\n"); return 2; } - } - int bad = 0; - - // The forms the DENSE weights actually use, taken from the manifest rather than invented: - // attn_qkv.weight IQ4_XS S4 group 32, no offset (the GDN mixer's qkv) - // attn_gate.weight Q4_K S4 group 32, offset (the GDN mixer's z) - // ssm_out.weight Q5_K S8 group 32, offset (the GDN mixer's output) - const Case cases[] = { - {"IQ4_XS S4 g32 no-offset", 4, -8, 32, Codebook::Affine, false}, - {"Q4_K S4 g32 offset", 4, 0, 32, Codebook::Affine, true}, - {"Q5_K S8 g32 offset", 8, 0, 32, Codebook::Affine, true}, - }; - - for (const Case& cs : cases) { - const long long n_in = 512, n_out = 64; // 2 Q8_K blocks wide, small enough for a host reference - std::mt19937 rng(2024); - std::normal_distribution g(0.0f, 1.0f); - std::vector xf((size_t) n_in); - for (auto& v : xf) v = g(rng); - - SForm f; - f.code_bits = cs.bits; - f.code_bias = cs.bias; - f.group_elems = cs.group; - f.codebook = cs.cb; - f.has_offset = cs.has_offset; - - const int per_byte = 8 / cs.bits; - std::vector codes((size_t) (n_out * n_in / per_byte)); - for (auto& v : codes) v = (uint8_t) (rng() & 0xFF); - const long long n_groups = n_in / cs.group; - std::vector scales((size_t) (n_out * n_groups)), offs((size_t) (n_out * n_groups)); - for (auto& v : scales) v = 0.01f + 0.001f * (float) (rng() % 20); - for (auto& v : offs) v = 0.2f * g(rng); - - // ---- the activation, from the REAL quantizer - std::vector xq8k((size_t) (n_in / 256) * 292); - float* d_xf = nullptr; - uint8_t* d_xq = nullptr; - check(cudaMalloc(&d_xf, (size_t) n_in * 4), "xf"); - check(cudaMalloc(&d_xq, xq8k.size()), "xq"); - check(cudaMemcpy(d_xf, xf.data(), (size_t) n_in * 4, cudaMemcpyHostToDevice), "cxf"); - strata::kernels::quantize_q8_K(d_xf, d_xq, n_in, nullptr); - check(cudaMemcpy(xq8k.data(), d_xq, xq8k.size(), cudaMemcpyDeviceToHost), "cxq"); - - // ---- host reference in double, over the same bytes - std::vector want((size_t) n_out, 0.0f); - for (long long o = 0; o < n_out; ++o) { - double acc = 0; - for (long long i = 0; i < n_in; ++i) - acc += weight_at(codes, scales, offs, f, n_in, o, i) * q8k_at(xq8k, i); - want[(size_t) o] = (float) acc; - } - - // ---- device - uint8_t* d_codes = nullptr; - float *d_scales = nullptr, *d_offs = nullptr, *d_y = nullptr; - check(cudaMalloc(&d_codes, codes.size()), "codes"); - check(cudaMalloc(&d_scales, scales.size() * 4), "scales"); - check(cudaMalloc(&d_offs, offs.size() * 4), "offs"); - check(cudaMalloc(&d_y, (size_t) n_out * 4), "y"); - check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "cc"); - check(cudaMemcpy(d_scales, scales.data(), scales.size() * 4, cudaMemcpyHostToDevice), "cs"); - check(cudaMemcpy(d_offs, offs.data(), offs.size() * 4, cudaMemcpyHostToDevice), "co"); - - std::vector naive((size_t) n_out), warp((size_t) n_out); - strata::kernels::s_gemv_q8k(d_xq, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in, n_out, - f, nullptr); - check(cudaMemcpy(naive.data(), d_y, (size_t) n_out * 4, cudaMemcpyDeviceToHost), "cy1"); - strata::kernels::s_gemv_q8k_split(d_xq, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in, - n_out, f, nullptr); - check(cudaMemcpy(warp.data(), d_y, (size_t) n_out * 4, cudaMemcpyDeviceToHost), "cy2"); - - double mag = 0, d1 = 0, d2 = 0; - for (long long o = 0; o < n_out; ++o) { - mag += std::fabs((double) want[(size_t) o]); - d1 += std::fabs((double) want[(size_t) o] - (double) naive[(size_t) o]); - d2 += std::fabs((double) want[(size_t) o] - (double) warp[(size_t) o]); - } - std::printf(" %-28s naive %.3e warp %.3e\n", cs.what, d1 / mag, d2 / mag); - // The kernel accumulates in f32, the reference in f64, over 512 terms with values of similar size. - // 1e-5 is the arithmetic's floor, not a structural allowance. - if (!(d1 / mag <= 1e-5 && d2 / mag <= 1e-5)) { std::printf(" *** over 1e-5 ***\n"); ++bad; } - - // ---- 2b. THE Q8_0 ACTIVATION, on the SAME weight planes. `s_gemv_q8_0_split` exists because the - // legacy block formats want Q8_0 and `ffn_down_shexp` cannot use Q8_K at all (n_in = 640 is not a - // multiple of 256). It shares every line with the Q8_K kernel except the activation loader, so what - // this checks is the LOADER - the 34-byte block, the fp16 `d`, and the element index inside it. - { - std::vector xq0((size_t) (n_in / 32) * 34); - uint8_t* d_x0 = nullptr; - check(cudaMalloc(&d_x0, xq0.size()), "x0"); - strata::kernels::quantize_q8_0(d_xf, d_x0, n_in, nullptr); - check(cudaMemcpy(xq0.data(), d_x0, xq0.size(), cudaMemcpyDeviceToHost), "cx0"); - - // the host reference over the SAME Q8_0 bytes, with the same weight decode - std::vector want0((size_t) n_out, 0.0f); - for (long long o = 0; o < n_out; ++o) { - double acc = 0; - for (long long i = 0; i < n_in; ++i) { - const uint8_t* blk = xq0.data() + (size_t) (i / 32) * 34; - uint16_t dbits; - std::memcpy(&dbits, blk, 2); - const double d = (double) strata::kernels::f32_from_f16(dbits); - const int8_t q = ((const int8_t*) (blk + 2))[i % 32]; - acc += weight_at(codes, scales, offs, f, n_in, o, i) * d * (double) q; - } - want0[(size_t) o] = (float) acc; - } - strata::kernels::s_gemv_q8_0_split(d_x0, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, - n_in, n_out, f, nullptr); - std::vector got0((size_t) n_out); - check(cudaMemcpy(got0.data(), d_y, (size_t) n_out * 4, cudaMemcpyDeviceToHost), "cy0"); - double m0 = 0, dd0 = 0; - for (long long o = 0; o < n_out; ++o) { - m0 += std::fabs((double) want0[(size_t) o]); - dd0 += std::fabs((double) want0[(size_t) o] - (double) got0[(size_t) o]); - } - std::printf(" %-28s Q8_0 act %.3e\n", cs.what, dd0 / (m0 > 1e-30 ? m0 : 1e-30)); - if (!(dd0 / (m0 > 1e-30 ? m0 : 1e-30) <= 1e-5)) { - std::printf(" *** the Q8_0 activation loader is WRONG ***\n"); - ++bad; - } - check(cudaFree(d_x0), "fx0"); - } - - // ---- 3. THE Q8_K vs FP16 GAP, on a K-quant weight - the case the contract decision needs - { - std::vector x16((size_t) n_in); - for (long long i = 0; i < n_in; ++i) x16[(size_t) i] = strata::kernels::f16_from_f32(xf[(size_t) i]); - uint16_t* d_x16 = nullptr; - check(cudaMalloc(&d_x16, (size_t) n_in * 2), "x16"); - check(cudaMemcpy(d_x16, x16.data(), (size_t) n_in * 2, cudaMemcpyHostToDevice), "cx16"); - std::vector fp16out((size_t) n_out); - strata::kernels::s_gemv(d_x16, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in, n_out, - f); - check(cudaMemcpy(fp16out.data(), d_y, (size_t) n_out * 4, cudaMemcpyDeviceToHost), "cy3"); - double dd = 0; - for (long long o = 0; o < n_out; ++o) - dd += std::fabs((double) naive[(size_t) o] - (double) fp16out[(size_t) o]); - const double rel = dd / mag; - const bool visible = rel > 1e-3; - std::printf(" %-24s %s (%.4f%% apart, tolerance 0.1%%)\n", "Q8_K vs fp16 activation", - visible ? "yes" : "*** NO ***", rel * 100); - if (!visible) ++bad; - cudaFree(d_x16); - } - cudaFree(d_xf); cudaFree(d_xq); cudaFree(d_codes); cudaFree(d_scales); cudaFree(d_offs); cudaFree(d_y); - } - - // ---- 4. output widths that are NOT a multiple of the eight rows per block - std::printf("\n"); - for (const Case& cs : cases) - for (long long n_out : {1LL, 7LL, 9LL, 61LL}) bad += ragged_rows(cs, n_out); - - std::printf("\ns_gemv_q8k: %d failures\n", bad); - if (bad) return 1; - if (selftest) std::printf("s_gemv_q8k_parity OK\n"); - return 0; -} diff --git a/src/kernels/sampler_parity.cpp b/src/kernels/sampler_parity.cpp deleted file mode 100644 index 2351722..0000000 --- a/src/kernels/sampler_parity.cpp +++ /dev/null @@ -1,1284 +0,0 @@ -// src/kernels/sampler_parity.cpp - P2.S2's test for the sampler chain. -// -// THE CHECK THAT MATTERS IS THAT THE ORDER IS OBSERVABLE. A sampler in the wrong order still returns a valid -// token, so "it produced a token" proves nothing; and because temperature is MONOTONIC it does not change which -// tokens `top_k` keeps, so a top-k-only fixture cannot see the order either. What it changes is `top_p`'s CUT: -// at T < 1 the distribution sharpens, the cumulative mass reaches p sooner, and fewer tokens survive. -// -// So this builds a fixture where that happens, computes the greedy pick under BOTH orders, and requires them to -// DIFFER - then requires the kernel to agree with the specified one. Without the first half, the test would -// pass against either order. -#include "strata/kernels/sampler.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { - -void check(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -// The host reference for the specified order: top_k -> top_p -> temperature -> argmax. -// `temp_first` swaps the first and last stages, which is the intuitive-but-wrong order. -int reference_pick(const std::vector& l, const strata::kernels::SamplerParams& p, bool temp_first) { - const int nv = (int) l.size(); - const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f; - auto val = [&](int v) { return temp_first ? l[(size_t) v] * inv_t : l[(size_t) v]; }; - - std::vector ids; - const int k = p.top_k > 0 ? p.top_k : nv; - std::vector taken((size_t) nv, 0); - for (int i = 0; i < k; ++i) { - int best = -1; - float bv = 0; - for (int v = 0; v < nv; ++v) { - if (taken[(size_t) v]) continue; - if (best < 0 || val(v) > bv) { best = v; bv = val(v); } - } - taken[(size_t) best] = 1; - ids.push_back(best); - } - if (p.top_p < 1.0f) { - float mx = val(ids[0]); - for (int v : ids) mx = std::fmax(mx, val(v)); - double sum = 0; - for (int v : ids) sum += std::exp((double) val(v) - (double) mx); - double cum = 0; - int cut = (int) ids.size(); - for (size_t i = 0; i < ids.size(); ++i) { - cum += std::exp((double) val(ids[i]) - (double) mx) / sum; - if (cum >= (double) p.top_p) { cut = (int) i + 1; break; } - } - if (cut < p.min_keep) cut = p.min_keep < (int) ids.size() ? p.min_keep : (int) ids.size(); - ids.resize((size_t) cut); - } - return ids[0]; // greedy: the largest SURVIVING logit, and `ids` is in descending order -} - -// The number of survivors AFTER top_p, in the given order - the quantity the order actually changes. -int reference_cut(const std::vector& l, const strata::kernels::SamplerParams& p, bool temp_first) { - const int nv = (int) l.size(); - const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f; - auto val = [&](int v) { return temp_first ? l[(size_t) v] * inv_t : l[(size_t) v]; }; - const int k = p.top_k > 0 ? p.top_k : nv; - std::vector ids; - std::vector taken((size_t) nv, 0); - for (int i = 0; i < k; ++i) { - int best = -1; float bv = 0; - for (int v = 0; v < nv; ++v) { - if (taken[(size_t) v]) continue; - if (best < 0 || val(v) > bv) { best = v; bv = val(v); } - } - taken[(size_t) best] = 1; ids.push_back(best); - } - if (p.top_p < 1.0f) { - float mx = val(ids[0]); - for (int v : ids) mx = std::fmax(mx, val(v)); - double sum = 0; - for (int v : ids) sum += std::exp((double) val(v) - (double) mx); - double cum = 0; - int cut = (int) ids.size(); - for (size_t i = 0; i < ids.size(); ++i) { - cum += std::exp((double) val(ids[i]) - (double) mx) / sum; - if (cum >= (double) p.top_p) { cut = (int) i + 1; break; } - } - if (cut < p.min_keep) cut = p.min_keep < (int) ids.size() ? p.min_keep : (int) ids.size(); - return cut; - } - return (int) ids.size(); -} - -int run(const char* name, const std::vector& logits, int n_tokens, const strata::kernels::SamplerParams& p, - const std::vector& want, const std::vector& hist = {}, int hist_len = 0) { - float* d_l = nullptr; - int* d_o = nullptr; - check(cudaMalloc(&d_l, logits.size() * sizeof(float)), "malloc logits"); - check(cudaMalloc(&d_o, (size_t) n_tokens * sizeof(int)), "malloc out"); - check(cudaMemcpy(d_l, logits.data(), logits.size() * sizeof(float), cudaMemcpyHostToDevice), "copy"); - // -1 in every output slot first: a row the kernel leaves unwritten can never match (a verify window reads - // every row, so "no output" is a wrong answer, not a skipped one) - check(cudaMemset(d_o, 0xFF, (size_t) n_tokens * sizeof(int)), "fill out"); - int* d_h = nullptr; - if (hist_len > 0) { - check(cudaMalloc(&d_h, hist.size() * sizeof(int)), "malloc hist"); - check(cudaMemcpy(d_h, hist.data(), hist.size() * sizeof(int), cudaMemcpyHostToDevice), "copy hist"); - } - strata::kernels::sample_tokens(d_l, n_tokens, (int) (logits.size() / n_tokens), d_h, hist_len, p, d_o, - nullptr); - std::vector got((size_t) n_tokens); - check(cudaMemcpy(got.data(), d_o, got.size() * sizeof(int), cudaMemcpyDeviceToHost), "back"); - int bad = 0; - for (int t = 0; t < n_tokens; ++t) if (got[(size_t) t] != want[(size_t) t]) ++bad; - std::printf(" %-34s %s (%d of %d differ)", name, bad ? "*** WRONG ***" : "matches", bad, n_tokens); - if (bad) std::printf(" first: want %d got %d", want[0], got[0]); - std::printf("\n"); - cudaFree(d_l); - cudaFree(d_o); - if (d_h) cudaFree(d_h); - return bad; -} - -// The Philox draw, host side - a transcription of the kernel's `philox_uniform` so the SAMPLED pick (not -// just the greedy argmax) can be pinned against a reference. `__umulhi(a, b)` is the high half of a 32x32 -// multiply, spelled `(uint32_t)(((uint64_t) a * b) >> 32)` here. -struct PhiloxRound { - uint32_t& c0; uint32_t& c1; uint32_t& c2; uint32_t& c3; - void step(uint32_t k0, uint32_t k1) const { - const uint32_t hi0 = (uint32_t) (((uint64_t) 0x9E3779B9u * c0) >> 32); - const uint32_t hi1 = (uint32_t) (((uint64_t) 0xBB67AE85u * c2) >> 32); - const uint32_t lo0 = 0x9E3779B9u * c0; - const uint32_t lo1 = 0xBB67AE85u * c2; - const uint32_t n0 = hi1 ^ c1 ^ k0; - const uint32_t n1 = lo1; - const uint32_t n2 = hi0 ^ c3 ^ k1; - const uint32_t n3 = lo0; - c0 = n0; c1 = n1; c2 = n2; c3 = n3; - } -}; - -float host_philox_uniform(uint64_t seed, uint64_t counter) { - uint32_t c0 = (uint32_t) counter, c1 = (uint32_t) (counter >> 32); - uint32_t c2 = (uint32_t) seed, c3 = (uint32_t) (seed >> 32); - PhiloxRound r{c0, c1, c2, c3}; - for (int i = 0; i < 10; ++i) r.step((uint32_t) i, 0u); - return (float) (c0 >> 8) * (1.0f / 16777216.0f); -} - -// The full SAMPLED chain, host side - the kernel's `sampler_kernel` in serial form, in llama.cpp's order: -// penalties on the raw logits during the top_k selection (ties to the lowest index), top_p's cut in double over -// the top_k list, the min_p prefix cut on its survivors, the temperature, and one Philox draw at -// (seed, counter + row). One penalties stage (issue #53: this reference used to repeat the kernel's second one). -int sampled_reference(const std::vector& l, const std::vector& hist, - const strata::kernels::SamplerParams& p, int row) { - auto penal = [&](float logit, int count) { - if (count <= 0) return logit; - if (logit <= 0.0f) logit *= p.penalty_repeat; else logit /= p.penalty_repeat; - logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present; - return logit; - }; - auto count = [&](int v) { int c = 0; for (int h : hist) if (h == v) ++c; return c; }; - const int nv = (int) l.size(); - const int KMAX = 64; // 1..64 as given; 0 (off) and wider keep the widest list, 64 - const int k = std::min(nv, (p.top_k > 0 && p.top_k < KMAX) ? p.top_k : KMAX); - std::vector sel_ids; - std::vector sel_logit; - std::vector taken((size_t) nv, 0); - for (int i = 0; i < k; ++i) { - int best = -1; float bv = 0; - for (int v = 0; v < nv; ++v) { - if (taken[(size_t) v]) continue; - const float s = penal(l[(size_t) v], count(v)); - if (best < 0 || s > bv) { best = v; bv = s; } - } - taken[(size_t) best] = 1; - sel_ids.push_back(best); sel_logit.push_back(bv); - } - // llama.cpp's order (issue #53): top_p over the whole top_k list, then min_p on its survivors - const int n_sel = (int) sel_ids.size(); - int n_keep = n_sel; - if (p.top_p < 1.0f) { - double sum = 0.0; - for (int i = 0; i < n_sel; ++i) sum += std::exp((double) sel_logit[(size_t) i] - (double) sel_logit[0]); - double cum = 0.0; - int cut = n_sel; - for (int i = 0; i < n_sel; ++i) { - cum += std::exp((double) sel_logit[(size_t) i] - (double) sel_logit[0]) / sum; - if (cum >= (double) p.top_p) { cut = i + 1; break; } - } - if (cut < p.min_keep) cut = p.min_keep < n_sel ? p.min_keep : n_sel; - n_keep = cut; - } - if (p.min_p > 0.0f) { - const float thresh = sel_logit[0] + std::log(p.min_p); - for (int i = 0; i < n_keep; ++i) - if (sel_logit[(size_t) i] < thresh) { n_keep = i; break; } - } - const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f; - auto scaled = [&](int i) { return sel_logit[(size_t) i] * inv_t; }; // one penalties stage, before (#53) - float smx = scaled(0); - for (int i = 1; i < n_keep; ++i) smx = std::fmax(smx, scaled(i)); - double sum = 0.0; - for (int i = 0; i < n_keep; ++i) sum += std::exp((double) scaled(i) - (double) smx); - const float u = host_philox_uniform(p.seed, p.counter + (uint64_t) row); - double cum = 0.0; - int pick = sel_ids[(size_t) (n_keep - 1)]; - for (int i = 0; i < n_keep; ++i) { - cum += std::exp((double) scaled(i) - (double) smx) / sum; - if ((double) u < cum) { pick = sel_ids[(size_t) i]; break; } - } - return pick; -} - -// Survivors after the min_p + top_p cuts, in the sampled chain - the quantity an order or a threshold -// actually changes, used to assert a fixture can SEE the feature before asserting the kernel matches. -int sampled_cut(const std::vector& l, const std::vector& hist, const strata::kernels::SamplerParams& p) { - auto penal = [&](float logit, int count) { - if (count <= 0) return logit; - if (logit <= 0.0f) logit *= p.penalty_repeat; else logit /= p.penalty_repeat; - logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present; - return logit; - }; - auto count = [&](int v) { int c = 0; for (int h : hist) if (h == v) ++c; return c; }; - const int nv = (int) l.size(); - const int KMAX = 64; - const int k = std::min(nv, (p.top_k > 0 && p.top_k < KMAX) ? p.top_k : KMAX); - std::vector sel; - std::vector taken((size_t) nv, 0); - for (int i = 0; i < k; ++i) { - int best = -1; float bv = 0; - for (int v = 0; v < nv; ++v) { - if (taken[(size_t) v]) continue; - const float s = penal(l[(size_t) v], count(v)); - if (best < 0 || s > bv) { best = v; bv = s; } - } - taken[(size_t) best] = 1; sel.push_back(bv); - } - int n_minp = (int) sel.size(); - if (p.min_p > 0.0f) { - const float thresh = sel[0] + std::log(p.min_p); - for (int i = 0; i < (int) sel.size(); ++i) - if (sel[(size_t) i] < thresh) { n_minp = i; break; } - } - if (p.top_p >= 1.0f) return n_minp; - double sum = 0.0; - for (int i = 0; i < n_minp; ++i) sum += std::exp((double) sel[(size_t) i] - (double) sel[0]); - double cum = 0.0; - int cut = n_minp; - for (int i = 0; i < n_minp; ++i) { - cum += std::exp((double) sel[(size_t) i] - (double) sel[0]) / sum; - if (cum >= (double) p.top_p) { cut = i + 1; break; } - } - if (cut < p.min_keep) cut = p.min_keep < n_minp ? p.min_keep : n_minp; - return cut; -} - -// ---- the kernel's own semantics, for the fixtures ---- -// -// `sampled_reference` picks the first unpicked logit even when it is -inf or NaN; the kernels never pick either, and -// a round that finds nothing stores id 0 with a -inf logit (and later rounds treat id 0 as taken, as `sampler_kernel` -// does). The mirror below follows the kernels, so rows with -inf, NaN, +inf and more requested than finite logits -// can be pinned exactly. On rows without those it is `sampled_reference`. -struct SelList { - std::vector ids; - std::vector logit; -}; - -// The top_k list of `sampler_kernel` for one row: `window` is the counted history (the row's last penalty_last_n). -SelList mirror_select(const float* l, int nv, const std::vector& window, const strata::kernels::SamplerParams& p, - int k) { - std::vector s((size_t) nv); - for (int v = 0; v < nv; ++v) { - int c = 0; - for (int h : window) c += h == v; - float x = l[v]; - if (c > 0) { - if (x <= 0.0f) x *= p.penalty_repeat; else x /= p.penalty_repeat; - x -= (float) c * p.penalty_freq + (c > 0 ? 1.0f : 0.0f) * p.penalty_present; - } - s[(size_t) v] = x; - } - SelList out; - std::vector taken((size_t) nv, 0); - for (int i = 0; i < k; ++i) { - int best = nv; - float bv = -std::numeric_limits::infinity(); - for (int v = 0; v < nv; ++v) - if (!taken[(size_t) v] && s[(size_t) v] > bv) { bv = s[(size_t) v]; best = v; } - const int id = best < nv ? best : 0; - taken[(size_t) id] = 1; - out.ids.push_back(id); - out.logit.push_back(bv); - } - return out; -} - -// The tail of `sampler_kernel` over a list (its first `k` entries): top_p, min_p, temperature, the Philox draw. -int mirror_pick(const SelList& sel, int k, const strata::kernels::SamplerParams& p, int row) { - int n_keep = k; - float mx = sel.logit[0]; - for (int i = 1; i < k; ++i) mx = std::fmax(mx, sel.logit[(size_t) i]); - if (p.top_p < 1.0f) { - double sum = 0.0; - for (int i = 0; i < k; ++i) sum += std::exp((double) sel.logit[(size_t) i] - (double) mx); - double cum = 0.0; - int cut = k; - for (int i = 0; i < k; ++i) { - cum += std::exp((double) sel.logit[(size_t) i] - (double) mx) / sum; - if (cum >= (double) p.top_p) { cut = i + 1; break; } - } - if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k; - n_keep = cut; - } - if (p.min_p > 0.0f) { - const float thresh = sel.logit[0] + std::log(p.min_p); - for (int i = 0; i < n_keep; ++i) - if (sel.logit[(size_t) i] < thresh) { n_keep = i; break; } - } - const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f; - auto scaled = [&](int i) { return sel.logit[(size_t) i] * inv_t; }; - float smx = scaled(0); - for (int i = 1; i < n_keep; ++i) smx = std::fmax(smx, scaled(i)); - double sum = 0.0; - for (int i = 0; i < n_keep; ++i) sum += std::exp((double) scaled(i) - (double) smx); - const float u = host_philox_uniform(p.seed, p.counter + (uint64_t) row); - double cum = 0.0; - int pick = sel.ids[(size_t) (n_keep > 0 ? n_keep - 1 : 0)]; - for (int i = 0; i < n_keep; ++i) { - cum += std::exp((double) scaled(i) - (double) smx) / sum; - if ((double) u < cum) { pick = sel.ids[(size_t) i]; break; } - } - return pick; -} - -int sampled_k(int top_k, int nv) { return std::min(nv, (top_k > 0 && top_k < 64) ? top_k : 64); } - -// Rows uploaded once and sampled under many parameter sets: `sample` returns the picks of one launch on `stream` -// (nullptr: the legacy stream), -1 prefilled as in `run`. -struct DeviceRows { - float* l = nullptr; - int* h = nullptr; - int* o = nullptr; - int n_tokens = 0, nv = 0, hist_len = 0; - DeviceRows(const std::vector& logits, int n_tokens_, const std::vector& hist, int hist_len_) - : n_tokens(n_tokens_), nv((int) (logits.size() / (size_t) n_tokens_)), hist_len(hist_len_) { - check(cudaMalloc(&l, logits.size() * sizeof(float)), "malloc logits"); - check(cudaMalloc(&o, (size_t) n_tokens * sizeof(int)), "malloc out"); - check(cudaMemcpy(l, logits.data(), logits.size() * sizeof(float), cudaMemcpyHostToDevice), "copy"); - if (hist_len > 0) { - check(cudaMalloc(&h, hist.size() * sizeof(int)), "malloc hist"); - check(cudaMemcpy(h, hist.data(), hist.size() * sizeof(int), cudaMemcpyHostToDevice), "copy hist"); - } - } - DeviceRows(const DeviceRows&) = delete; - DeviceRows& operator=(const DeviceRows&) = delete; - ~DeviceRows() { - cudaFree(l); - cudaFree(o); - if (h) cudaFree(h); - } - std::vector sample(const strata::kernels::SamplerParams& p, cudaStream_t stream) { - check(cudaMemset(o, 0xFF, (size_t) n_tokens * sizeof(int)), "fill out"); - strata::kernels::sample_tokens(l, n_tokens, nv, h, hist_len, p, o, stream); - if (stream != nullptr) check(cudaStreamSynchronize(stream), "stream sync"); - std::vector got((size_t) n_tokens); - check(cudaMemcpy(got.data(), o, got.size() * sizeof(int), cudaMemcpyDeviceToHost), "back"); - return got; - } -}; - -// The counted window of row t: the last min(penalty_last_n, hist_len) entries (none without penalties). -std::vector window_of(const std::vector& hist, int hist_len, int t, int last_n) { - if (hist_len <= 0 || last_n <= 0) return {}; - const int h = std::min(last_n, hist_len); - const int* row = hist.data() + (size_t) t * hist_len; - return std::vector(row + (hist_len - h), row + hist_len); -} - -// `--bench`: the sampled path alone at the engine's vocabulary, per call, on the path the environment selects. -void bench_sampled() { - const int NV = 248320; - cudaStream_t s = nullptr; - check(cudaStreamCreate(&s), "stream"); - std::mt19937 rng(20); - std::normal_distribution g(0.0f, 3.0f); - for (int T : {1, 4, 8}) { - std::vector l((size_t) NV * T); - for (auto& v : l) v = g(rng); - float* d_l = nullptr; - int* d_o = nullptr; - check(cudaMalloc(&d_l, l.size() * sizeof(float)), "bench logits"); - check(cudaMalloc(&d_o, (size_t) T * sizeof(int)), "bench out"); - check(cudaMemcpy(d_l, l.data(), l.size() * sizeof(float), cudaMemcpyHostToDevice), "bench copy"); - for (int k : {20, 64}) { - strata::kernels::SamplerParams p; - p.top_k = k; p.top_p = 0.95f; p.temperature = 0.7f; p.seed = 1; - for (int w = 0; w < 3; ++w) strata::kernels::sample_tokens(d_l, T, NV, nullptr, 0, p, d_o, s); - check(cudaStreamSynchronize(s), "bench warmup"); - cudaEvent_t e0, e1; - check(cudaEventCreate(&e0), "event"); - check(cudaEventCreate(&e1), "event"); - const int iters = 50; - check(cudaEventRecord(e0, s), "record"); - for (int it = 0; it < iters; ++it) { - p.counter = (uint64_t) it; - strata::kernels::sample_tokens(d_l, T, NV, nullptr, 0, p, d_o, s); - } - check(cudaEventRecord(e1, s), "record"); - check(cudaEventSynchronize(e1), "bench sync"); - float ms = 0.0f; - check(cudaEventElapsedTime(&ms, e0, e1), "elapsed"); - std::printf(" bench: n_vocab %d, rows %d, top_k %2d, top_p 0.95: %8.1f us per call\n", NV, T, k, - 1000.0 * (double) ms / iters); - cudaEventDestroy(e0); - cudaEventDestroy(e1); - } - cudaFree(d_l); - cudaFree(d_o); - } - cudaStreamDestroy(s); -} - -} // namespace - -int main(int argc, char** argv) { - bool selftest = false, bench = false; - for (int i = 1; i < argc; ++i) { - if (std::string(argv[i]) == "--selftest") selftest = true; - else if (std::string(argv[i]) == "--bench") bench = true; - else { std::fprintf(stderr, "usage: sampler_parity [--selftest] [--bench]\n"); return 2; } - } - { - // the sampled path under test; ctest runs this binary once per path - auto on = [](const char* n) { const char* e = std::getenv(n); return e && *e && std::strcmp(e, "0") != 0; }; - std::printf(" sampled path: %s\n", on("STRATA_OLD_SAMPLER") ? "sampler_kernel (STRATA_OLD_SAMPLER)" - : on("STRATA_SAMPLER_ONE_BLOCK") ? "one block (STRATA_SAMPLER_ONE_BLOCK)" - : "split top_k (default)"); - } - if (bench) { - bench_sampled(); - return 0; - } - int bad = 0; - const int NV = 512, NT = 4; - - // ---- fixture 1: plain greedy. top_k = 0 (disabled), top_p = 1 (disabled), T = 1 -> argmax. - { - strata::kernels::SamplerParams p; p.top_k = 0; p.top_p = 1.0f; p.temperature = 1.0f; p.greedy = true; - std::mt19937 rng(3); std::normal_distribution g(0.0f, 1.0f); - std::vector l((size_t) NV * NT); - for (auto& v : l) v = g(rng); - std::vector want((size_t) NT); - for (int t = 0; t < NT; ++t) want[(size_t) t] = reference_pick({l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV}, p, false); - bad += run("greedy argmax", l, NT, p, want); - } - - // ---- fixture 2: THE ORDER FIXTURE. T = 0.5 sharpens the distribution enough that top_p = 0.5 cuts - // differently before and after the scaling, and the two orders then pick DIFFERENT tokens. - { - strata::kernels::SamplerParams p; p.top_k = 0; p.top_p = 0.5f; p.temperature = 0.5f; - p.min_keep = 1; p.greedy = true; - std::vector l((size_t) NV * NT, -1000.0f); - for (int t = 0; t < NT; ++t) { - // a flat-ish head so the cumulative mass crosses 0.5 inside it, and one clear leader - l[(size_t) t * NV + 0] = 3.0f; - for (int v = 1; v < 8; ++v) l[(size_t) t * NV + v] = 2.6f - 0.05f * (float) v; - } - std::vector want((size_t) NT), other((size_t) NT); - for (int t = 0; t < NT; ++t) { - const std::vector row(l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV); - want[(size_t) t] = reference_pick(row, p, false); // the SPECIFIED order - other[(size_t) t] = reference_pick(row, p, true); // temperature first - } - // If the two orders agree on this fixture the test cannot see the order, and saying "the kernel - // matches the spec" would be vacuous. - // GREEDY CANNOT SEE THE ORDER, and saying otherwise would be a vacuous check: no filter removes the - // global argmax, and temperature is monotonic, so the greedy pick is order-independent by - // construction. What the order changes is the top_p CUT, so the fixture is asserted to be - // order-SENSITIVE at the cut, which is a property of the fixture rather than of the kernel. - int cut_spec = 0, cut_alt = 0; - for (int t = 0; t < NT; ++t) { - const std::vector row(l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV); - cut_spec += reference_cut(row, p, false); - cut_alt += reference_cut(row, p, true); - } - const bool distinguishable = (cut_spec != cut_alt); - std::printf(" %-34s %s (survivors: spec %d, temp-first %d)\n", "order is observable on this fixture", - distinguishable ? "yes" : "*** NO - THE FIXTURE CANNOT SEE THE ORDER ***", cut_spec, - cut_alt); - if (!distinguishable) ++bad; - // greedy is still checked here, but as an ARGMAX check, not an order check - bad += run("greedy over this fixture", l, NT, p, want); - } - - // ---- fixture 3: greedy consumes NO random number. Two runs with different seeds must agree, or the - // seeded streams diverge between greedy and sampled runs - which docs/sampling.md §3 calls out. - { - strata::kernels::SamplerParams a; a.top_k = 20; a.top_p = 0.95f; a.temperature = 1.0f; a.greedy = true; a.seed = 1; - strata::kernels::SamplerParams b = a; b.seed = 999999; - std::mt19937 rng(5); std::normal_distribution g(0.0f, 1.0f); - std::vector l((size_t) NV * NT); - for (auto& v : l) v = g(rng); - std::vector wa((size_t) NT); - for (int t = 0; t < NT; ++t) wa[(size_t) t] = reference_pick({l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV}, a, false); - float* d_l = nullptr; int *d_a = nullptr, *d_b = nullptr; - check(cudaMalloc(&d_l, l.size() * sizeof(float)), "m1"); - check(cudaMalloc(&d_a, (size_t) NT * sizeof(int)), "m2"); - check(cudaMalloc(&d_b, (size_t) NT * sizeof(int)), "m3"); - check(cudaMemcpy(d_l, l.data(), l.size() * sizeof(float), cudaMemcpyHostToDevice), "c1"); - strata::kernels::sample_tokens(d_l, NT, NV, nullptr, 0, a, d_a, nullptr); - strata::kernels::sample_tokens(d_l, NT, NV, nullptr, 0, b, d_b, nullptr); - std::vector ga((size_t) NT), gb((size_t) NT); - check(cudaMemcpy(ga.data(), d_a, ga.size() * sizeof(int), cudaMemcpyDeviceToHost), "g1"); - check(cudaMemcpy(gb.data(), d_b, gb.size() * sizeof(int), cudaMemcpyDeviceToHost), "g2"); - int mismatch = 0, wrong = 0; - for (int t = 0; t < NT; ++t) { - if (ga[(size_t) t] != gb[(size_t) t]) ++mismatch; - if (ga[(size_t) t] != wa[(size_t) t]) ++wrong; - } - std::printf(" %-34s %s (seed-independent: %d differ; vs reference: %d wrong)\n", - "greedy ignores the seed", (!mismatch && !wrong) ? "matches" : "*** WRONG ***", mismatch, - wrong); - bad += mismatch + wrong; - cudaFree(d_l); cudaFree(d_a); cudaFree(d_b); - } - - - // ---- fixture 4: PENALTIES. Two sub-cases, each built so the rule it tests decides the answer. - { - // host reference for the penalty stage, transcribed from llama_sampler_penalties_apply - auto penal = [](float logit, int count, const strata::kernels::SamplerParams& p) { - if (count <= 0) return logit; - if (logit <= 0.0f) logit *= p.penalty_repeat; else logit /= p.penalty_repeat; - logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present; - return logit; - }; - auto pick = [&](const std::vector& l, const std::vector& hist, - const strata::kernels::SamplerParams& p, bool divide_unconditionally) { - int best = 0; float bv = 0; bool first = true; - for (int v = 0; v < (int) l.size(); ++v) { - int c = 0; for (int h : hist) if (h == v) ++c; - float s; - if (divide_unconditionally && c > 0) { - s = l[(size_t) v] / p.penalty_repeat - - (float) c * p.penalty_freq - (c > 0 ? 1.0f : 0.0f) * p.penalty_present; - } else { - s = penal(l[(size_t) v], c, p); - } - if (first || s > bv) { bv = s; best = v; first = false; } - } - return best; - }; - - const int NV2 = 8, NT2 = 2; - strata::kernels::SamplerParams p; p.top_k = 0; p.top_p = 1.0f; p.temperature = 1.0f; - p.greedy = true; p.penalty_last_n = 4; p.penalty_repeat = 2.0f; - - // A: ALL logits negative, so the multiply-or-divide rule decides the argmax - std::vector la((size_t) NV2 * NT2, -8.0f); - for (int t = 0; t < NT2; ++t) { - la[(size_t) t * NV2 + 0] = -1.0f; // in the history -> penalised - la[(size_t) t * NV2 + 1] = -1.2f; // not penalised -> should win - } - std::vector hist_a((size_t) NT2 * 4, -1); - for (int t = 0; t < NT2; ++t) hist_a[(size_t) t * 4 + 0] = 0; - std::vector want_a((size_t) NT2), alt_a((size_t) NT2); - for (int t = 0; t < NT2; ++t) { - const std::vector row(la.begin() + (size_t) t * NV2, la.begin() + (size_t) (t + 1) * NV2); - const std::vector h(hist_a.begin() + (size_t) t * 4, hist_a.begin() + (size_t) (t + 1) * 4); - want_a[(size_t) t] = pick(row, h, p, false); - alt_a[(size_t) t] = pick(row, h, p, true); // divide unconditionally - } - const bool A_visible = want_a[0] != alt_a[0]; - std::printf(" %-34s %s (multiply-rule %d, divide-always %d)\n", - "multiply-or-divide is observable", A_visible ? "yes" : "*** NO ***", want_a[0], - alt_a[0]); - if (!A_visible) ++bad; - else bad += run("penalties: repeat on negatives", la, NT2, p, want_a, hist_a, 4); - - // B: the PRESENCE penalty is a boolean, so two occurrences cost the same as one. The runner's margin - // is inside the difference between one and two applications. - std::vector lb((size_t) NV2 * NT2, -8.0f); - for (int t = 0; t < NT2; ++t) { - lb[(size_t) t * NV2 + 0] = 5.0f; // seen twice -> penalised ONCE (presence) + freq*2 - lb[(size_t) t * NV2 + 1] = 3.4f; // unseen - } - std::vector hist_b((size_t) NT2 * 4, -1); - for (int t = 0; t < NT2; ++t) { - hist_b[(size_t) t * 4 + 0] = 0; - hist_b[(size_t) t * 4 + 1] = 0; // twice - } - strata::kernels::SamplerParams q = p; q.penalty_present = 1.5f; q.penalty_freq = 0.0f; - std::vector want_b((size_t) NT2); - for (int t = 0; t < NT2; ++t) { - const std::vector row(lb.begin() + (size_t) t * NV2, lb.begin() + (size_t) (t + 1) * NV2); - const std::vector h(hist_b.begin() + (size_t) t * 4, hist_b.begin() + (size_t) (t + 1) * 4); - want_b[(size_t) t] = pick(row, h, q, false); - } - std::printf(" %-34s want token %d (with present=1.5, token 0 goes 5.0/2 - 1.5 = 1.0 vs token 1 at " - "3.4)\n", "presence penalty is a boolean", want_b[0]); - bad += run("penalties: presence is boolean", lb, NT2, q, want_b, hist_b, 4); - } - - // ---- fixture 5: TEMPERATURE 0 MUST STILL RETURN THE ARGMAX. Regression test for a real bug. - // - // The greedy branch used to read `apply_penalties(l[v] * inv_t, ...)`. `inv_t` is 0.0f whenever - // temperature <= 0, so at temperature 0 EVERY logit became 0.0f and the argmax returned index 0 - the - // sampler emitted token 0 forever, whatever the model predicted. OpenAI clients send `temperature: 0` - // for greedy decoding, so this was reachable from any ordinary client. - // - // It survived because EVERY other greedy fixture in this file sets temperature = 1.0f, where inv_t = 1.0 - // and the extra multiply is harmless. The bug needs temperature <= 0 to appear, and no fixture used it. - // The fixture below makes token 0 the WORST token in every row, so returning 0 is unambiguously wrong. - { - const int NV3 = 512, NT3 = 4; - std::vector l((size_t) NV3 * NT3, -5.0f); - std::vector want((size_t) NT3); - for (int t = 0; t < NT3; ++t) { - const int best = 100 + t; // the argmax is never token 0 - l[(size_t) t * NV3 + best] = 3.0f; - l[(size_t) t * NV3 + 0] = -9.0f; // token 0 is the worst in the row - want[(size_t) t] = best; - } - strata::kernels::SamplerParams p0; - p0.top_k = 0; p0.top_p = 1.0f; p0.temperature = 0.0f; p0.greedy = false; - bad += run("T=0 greedy=false is the argmax", l, NT3, p0, want); - - strata::kernels::SamplerParams p1 = p0; p1.greedy = true; - bad += run("T=0 greedy=true is the argmax", l, NT3, p1, want); - - strata::kernels::SamplerParams p2 = p0; p2.greedy = true; p2.temperature = 1.0f; - bad += run("T=1 greedy=true is the argmax", l, NT3, p2, want); - } - - // ---- fixture 6: PENALTIES IN THE SAMPLED CHAIN. Fixture 4 pins the greedy (argmax) path; the sampled - // chain gets its own reference (the full chain with the host Philox) and its own observability check: with - // the penalties on, the history row's favourite must LOSE a pick it would win penalty-free. - { - const int NV2 = 8, NT2 = 2; - strata::kernels::SamplerParams p; - p.top_k = 5; p.top_p = 0.9f; p.temperature = 0.8f; p.seed = 9; p.counter = 0; - p.penalty_last_n = 4; p.penalty_repeat = 3.0f; p.penalty_freq = 0.2f; p.penalty_present = 0.6f; - - std::vector l((size_t) NV2 * NT2, -8.0f); - std::vector hist((size_t) NT2 * 4, -1); - for (int t = 0; t < NT2; ++t) { - float* row = l.data() + (size_t) t * NV2; - row[0] = 9.0f; row[1] = 4.5f; row[2] = 4.4f; row[3] = 4.3f; // token 0 leads clean (9 vs 4.5) - hist[(size_t) t * 4 + 0] = 0; // and falls to 2.2/2.0 penalised - hist[(size_t) t * 4 + 1] = t == 1 ? 0 : -1; // (repeat 3, freq, presence) - } - std::vector want((size_t) NT2), clean((size_t) NT2); - strata::kernels::SamplerParams clean_p = p; - clean_p.penalty_last_n = 0; clean_p.penalty_repeat = 1.0f; - clean_p.penalty_freq = 0.0f; clean_p.penalty_present = 0.0f; - for (int t = 0; t < NT2; ++t) { - const std::vector row(l.begin() + (size_t) t * NV2, l.begin() + (size_t) (t + 1) * NV2); - const std::vector h(hist.begin() + (size_t) t * 4, hist.begin() + (size_t) (t + 1) * 4); - want[(size_t) t] = sampled_reference(row, h, p, t); - clean[(size_t) t] = sampled_reference(row, h, clean_p, t); - } - const bool visible = want[0] != clean[0] || want[1] != clean[1]; - std::printf(" %-34s %s (penalised picks %d/%d, clean %d/%d)\n", - "sampled penalties are observable", visible ? "yes" : "*** NO ***", want[0], want[1], - clean[0], clean[1]); - if (!visible) ++bad; - else bad += run("sampled chain: penalties + top_k/p", l, NT2, p, want, hist, 4); - } - - // ---- fixture 7: MIN_P. The cut is a PREFIX of the descending top_k list (logit >= max + log(min_p)), - // so the fixture asserts the survivor count moves with the threshold (the observability half) and that - // the kernel's pick equals the reference's through the full sampled chain (the correctness half). - { - const int NV3 = 8, NT3 = 2; - std::vector l((size_t) NV3 * NT3, -8.0f); - for (int t = 0; t < NT3; ++t) { - float* row = l.data() + (size_t) t * NV3; - row[0] = 4.0f; row[1] = 3.5f; row[2] = 3.2f; row[3] = 3.1f; // gaps keep the cut off the - row[4] = 2.0f; // logf/rounding knife edge - } - strata::kernels::SamplerParams base; - base.top_k = 6; base.top_p = 1.0f; base.temperature = 0.9f; base.seed = 77; - - int c0 = 0, c05 = 0, c09 = 0; - for (int t = 0; t < NT3; ++t) { - const std::vector row(l.begin() + (size_t) t * NV3, l.begin() + (size_t) (t + 1) * NV3); - strata::kernels::SamplerParams q = base; q.min_p = 0.0f; - c0 += sampled_cut(row, {}, q); - q.min_p = 0.5f; c05 += sampled_cut(row, {}, q); - q.min_p = 0.9f; c09 += sampled_cut(row, {}, q); - } - const bool visible = c0 > c05 && c05 > c09 && c09 >= NT3; - std::printf(" %-34s %s (survivors: min_p 0 -> %d, 0.5 -> %d, 0.9 -> %d)\n", - "min_p cut is observable", visible ? "yes" : "*** NO ***", c0, c05, c09); - if (!visible) ++bad; - - for (float mp : {0.0f, 0.5f, 0.9f}) { - strata::kernels::SamplerParams q = base; q.min_p = mp; - std::vector want((size_t) NT3); - for (int t = 0; t < NT3; ++t) { - const std::vector row(l.begin() + (size_t) t * NV3, l.begin() + (size_t) (t + 1) * NV3); - want[(size_t) t] = sampled_reference(row, {}, q, t); - } - char name[64]; - std::snprintf(name, sizeof name, "sampled chain: min_p=%.1f", (double) mp); - bad += run(name, l, NT3, q, want); - } - } - - // ---- fixture 8: THE PENALTY WINDOW IS THE TAIL. With an 8-entry history and penalty_last_n = 4, only - // the LAST four entries count: a token punished in the old half must come back to full strength, and one - // punished in the tail half stays down. The reference counts the same tail; the observability check runs - // the reference once more WITHOUT the clamp (counting all 8) and requires the picks to differ. - { - const int NV4 = 8; - strata::kernels::SamplerParams p; - p.top_k = 0; p.top_p = 1.0f; p.temperature = 1.0f; p.greedy = true; - p.penalty_last_n = 4; p.penalty_repeat = 3.0f; p.penalty_freq = 0.3f; p.penalty_present = 0.5f; - - std::vector l((size_t) NV4, -8.0f); - l[0] = 6.0f; l[3] = 6.5f; // token 0 leads clean; token 3 is the tail offender - std::vector hist = {0, 0, 0, 0, 3, 3, 3, 3}; // token 0 old (out), token 3 in the tail - - auto pick_clamped = [&](bool clamp) { - int best = 0; float bv = 0; bool first = true; - for (int v = 0; v < NV4; ++v) { - int c = 0; - for (int i = 0; i < (clamp ? 4 : 8); ++i) if (hist[(size_t) (8 - (clamp ? 4 : 8) + i)] == v) ++c; - float logit = l[(size_t) v]; - if (c > 0) { logit = logit <= 0.0f ? logit * p.penalty_repeat : logit / p.penalty_repeat; - logit -= (float) c * p.penalty_freq + p.penalty_present; } - if (first || logit > bv) { bv = logit; best = v; first = false; } - } - return best; - }; - const int want = pick_clamped(true), unclamped = pick_clamped(false); - const bool visible = want != unclamped; - std::printf(" %-34s %s (clamped pick %d, full-history pick %d)\n", - "penalty window clamp is observable", visible ? "yes" : "*** NO ***", want, unclamped); - if (!visible) ++bad; - else bad += run("penalty window: tail only", {l.begin(), l.end()}, 1, p, {want}, hist, 8); - } - - // ---- fixture 9: ONE PENALTIES STAGE (issue #53), against an independently computed distribution, not the - // reference above (which had copied the kernel's mistake). Two tokens with equal logits, token 0 in the - // history, presence penalty 1.5, temperature 0.7: llama.cpp's chain gives token 0 the logit (0 - 1.5) / 0.7, - // P = 1 / (1 + exp(1.5 / 0.7)) = 0.1050; a second penalty after the temperature made it 0.0255. Over 8,000 - // draws the kernel's share of token 0 must be near 0.105 (4 sigma = 0.014), and its picks must equal the - // reference's draw for draw. - { - const int NT9 = 8000; - strata::kernels::SamplerParams p; - p.top_k = 2; p.top_p = 1.0f; p.min_p = 0.0f; p.temperature = 0.7f; p.seed = 53; p.counter = 0; - p.penalty_last_n = 1; p.penalty_repeat = 1.0f; p.penalty_freq = 0.0f; p.penalty_present = 1.5f; - std::vector l((size_t) 2 * NT9, 0.0f); - std::vector hist((size_t) NT9, 0); - std::vector want((size_t) NT9); - int zeros = 0; - for (int t = 0; t < NT9; ++t) { - want[(size_t) t] = sampled_reference({0.0f, 0.0f}, {0}, p, t); - zeros += want[(size_t) t] == 0; - } - const double expect = 1.0 / (1.0 + std::exp(1.5 / 0.7)), share = (double) zeros / NT9; - const bool near = std::fabs(share - expect) < 0.014; - std::printf(" %-34s %s (token 0 drawn %.4f of %d, expected %.4f; twice-penalised would be 0.0255)\n", - "one penalties stage (#53)", near ? "yes" : "*** NO ***", share, NT9, expect); - if (!near) ++bad; - bad += run("sampled chain: #53's example", l, NT9, p, want, hist, 1); - } - - // ---- fixture 10: TOP_P BEFORE MIN_P (llama.cpp's order). Probabilities 0.4 / 0.3 / 0.2 / 0.1, top_p 0.75, - // min_p 0.3 (keeps p >= 0.12): top_p over all four keeps three (0.4 + 0.3 < 0.75 <= 0.9) and min_p keeps them; - // min_p first would drop 0.1, renormalise, and top_p would then stop at two (0.444 + 0.333 >= 0.75). So token - // 2 must be drawn sometimes - never in the old order - and every pick must equal the reference's. - { - const int NT10 = 256; - strata::kernels::SamplerParams p; - p.top_k = 4; p.top_p = 0.75f; p.min_p = 0.3f; p.temperature = 1.0f; p.seed = 10; p.counter = 0; - const float lp[4] = {std::log(0.4f), std::log(0.3f), std::log(0.2f), std::log(0.1f)}; - std::vector row = {lp[0], lp[1], lp[2], lp[3], -30.0f, -30.0f, -30.0f, -30.0f}; - std::vector l; - for (int t = 0; t < NT10; ++t) l.insert(l.end(), row.begin(), row.end()); - std::vector want((size_t) NT10); - int twos = 0; - for (int t = 0; t < NT10; ++t) { - want[(size_t) t] = sampled_reference(row, {}, p, t); - twos += want[(size_t) t] == 2; - } - std::printf(" %-34s %s (token 2 drawn %d of %d times)\n", "top_p before min_p is observable", - twos > 0 ? "yes" : "*** NO ***", twos, NT10); - if (twos == 0) ++bad; - bad += run("sampled chain: top_p then min_p", l, NT10, p, want); - } - - // ---- fixture 11: A STALE HISTORY WITH last_n = 0 IS INERT (PR #59). A caller can hand over a history buffer - // from a previous penalised request while this request disables the penalties - the run must equal the - // no-history run in both kernels, and the bitmap the launch did not size must stay untouched. - { - std::mt19937 rng(11); std::normal_distribution g(0.0f, 1.0f); - std::vector l((size_t) NV * NT); - for (auto& v : l) v = g(rng); - std::vector hist((size_t) NT * 8, -1); - for (int t = 0; t < NT; ++t) hist[(size_t) t * 8] = 3; - - strata::kernels::SamplerParams p; - p.top_k = 20; p.top_p = 0.95f; p.temperature = 0.8f; p.seed = 5; - std::vector want((size_t) NT); - for (int t = 0; t < NT; ++t) - want[(size_t) t] = sampled_reference({l.begin() + (size_t) t * NV, - l.begin() + (size_t) (t + 1) * NV}, {}, p, t); - bad += run("stale history, last_n=0 (sampled)", l, NT, p, want, hist, 8); - - strata::kernels::SamplerParams gp = p; gp.greedy = true; gp.top_k = 0; gp.top_p = 1.0f; - std::vector gwant((size_t) NT); - for (int t = 0; t < NT; ++t) - gwant[(size_t) t] = reference_pick({l.begin() + (size_t) t * NV, - l.begin() + (size_t) (t + 1) * NV}, gp, false); - bad += run("stale history, last_n=0 (greedy)", l, NT, gp, gwant, hist, 8); - } - - // ---- fixture 12: ONE HISTORY PER ROW (engine 0.1.19). A verify window samples T rows, and row t's pick - // follows the drafts 1..t: its penalties must count them. The engine used to stage row 0 alone, so rows - // 1..T-1 read slots nobody wrote. Here every row gets `penalty_rows`' history and is pinned against a - // per-row scalar reference; the fixture first asserts it can SEE the difference - with row 0's history - // copied to every row (the nearest well-defined stand-in for the old staging) some row must pick differently. - // Row t's own newest token (window[t]) is its favourite by a margin the presence penalty overturns. - { - auto greedy_pen = [](const std::vector& l, const std::vector& hist, - const strata::kernels::SamplerParams& p) { - int best = 0; float bv = 0; bool first = true; - for (int v = 0; v < (int) l.size(); ++v) { - int c = 0; for (int h : hist) if (h == v) ++c; - float s = l[(size_t) v]; - if (c > 0) { - if (s <= 0.0f) s *= p.penalty_repeat; else s /= p.penalty_repeat; - s -= (float) c * p.penalty_freq + p.penalty_present; - } - if (first || s > bv) { bv = s; best = v; first = false; } - } - return best; - }; - std::mt19937 rng(12); std::normal_distribution g(0.0f, 1.0f); - const int TAIL = 5000; // longer than the widest window below - std::vector tail((size_t) TAIL); - for (auto& v : tail) v = (int32_t) (rng() % NV); - int observable = 0, rows_checked = 0; - for (int T : {1, 2, 4, 8}) { - for (int H : {1, 64, 1024, 4096}) { - std::vector window((size_t) T); - for (int t = 0; t < T; ++t) window[(size_t) t] = (int32_t) (100 + 37 * t); // distinct, in range - std::vector rows((size_t) T * H); - strata::kernels::penalty_rows(tail.data(), TAIL, window.data(), T, H, rows.data()); - std::vector l((size_t) T * NV); - for (auto& v : l) v = g(rng); - for (int t = 0; t < T; ++t) l[(size_t) t * NV + window[(size_t) t]] = 5.0f; - strata::kernels::SamplerParams gp; - gp.greedy = true; gp.temperature = 0.0f; gp.top_k = 0; gp.top_p = 1.0f; - gp.penalty_last_n = H; gp.penalty_present = 4.0f; - strata::kernels::SamplerParams sp2; - sp2.top_k = 20; sp2.top_p = 0.9f; sp2.temperature = 0.7f; sp2.seed = 1000 + (uint64_t) H; - sp2.counter = 77; sp2.penalty_last_n = H; sp2.penalty_present = 4.0f; sp2.penalty_repeat = 1.1f; - std::vector gwant((size_t) T), swant((size_t) T), rows_int(rows.begin(), rows.end()); - for (int t = 0; t < T; ++t) { - const std::vector lr(l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV); - const std::vector own(rows.begin() + (size_t) t * H, rows.begin() + (size_t) (t + 1) * H); - const std::vector row0(rows.begin(), rows.begin() + H); - gwant[(size_t) t] = greedy_pen(lr, own, gp); - swant[(size_t) t] = sampled_reference(lr, own, sp2, t); - if (t > 0 && greedy_pen(lr, row0, gp) != gwant[(size_t) t]) ++observable; - ++rows_checked; - } - char name[64]; - std::snprintf(name, sizeof name, "per-row history T=%d H=%d greedy", T, H); - bad += run(name, l, T, gp, gwant, rows_int, H); - std::snprintf(name, sizeof name, "per-row history T=%d H=%d sampled", T, H); - bad += run(name, l, T, sp2, swant, rows_int, H); - } - } - std::printf(" %-34s %s (%d drafted rows pick differently with row 0's history, of %d rows)\n", - "per-row histories are observable", observable > 0 ? "yes" : "*** NO ***", observable, - rows_checked); - if (observable == 0) ++bad; - } - - // ---- fixture 13: HISTORY IDS OUTSIDE THE VOCABULARY ARE IGNORED. The bitmap is sized for n_vocab bits; - // an id >= n_vocab used to set a bit past its end (a shared-memory write out of bounds - compute-sanitizer - // memcheck reports it). They can never be a candidate, so the result equals the reference without them. - { - std::mt19937 rng(13); std::normal_distribution g(0.0f, 1.0f); - const int H = 16; - std::vector l((size_t) NV * NT); - for (auto& v : l) v = g(rng); - std::vector hist((size_t) NT * H, -1), valid_only((size_t) NT * H, -1); - const int junk[] = {NV, NV + 1000, 0x7fffffff, -5, 1 << 20}; - for (int t = 0; t < NT; ++t) { - for (int j = 0; j < H; ++j) { - const bool bogus = j % 3 == 0; - const int v = bogus ? junk[(size_t) (j / 3) % 5] : (int) (rng() % NV); - hist[(size_t) t * H + j] = v; - if (!bogus) valid_only[(size_t) t * H + j] = v; - } - l[(size_t) t * NV + hist[(size_t) t * H + 1]] = 4.0f; // a penalised favourite, so penalties matter - } - strata::kernels::SamplerParams gp; - gp.greedy = true; gp.temperature = 0.0f; gp.top_k = 0; gp.top_p = 1.0f; - gp.penalty_last_n = H; gp.penalty_present = 3.0f; - strata::kernels::SamplerParams sp2 = gp; - sp2.greedy = false; sp2.temperature = 0.8f; sp2.top_k = 20; sp2.top_p = 0.95f; sp2.seed = 13; - std::vector gwant((size_t) NT), swant((size_t) NT); - for (int t = 0; t < NT; ++t) { - const std::vector lr(l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV); - const std::vector ok(valid_only.begin() + (size_t) t * H, valid_only.begin() + (size_t) (t + 1) * H); - { // the greedy reference with the penalty (reference_pick has none) - int best = 0; float bv = 0; bool first = true; - for (int v = 0; v < NV; ++v) { - int c = 0; for (int h : ok) if (h == v) ++c; - float s = lr[(size_t) v]; - if (c > 0) { if (s <= 0.0f) s *= gp.penalty_repeat; else s /= gp.penalty_repeat; s -= gp.penalty_present; } - if (first || s > bv) { bv = s; best = v; first = false; } - } - gwant[(size_t) t] = best; - } - swant[(size_t) t] = sampled_reference(lr, ok, sp2, t); - } - bad += run("out-of-vocab history ids (greedy)", l, NT, gp, gwant, hist, H); - bad += run("out-of-vocab history ids (sampled)", l, NT, sp2, swant, hist, H); - } - - // ---- fixture 14: THE top_k CONTRACT. 1..64 as given; 0 ("off") and anything wider use the widest list the - // kernel keeps, 64 - and every row is written (the sampled kernel used to print an error for 0 and leave the - // row unwritten, which a verify window then read as a token; `run` pre-fills -1 so that fails here). - { - std::mt19937 rng(14); std::normal_distribution g(0.0f, 1.0f); - std::vector l((size_t) NV * NT); - for (auto& v : l) v = g(rng) * 0.3f; // flat: the 64-wide list matters to the draw - strata::kernels::SamplerParams p64; - p64.top_k = 64; p64.top_p = 1.0f; p64.temperature = 1.5f; p64.seed = 14; - std::vector want((size_t) NT); - for (int t = 0; t < NT; ++t) - want[(size_t) t] = sampled_reference({l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV}, - {}, p64, t); - bad += run("sampled top_k=64", l, NT, p64, want); - strata::kernels::SamplerParams p0 = p64; p0.top_k = 0; - bad += run("sampled top_k=0 means 64", l, NT, p0, want); - strata::kernels::SamplerParams p100 = p64; p100.top_k = 100; - bad += run("sampled top_k=100 means 64", l, NT, p100, want); - strata::kernels::SamplerParams pneg = p64; pneg.top_k = -3; - bad += run("sampled top_k=-3 means 64", l, NT, pneg, want); - } - - // ---- fixture 15: `penalty_rows`, host only, against the plain definition: row t = the last h tokens of - // tail + window[0..t], -1 padded in front. Covers a tail shorter than, equal to and longer than h, and row 0 - // equal to the single row the engine staged before 0.1.19. - { - int wrong = 0, cases = 0; - for (int n_tail : {0, 1, 5, 63, 64, 65, 300}) { - for (int T : {1, 3, 8}) { - for (int h : {1, 4, 64, 100}) { - std::vector tail((size_t) n_tail), window((size_t) T); - for (int i = 0; i < n_tail; ++i) tail[(size_t) i] = 1000 + i; - for (int i = 0; i < T; ++i) window[(size_t) i] = 5000 + i; - std::vector rows((size_t) T * h, 12345); - strata::kernels::penalty_rows(tail.data(), n_tail, window.data(), T, h, rows.data()); - for (int t = 0; t < T; ++t) { - std::vector seq(tail); - seq.insert(seq.end(), window.begin(), window.begin() + t + 1); - std::vector expect((size_t) h, -1); - const int take = (int) std::min((size_t) h, seq.size()); - for (int j = 0; j < take; ++j) expect[(size_t) (h - take + j)] = seq[seq.size() - take + j]; - if (!std::equal(expect.begin(), expect.end(), rows.begin() + (size_t) t * h)) ++wrong; - ++cases; - } - // row 0 = the old single-row staging: consumed tail, then the fed-back head last - std::vector old((size_t) h, -1); - const int take0 = (int) std::min(h, (int64_t) n_tail + 1); - for (int j = 0; j < take0 - 1; ++j) old[(size_t) (h - take0 + j)] = tail[(size_t) (n_tail - (take0 - 1) + j)]; - old[(size_t) (h - 1)] = window[0]; - if (!std::equal(old.begin(), old.end(), rows.begin())) ++wrong; - ++cases; - } - } - } - std::printf(" %-34s %s (%d of %d rows differ)\n", "penalty_rows layout", wrong ? "*** WRONG ***" : "matches", - wrong, cases); - bad += wrong; - } - - // A continuous stream and individual decode calls consume the same draw counters. - { - constexpr int count = 32, vocab = 16; - std::vector uniform(count * vocab, 0.0f); - float* input = nullptr; - int* output = nullptr; - check(cudaMalloc(&input, uniform.size() * sizeof(float)), "counter logits"); - check(cudaMalloc(&output, count * sizeof(int)), "counter output"); - check(cudaMemcpy(input, uniform.data(), uniform.size() * sizeof(float), cudaMemcpyHostToDevice), "counter upload"); - strata::kernels::SamplerParams p; - p.top_k = vocab; p.top_p = 1.0f; p.seed = 123; p.counter = (uint64_t(1) << 32) + 7; - strata::kernels::sample_tokens(input, count, vocab, nullptr, 0, p, output, nullptr); - std::vector batch(count), singles(count), repeated(count); - check(cudaMemcpy(batch.data(), output, count * sizeof(int), cudaMemcpyDeviceToHost), "counter batch"); - for (int i = 0; i < count; ++i) { - auto one = p; one.counter += i; - strata::kernels::sample_tokens(input, 1, vocab, nullptr, 0, one, output + i, nullptr); - } - check(cudaMemcpy(singles.data(), output, count * sizeof(int), cudaMemcpyDeviceToHost), "counter singles"); - strata::kernels::sample_tokens(input, count, vocab, nullptr, 0, p, output, nullptr); - check(cudaMemcpy(repeated.data(), output, count * sizeof(int), cudaMemcpyDeviceToHost), "counter repeated"); - bool varies = false; - for (int i = 1; i < count; ++i) varies |= batch[i] != batch[0]; - const bool valid = batch == singles && batch == repeated && varies; - std::printf(" sampler draw counter segmentation/repeat: %s\n", valid ? "PASS" : "FAIL"); - bad += !valid; - cudaFree(input); cudaFree(output); - } - - // ---- fixture 16: THE WHOLE top_k LIST, POSITION BY POSITION, UNDER TIES. A pick shows the list - // through one draw; this reads the list itself. Every row holds a +inf logit, so the tail's arithmetic is NaN - // (inf - inf), no cut fires and no draw lands: the chain returns its LAST kept entry, sel_ids[k - 1]. Launching - // top_k = 1..64 then reads the list one position at a time - its set and its order. The rows make the order - // rest on the tie rule: hundreds of logits share the top finite values, spread over every split block, warp and - // lane; -0 and +0 tie; -inf and NaN are mixed in; a row has fewer finite logits than 64 (the sentinel id 0 must - // come out); a penalised row lands its penalised tokens exactly on other tokens' values. Vocabularies: the - // engine's 248,320 (a partial last split block), 100,003, 262,144 (the widest split), 262,145 (one more: the - // one-block fallback) and 1,000. - { - const float inf = std::numeric_limits::infinity(); - const float qnan = std::numeric_limits::quiet_NaN(); - int wrong = 0, probes = 0, sentinels = 0; - for (int nv : {248320, 100003, 262144, 262145, 1000}) { - const int T = 4, H = 64; - std::mt19937 rng((unsigned) (1600 + nv)); - std::normal_distribution g(0.0f, 1.0f); - std::vector l((size_t) nv * T); - for (auto& v : l) v = std::floor(g(rng) * 4.0f) / 4.0f; // quarter steps: ties everywhere - auto spread = [&](int j) { return (int) (((int64_t) j * 7919 + 13) % nv); }; - // row 0: 20 logits at 6.25 and 300 at 6.0 over the whole row, two +inf - float* r0 = l.data(); - for (int j = 0; j < 320; ++j) r0[spread(j)] = j < 20 ? 6.25f : 6.0f; - r0[nv / 2] = inf; - r0[nv - 1] = inf; - // row 1: nothing above 0, every zero signed by its id's parity (-0 at even ids), one +inf - float* r1 = l.data() + (size_t) nv; - for (int v = 0; v < nv; ++v) { - r1[v] = -std::fabs(r1[v]); - if (r1[v] == 0.0f) r1[v] = (v & 1) ? 0.0f : -0.0f; - } - r1[3] = inf; - // row 2: -inf everywhere but ten finite logits (two values), two NaN and a +inf: 11 candidates in all - float* r2 = l.data() + (size_t) 2 * nv; - for (int v = 0; v < nv; ++v) r2[v] = -inf; - for (int j = 0; j < 10; ++j) r2[spread(j + 400)] = j < 5 ? 1.0f : 0.5f; - r2[spread(500)] = qnan; - r2[spread(501)] = qnan; - r2[spread(502)] = inf; - // row 3: penalties. Window ids on block and warp edges, repeats, and ids outside the vocabulary; the - // penalised tokens sit at 9.0, which repeat 2 / freq 0.25 / present 0.5 turns into 4.0 - 0.25 x count - // (3.75, 3.5, ...), values the quarter-step logits share. - float* r3 = l.data() + (size_t) 3 * nv; - std::vector hist((size_t) T * H, -1); - int* h3 = hist.data() + (size_t) 3 * H; - const int edges[] = {0, 1023, 1024, 4095, 4096, 8191, 8192, 12345, nv / 2 + 1, nv - 2}; - int hn = 0; - for (int e : edges) - if (e < nv && e != nv / 2) { - h3[hn++] = e; - if (hn % 3 == 0) h3[hn++] = e; // counted twice - r3[e] = 9.0f; - } - h3[hn++] = nv; // ignored: outside - h3[hn++] = nv + 77; - h3[hn++] = -5; - for (int j = 0; j < 30; ++j) r3[spread(j + 600)] = j < 15 ? 3.75f : 3.5f; - r3[nv / 2] = inf; // not in the window - - strata::kernels::SamplerParams base; - base.top_p = 1.0f; base.min_p = 0.0f; base.temperature = 0.8f; base.seed = 16; - base.penalty_last_n = H; base.penalty_repeat = 2.0f; base.penalty_freq = 0.25f; - base.penalty_present = 0.5f; - const int kmax = sampled_k(64, nv); - std::vector lists; - for (int t = 0; t < T; ++t) - lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, H), base, kmax)); - DeviceRows rows(l, T, hist, H); - for (int top_k = 0; top_k <= 66; ++top_k) { - strata::kernels::SamplerParams p = base; - p.top_k = top_k == 65 ? 100 : top_k == 66 ? -3 : top_k; // 0, 100 and -3 mean 64 - p.top_p = (top_k & 1) ? 0.5f : 1.0f; // both tail branches (NaN: no cut) - p.counter = (uint64_t) top_k; - const int k = sampled_k(p.top_k, nv); - const std::vector got = rows.sample(p, nullptr); - for (int t = 0; t < T; ++t) { - const int want = lists[(size_t) t].ids[(size_t) (k - 1)]; - sentinels += (t == 2 && k > 11); - ++probes; - if (got[(size_t) t] != want) { - if (wrong < 8) - std::printf(" n_vocab %d row %d top_k %d: position %d want id %d got %d\n", nv, t, - p.top_k, k - 1, want, got[(size_t) t]); - ++wrong; - } - } - } - } - // the fixture must reach the sentinel (row 2 has 11 candidates) or it cannot see the "nothing left" rule - std::printf(" %-34s %s (%d of %d positions differ; %d sentinel positions)\n", "top_k list under ties", - wrong || !sentinels ? "*** WRONG ***" : "matches", wrong, probes, sentinels); - bad += wrong + (sentinels == 0); - } - - // ---- fixture 17: SAMPLED DRAWS UNDER TIES. The realistic chain - finite logits on half steps, - // so dozens of tokens share each value near the top - through every stage: top_k 1 / 20 / 64, top_p 0.9 / 1, - // min_p 0 / 0.05, a hot temperature that spreads the draws over the whole list, penalties off and on (half of - // each window on the row's head, so they reorder it). 17 rows (the split's scratch is first sized for 16: this - // regrows it), on the legacy stream and on a created one. Observability: some picks must be tokens that tie - // with another kept token, or the tie rule would go untested. - { - const int T = 17, H = 64; - cudaStream_t cs = nullptr; - check(cudaStreamCreate(&cs), "fixture 17 stream"); - int wrong = 0, draws = 0, tied = 0; - for (int nv : {248320, 512}) { - std::mt19937 rng((unsigned) (1700 + nv)); - std::normal_distribution g(0.0f, 1.5f); - std::vector l((size_t) nv * T); - for (auto& v : l) v = std::floor(g(rng) * 2.0f) / 2.0f; - if (nv == 512) - for (auto& v : l) v = std::floor(v / 2.0f); // whole steps: a few big tie groups - std::vector hist((size_t) T * H); - for (int t = 0; t < T; ++t) { - const float* row = l.data() + (size_t) t * nv; - const float mx = *std::max_element(row, row + nv); - std::vector head; - for (int v = 0; v < nv; ++v) - if (row[v] >= mx - 1.0f) head.push_back(v); - for (int j = 0; j < H; ++j) - hist[(size_t) t * H + j] = (j & 1) ? (int) (rng() % (unsigned) nv) - : head[(size_t) (rng() % (unsigned) head.size())]; - } - DeviceRows rows(l, T, hist, H); - int config = 0; - for (int pen = 0; pen < 2; ++pen) { - strata::kernels::SamplerParams base; - base.temperature = 2.5f; base.seed = 17; - base.penalty_last_n = pen ? H : 0; - base.penalty_repeat = 1.25f; base.penalty_freq = 0.25f; base.penalty_present = 0.5f; - const int kmax = sampled_k(64, nv); - std::vector lists; - for (int t = 0; t < T; ++t) - lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, base.penalty_last_n), - base, kmax)); - for (int top_k : {1, 20, 64}) - for (float top_p : {0.9f, 1.0f}) - for (float min_p : {0.0f, 0.05f}) - for (cudaStream_t st : {(cudaStream_t) nullptr, cs}) { - strata::kernels::SamplerParams p = base; - p.top_k = top_k; p.top_p = top_p; p.min_p = min_p; - p.counter = (uint64_t) (1000 * ++config); - const int k = sampled_k(top_k, nv); - const std::vector got = rows.sample(p, st); - for (int t = 0; t < T; ++t) { - const SelList& sl = lists[(size_t) t]; - const int want = mirror_pick(sl, k, p, t); - ++draws; - int same = 0; - for (int i = 0; i < k; ++i) { - if (sl.ids[(size_t) i] != want) continue; - for (int j = 0; j < k; ++j) same += sl.logit[(size_t) j] == sl.logit[(size_t) i]; - break; - } - tied += same > 1; - if (got[(size_t) t] != want) { - if (wrong < 8) - std::printf(" n_vocab %d row %d top_k %d top_p %.2f min_p %.2f pen %d: " - "want %d got %d\n", nv, t, top_k, (double) top_p, - (double) min_p, pen, want, got[(size_t) t]); - ++wrong; - } - } - } - } - } - cudaStreamDestroy(cs); - std::printf(" %-34s %s (%d of %d draws differ; %d picks tie with another kept token)\n", - "sampled draws under ties", wrong || !tied ? "*** WRONG ***" : "matches", wrong, draws, tied); - bad += wrong + (tied == 0); - } - - // ---- fixture 18: THE DEFAULT PATH'S AUTOMATIC FALLBACKS. (a) A stream under graph capture - // (ThreadLocal mode) gets the one-block kernel, penalty bitmap in dynamic shared memory, inside the graph: the - // capture must succeed and the replayed graph (twice) must pick the mirror's tokens; the same stream uncaptured - // then takes the split path (its scratch is first allocated after the capture) and picks the same. (b) More - // rows than a split launch takes (64) fall back to one block; exactly 64 stay split. - { - int wrong = 0, draws = 0; - const int H = 64; - auto compare = [&](const char* what, const std::vector& got, const std::vector& lists, int k, - const strata::kernels::SamplerParams& p) { - for (size_t t = 0; t < got.size(); ++t) { - const int want = mirror_pick(lists[t], k, p, (int) t); - ++draws; - if (got[t] != want) { - if (wrong < 8) std::printf(" %s row %zu: want %d got %d\n", what, t, want, got[t]); - ++wrong; - } - } - }; - auto make = [&](int nv, int T, unsigned seed, std::vector& l, std::vector& hist) { - std::mt19937 rng(seed); - std::normal_distribution g(0.0f, 1.5f); - l.assign((size_t) nv * T, 0.0f); - for (auto& v : l) v = std::floor(g(rng) * 2.0f) / 2.0f; - hist.assign((size_t) T * H, 0); - for (auto& h : hist) h = (int) (rng() % (unsigned) nv); - }; - { - const int nv = 248320, T = 3; - std::vector l; - std::vector hist; - make(nv, T, 1800u, l, hist); - strata::kernels::SamplerParams p; - p.top_k = 20; p.top_p = 0.9f; p.temperature = 2.5f; p.seed = 18; p.counter = 77; - p.penalty_last_n = H; p.penalty_repeat = 1.25f; p.penalty_freq = 0.25f; p.penalty_present = 0.5f; - const int k = sampled_k(p.top_k, nv); - std::vector lists; - for (int t = 0; t < T; ++t) - lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, H), p, k)); - DeviceRows rows(l, T, hist, H); - cudaStream_t cs = nullptr; - check(cudaStreamCreate(&cs), "fixture 18 stream"); - check(cudaMemset(rows.o, 0xFF, (size_t) T * sizeof(int)), "fixture 18 fill"); - cudaGraph_t graph = nullptr; - cudaGraphExec_t exec = nullptr; - check(cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal), "begin capture"); - strata::kernels::sample_tokens(rows.l, T, nv, rows.h, H, p, rows.o, cs); - check(cudaStreamEndCapture(cs, &graph), "end capture"); - check(cudaGraphInstantiate(&exec, graph, 0), "instantiate"); - for (int replay = 0; replay < 2; ++replay) { - check(cudaMemset(rows.o, 0xFF, (size_t) T * sizeof(int)), "fixture 18 refill"); - check(cudaGraphLaunch(exec, cs), "graph launch"); - check(cudaStreamSynchronize(cs), "graph sync"); - std::vector got((size_t) T); - check(cudaMemcpy(got.data(), rows.o, got.size() * sizeof(int), cudaMemcpyDeviceToHost), "back"); - compare("captured graph", got, lists, k, p); - } - cudaGraphExecDestroy(exec); - cudaGraphDestroy(graph); - compare("same stream, uncaptured", rows.sample(p, cs), lists, k, p); - cudaStreamDestroy(cs); - } - for (int T : {64, 70}) { - const int nv = 512; - std::vector l; - std::vector hist; - make(nv, T, 1810u + (unsigned) T, l, hist); - strata::kernels::SamplerParams p; - p.top_k = 64; p.top_p = 1.0f; p.temperature = 2.5f; p.seed = 18; p.counter = (uint64_t) T; - const int k = sampled_k(p.top_k, nv); - std::vector lists; - for (int t = 0; t < T; ++t) lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, {}, p, k)); - DeviceRows rows(l, T, hist, 0); - compare(T > 64 ? "70 rows (one block)" : "64 rows (split)", rows.sample(p, nullptr), lists, k, p); - } - std::printf(" %-34s %s (%d of %d draws differ)\n", "fallbacks: graph capture, row cap", - wrong ? "*** WRONG ***" : "matches", wrong, draws); - bad += wrong; - } - - std::printf("\nsampler: %d failures\n", bad); - if (bad) return 1; - if (selftest) std::printf("sampler_parity OK\n"); - return 0; -} diff --git a/src/kernels/shared_expert_parity.cpp b/src/kernels/shared_expert_parity.cpp deleted file mode 100644 index 62dbc96..0000000 --- a/src/kernels/shared_expert_parity.cpp +++ /dev/null @@ -1,674 +0,0 @@ -// src/kernels/shared_expert_parity.cpp - P2.S2's test for the shared expert. -// -// WHAT THIS CAN AND CANNOT CHECK TIGHTLY. The weights are driven with FP16 activations because Q8_K is not -// implemented, and the SwiGLU intermediate is converted to fp16 before the down projection - so the tolerance -// here is set by that conversion (~1e-3) and NOT by the structure. Round 193 measured the activation-format -// choice at 0.6175% against the reference, which is the floor this test inherits and states. -// -// WHAT IT PINS DOWN TIGHTLY IS THE STRUCTURE, which is what `docs/semantics.md` records as having been believed -// wrong for many rounds: -// -// 1. SILU ON GATE, not on up. Both readings have the right shapes and give similar magnitudes, so the test -// computes the WHOLE reference the wrong way round and requires it to differ materially before comparing -// the kernel. A test that only did the second half would pass against either reading. -// 2. THE SCALAR GATE. `ffn_gate_inp_shexp` is (n_embd,) and yields ONE value per token; the two rival -// 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 - -#include -#include -#include -#include -#include -#include -#include - -namespace { - -void check(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -// THE CONVERSIONS COME FROM `f16_bits.hpp`, and this test used to carry its own copies. The private -// `f16_to_f32` here flushed fp16 SUBNORMALS to zero (`if (ex == 0) out = sign`), so 0x0001 decoded as 0.0 -// instead of 2^-24; and the private encoder returned NaN for finite fp16 overflow. Neither is visible with -// an O(1) fixture, which is exactly what this file had. Using the shared, oracle-validated pair means the -// test and the kernel cannot disagree about the conversion itself. -// using-declarations rather than renames at the call sites, so the body below is untouched by the swap. -using strata::kernels::f16_from_f32; -using strata::kernels::f32_from_f16; -inline uint16_t f32_to_f16(float f) { return f16_from_f32(f); } -inline float f16_to_f32(uint16_t h) { return f32_from_f16(h); } - -// The S2 decode used from the host: one code per element, group 64, bias -1. -// Normalised L1 difference, used by the moe_combine checks. (The shared-expert checks above report worst -// RELATIVE error per output instead, because there the question is per-element accuracy; here it is whether a -// whole rival READING is distinguishable, which is a vector-level question.) -double rel_l1(const std::vector& a, const std::vector& 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); -} - -/// `block_q8_0` on the host: 34 bytes per 32 elements, `fp16 d` then `int8 qs[32]`. Written from the LAYOUT -/// rather than from the kernel, so it can disagree with it. -double q8_0_host(const std::vector& x, long long i) { - const uint8_t* blk = x.data() + (size_t) (i / 32) * 34; - uint16_t db; - std::memcpy(&db, blk, 2); - const int8_t q = ((const int8_t*) (blk + 2))[i % 32]; - return (double) strata::kernels::f32_from_f16(db) * (double) q; -} - -float s2_weight(const std::vector& codes, const std::vector& scales, long long row, long long n_in, long long i) { - const uint8_t byte = codes[(size_t) (row * (n_in / 4) + i / 4)]; - const int code = (byte >> ((i % 4) * 2)) & 3; - return (float) (code - 1) * scales[(size_t) (row * (n_in / 64) + i / 64)]; -} - -} // namespace - -int main(int argc, char** argv) { - bool selftest = false; - for (int i = 1; i < argc; ++i) { - if (std::string(argv[i]) == "--selftest") selftest = true; - else { std::fprintf(stderr, "usage: shared_expert_parity [--selftest]\n"); return 2; } - } - - const long long n_embd = 256, n_ff = 64; // small, so the host reference can be a plain loop - const int tpr = 32; - std::mt19937 rng(77); - std::normal_distribution gauss(0.0f, 1.0f); - - // POSITIVE activations, so the sign of each projection is set by the sign of its weights. - std::vector fx((size_t) n_embd); - for (auto& v : fx) v = std::fabs(gauss(rng)) + 0.5f; - std::vector hx((size_t) n_embd); - std::vector hx0; // filled below, once the Q8_0 image exists; the reference reads it - for (long long i = 0; i < n_embd; ++i) hx[(size_t) i] = f32_to_f16(fx[(size_t) i]); - - // GATE CODES ALL 3 (+2d) AND UP CODES ALL 0 (-d): with positive scales and positive activations the gate - // projection is strongly POSITIVE and the up projection strongly NEGATIVE, which is the configuration where - // `silu(g)*u` and `silu(u)*g` differ by orders of magnitude rather than by percent. - std::vector gc((size_t) n_ff * n_embd / 4, 0xFF), uc((size_t) n_ff * n_embd / 4, 0x00), - dc((size_t) n_embd * n_ff / 4); - for (auto& v : dc) v = (uint8_t) (rng() & 0xFF); - std::vector gs((size_t) n_ff * (n_embd / 64)), us((size_t) n_ff * (n_embd / 64)), - ds((size_t) n_embd * (n_ff / 64)); - // GATE/UP SCALES ARE 10x SMALLER THAN THE DOWN SCALES, and that asymmetry is load-bearing. - // - // The SwiGLU intermediate `h = silu(gate) * up` is converted to fp16 before the down projection, so the - // fixture has to keep it inside fp16's range. At 0.2..0.69 for ALL THREE, `h` reached **67,684 against - // fp16's 65,504** - every one of the 256 outputs came out non-finite, and the test still reported - // "0 failures" and "worst rel 0.000e+00" (see the note on the metric below). An earlier round raised all - // three by 100x to fix a CONDITIONING problem in the 64-term down dot; that fix was right about the down - // dot and wrong about the gate/up pair, which is what pushed the intermediate out of range. - // - // Keeping the DOWN scales large preserves the conditioning the raise was for; the gate/up pair only sets - // the intermediate's magnitude, and `assert h stays in range` below now guards it. - auto fill_gu = [&](std::vector& v) { for (auto& s : v) s = 0.02f + 0.001f * (float) (rng() % 50); }; - auto fill_d = [&](std::vector& v) { for (auto& s : v) s = 0.2f + 0.01f * (float) (rng() % 50); }; - fill_gu(gs); - fill_gu(us); - fill_d(ds); - std::vector ginp((size_t) n_embd); - for (auto& v : ginp) v = gauss(rng) * 0.05f; - - // THE SCALAR GATE'S TWO OPERANDS ARE BF16, because `ffn_gate_inp_shexp` is a BF16 weight and ggml converts - // the activation to the weight's `vec_dot_type`. The reference therefore dots the bf16 IMAGES of both, not - // the originals - and the kernel is handed the same bf16 images. Rounding both here rather than only on - // the device is what keeps the comparison honest: rounding one side alone would show up as a fixed offset - // in the gate and be blamed on the kernel. - std::vector hx_bf16((size_t) n_embd), hginp_bf16((size_t) n_embd); - for (long long i = 0; i < n_embd; ++i) { - hx_bf16[(size_t) i] = strata::kernels::bf16_from_f32(fx[(size_t) i]); - hginp_bf16[(size_t) i] = strata::kernels::bf16_from_f32(ginp[(size_t) i]); - } - - // ---- host reference, exactly as ref/moe.py writes it - auto reference = [&](bool silu_on_up, bool elementwise_gate) { - std::vector gp((size_t) n_ff, 0.0f), upp((size_t) n_ff, 0.0f); - for (long long r = 0; r < n_ff; ++r) { - double a = 0, b = 0; - for (long long i = 0; i < n_embd; ++i) { - const double xv = q8_0_host(hx0, i); - a += xv * (double) s2_weight(gc, gs, r, n_embd, i); - b += xv * (double) s2_weight(uc, us, r, n_embd, i); - } - gp[(size_t) r] = (float) a; - upp[(size_t) r] = (float) b; - } - std::vector h((size_t) n_ff); - for (long long r = 0; r < n_ff; ++r) { - const double gv = silu_on_up ? upp[(size_t) r] : gp[(size_t) r]; - const double other = silu_on_up ? gp[(size_t) r] : upp[(size_t) r]; - h[(size_t) r] = (float) (gv / (1.0 + std::exp(-gv))) * (float) other; - } - // THE INTERMEDIATE IS QUANTIZED TO Q8_0, which is what the DOWN weight's contract asks for and what the - // kernel now does. ggml's `quantize_row_q8_0`: `d = amax / 127`, `q = round(x / d)`, value `q * d`. - // Written out here rather than reused, so that it CAN disagree with the kernel. - std::vector h16((size_t) n_ff); - for (long long b = 0; b < n_ff; b += 32) { - const long long e = (b + 32 < n_ff) ? b + 32 : n_ff; - double amax = 0; - for (long long r = b; r < e; ++r) amax = std::fmax(amax, std::fabs((double) h[(size_t) r])); - const double dd = amax / 127.0; - const double id = dd > 0 ? 1.0 / dd : 0.0; - for (long long r = b; r < e; ++r) { - double q = std::round((double) h[(size_t) r] * id); - q = std::fmax(-127.0, std::fmin(127.0, q)); - h16[(size_t) r] = (float) (q * dd); - } - } - std::vector out((size_t) n_embd, 0.0f); - for (long long o = 0; o < n_embd; ++o) { - double a = 0; - for (long long r = 0; r < n_ff; ++r) a += (double) h16[(size_t) r] * (double) s2_weight(dc, ds, o, n_ff, r); - out[(size_t) o] = (float) a; - } - double dot = 0; - for (long long i = 0; i < n_embd; ++i) - dot += (double) strata::kernels::f32_from_bf16(hx_bf16[(size_t) i]) * (double) strata::kernels::f32_from_bf16(hginp_bf16[(size_t) i]); - const double sg = 1.0 / (1.0 + std::exp(-dot)); - for (long long o = 0; o < n_embd; ++o) { - out[(size_t) o] = elementwise_gate ? (float) ((double) out[(size_t) o] * sg) - : (float) ((double) out[(size_t) o] * sg); - } - return out; - }; - - // ---- device side - uint16_t* d_x = nullptr; - uint8_t* d_x_used = nullptr; // the Q8_0 image the kernel now takes - uint16_t *d_xb = nullptr, *d_ginpb = nullptr; - uint8_t *d_gc = nullptr, *d_uc = nullptr, *d_dc = nullptr; - float *d_gs = nullptr, *d_us = nullptr, *d_ds = nullptr, *d_ginp = nullptr, *d_out = nullptr; - check(cudaMalloc(&d_x, hx.size() * sizeof(uint16_t)), "m x"); - check(cudaMalloc(&d_gc, gc.size()), "m gc"); - check(cudaMalloc(&d_uc, uc.size()), "m uc"); - check(cudaMalloc(&d_dc, dc.size()), "m dc"); - check(cudaMalloc(&d_gs, gs.size() * sizeof(float)), "m gs"); - check(cudaMalloc(&d_us, us.size() * sizeof(float)), "m us"); - check(cudaMalloc(&d_ds, ds.size() * sizeof(float)), "m ds"); - check(cudaMalloc(&d_ginp, ginp.size() * sizeof(float)), "m ginp"); - check(cudaMalloc(&d_xb, hx_bf16.size() * sizeof(uint16_t)), "m xb"); - check(cudaMalloc(&d_ginpb, hginp_bf16.size() * sizeof(uint16_t)), "m ginpb"); - check(cudaMalloc(&d_out, (size_t) n_embd * sizeof(float)), "m out"); - check(cudaMemcpy(d_x, hx.data(), hx.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "c x"); - check(cudaMemcpy(d_gc, gc.data(), gc.size(), cudaMemcpyHostToDevice), "c gc"); - check(cudaMemcpy(d_uc, uc.data(), uc.size(), cudaMemcpyHostToDevice), "c uc"); - check(cudaMemcpy(d_dc, dc.data(), dc.size(), cudaMemcpyHostToDevice), "c dc"); - check(cudaMemcpy(d_gs, gs.data(), gs.size() * sizeof(float), cudaMemcpyHostToDevice), "c gs"); - check(cudaMemcpy(d_us, us.data(), us.size() * sizeof(float), cudaMemcpyHostToDevice), "c us"); - check(cudaMemcpy(d_ds, ds.data(), ds.size() * sizeof(float), cudaMemcpyHostToDevice), "c ds"); - check(cudaMemcpy(d_ginp, ginp.data(), ginp.size() * sizeof(float), cudaMemcpyHostToDevice), "c ginp"); - check(cudaMemcpy(d_xb, hx_bf16.data(), hx_bf16.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "c xb"); - check(cudaMemcpy(d_ginpb, hginp_bf16.data(), hginp_bf16.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), - "c ginpb"); - - const strata::kernels::SForm f{2, -1, 64, strata::kernels::Codebook::Affine, false, /*act_kind=*/0}; - // **THE ACTIVATION IS Q8_0, NOT FP16, AND THE FIXTURE HAS TO MATCH THE CONTRACT.** The kernel used to take - // an fp16 activation for all three projections, which was simply the wrong `vec_dot_type` - and the - // reference here computed with the fp16 values, so the two agreed on a number the reference model would not - // produce. A fixture that agrees with the kernel about the wrong activation is not a check. - hx0.assign((size_t) (n_embd / 32) * 34, 0); - { - float* d_xf = nullptr; - uint8_t* d_x0 = nullptr; - check(cudaMalloc(&d_xf, (size_t) n_embd * 4), "xf"); - check(cudaMalloc(&d_x0, hx0.size()), "x0"); - check(cudaMemcpy(d_xf, fx.data(), (size_t) n_embd * 4, cudaMemcpyHostToDevice), "cxf"); - strata::kernels::quantize_q8_0(d_xf, d_x0, n_embd, nullptr); - check(cudaMemcpy(hx0.data(), d_x0, hx0.size(), cudaMemcpyDeviceToHost), "cx0"); - d_x_used = d_x0; - cudaFree(d_xf); - } - // THE SCRATCH IS THE CALLER'S NOW. It used to be four `cudaMalloc`s inside the kernel - illegal during - // stream capture AND a token-path allocation that P2.T10 forbids. The fixture owns it here, exactly as the - // layer does, so the test exercises the real contract instead of a private one. - float* d_scratch = nullptr; - check(cudaMalloc(&d_scratch, strata::kernels::shared_expert_scratch_bytes(n_ff)), "m scratch"); - strata::kernels::shared_expert(d_x_used, nullptr, d_xb, f, d_gc, d_gs, nullptr, f, d_uc, d_us, nullptr, f, - d_dc, d_ds, nullptr, d_ginpb, d_scratch, d_out, n_embd, n_ff, tpr, nullptr); - std::vector got((size_t) n_embd); - check(cudaMemcpy(got.data(), d_out, got.size() * sizeof(float), cudaMemcpyDeviceToHost), "c out"); - - int bad = 0; - const std::vector want = reference(false, false); - const std::vector wrong_silu = reference(true, false); - - // ---- the trap, asserted observable BEFORE the kernel is judged - double d_wrong = 0, mag = 0; - for (long long o = 0; o < n_embd; ++o) { - d_wrong += std::fabs((double) want[(size_t) o] - (double) wrong_silu[(size_t) o]); - mag += std::fabs((double) want[(size_t) o]); - } - const double rel_wrong = d_wrong / (mag > 1e-30 ? mag : 1e-30); - std::printf(" %-40s %s (%.2f%% apart)\n", "silu-on-gate vs silu-on-up is observable", - rel_wrong > 0.5 ? "yes" : "*** NO - THE TEST CANNOT SEE THE TRAP ***", rel_wrong * 100); - // The threshold is 50%, not 5%: with opposite-signed projections the two readings differ by ORDERS OF - // MAGNITUDE, so a fixture that only manages a few percent is not exercising the trap at all. - // - // **WRITTEN `!(x > floor)` AND NOT `x <= floor`.** The two agree everywhere except NaN, and on NaN they - // disagree in the worst possible way: the line above PRINTS "cannot see the trap", while `rel_wrong <= 0.5` - // is FALSE for NaN and therefore counted no failure. The test reported "0 failures" with a NaN fixture - - // a test that lies about the one thing it exists to check. A comparison written `x <= t` is a check that - // NaN silently passes, and this project writes them by habit. - if (!(rel_wrong > 0.5)) ++bad; - - // ---- the kernel against the correct reference - double worst = 0, sum = 0; - long long nonfinite = 0; - for (long long o = 0; o < n_embd; ++o) { - const double a = want[(size_t) o], b = got[(size_t) o]; - sum += std::fabs(a); - if (!std::isfinite(a) || !std::isfinite(b)) ++nonfinite; - const double rel = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30); - // `!(rel <= worst)` rather than `rel > worst`: with NaN, `rel > worst` never fires, `worst` stays at - // its initial 0, and the summary line reports **worst rel 0.000e+00** for a fixture that is entirely - // NaN. That is how this check reported a clean pass while computing nothing. - if (!(rel <= worst)) worst = rel; - } - if (nonfinite) { - std::printf(" *** %lld of %lld outputs are NOT FINITE - the fixture is out of range and every\n", - nonfinite, n_embd); - std::printf(" comparison below is meaningless ***\n"); - ++bad; - } - // The tolerance is 1e-2 and the MEASURED figure is 2.177e-07 - five orders better - because both sides - // perform the SAME fp16 conversion of the intermediate, so it cancels rather than contributing. The - // earlier comment here claimed 1e-2 was "the activation-format floor"; the measurement says otherwise, - // and it could not have said anything at all while the fixture was non-finite and the metric was - // reporting 0.000e+00 for it. - // - // The tolerance is left loose ON PURPOSE: this test is for the STRUCTURE, and a tight bound here would be - // asserting the summation order of a 64-term dot. The number that matters is printed next to it. - std::printf(" %-40s worst rel %.3e over %lld outputs (mean |ref| %.4f)\n", "structure vs reference", - worst, n_embd, sum / (double) n_embd); - if (!(worst <= 1e-2)) { - std::printf(" *** over 1e-2 - that is beyond the activation-format floor, so it is structural ***\n"); - ++bad; - } - - // ---- THE FIXTURE MUST STAY INSIDE FP16, because that is the domain the kernel works in. - // - // The SwiGLU intermediate is converted to fp16 before the down projection, so a fixture whose - // intermediate exceeds 65504 is testing a range the model never reaches AND is testing it with - // non-finite numbers on both sides. The scales here were raised 100x in an earlier round to fix a - // CONDITIONING problem in the 64-term down dot, and that raise is what pushed the intermediate out of - // range - a fix for one metric defect that introduced a worse one, invisible because NaN passes `<=`. - { - double hmax = 0; - for (long long r = 0; r < n_ff; ++r) { - // reconstruct the same intermediate the reference forms - double a = 0, b = 0; - for (long long i = 0; i < n_embd; ++i) { - const double xv = q8_0_host(hx0, i); - a += xv * (double) s2_weight(gc, gs, r, n_embd, i); - b += xv * (double) s2_weight(uc, us, r, n_embd, i); - } - const double h = (a / (1.0 + std::exp(-a))) * b; - hmax = std::fmax(hmax, std::fabs(h)); - } - const bool in_range = hmax < 65504.0 && std::isfinite(hmax); - std::printf(" %-40s %s (max |h| %.1f, fp16 max 65504)\n", "the fixture's SwiGLU stays in fp16 range", - in_range ? "yes" : "*** NO ***", hmax); - if (!in_range) ++bad; - } - - // Isolate the BF16 scalar gate: keep the quantized expert inputs fixed and vary only its F32/BF16 - // activation. A zero scalar weight first exposes half the ungated output without duplicating the GEMVs. - { - using namespace strata::kernels; - std::vector zeros((size_t) n_embd, 0), basis(zeros); - basis[0] = bf16_from_f32(1.0f); - std::vector witness((size_t) n_embd, 0.0f); - witness[0] = 1.00390625f; - std::vector witness_bf16((size_t) n_embd, 0); - witness_bf16[0] = bf16_from_f32(witness[0]); - float* d_witness = nullptr; - check(cudaMalloc(&d_witness, witness.size() * sizeof(float)), "native shared x"); - check(cudaMemcpy(d_witness, witness.data(), witness.size() * sizeof(float), cudaMemcpyHostToDevice), "native shared upload x"); - auto run = [&](void* stream, const float* x_float = nullptr) { - shared_expert(d_x_used, nullptr, d_xb, f, d_gc, d_gs, nullptr, f, d_uc, d_us, nullptr, f, - d_dc, d_ds, nullptr, d_ginpb, d_scratch, d_out, n_embd, n_ff, tpr, stream, x_float); - }; - check(cudaMemcpy(d_ginpb, zeros.data(), zeros.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "zero shared gate"); - run(nullptr); - std::vector half_output((size_t) n_embd), legacy((size_t) n_embd), native((size_t) n_embd), replay((size_t) n_embd); - check(cudaMemcpy(half_output.data(), d_out, half_output.size() * sizeof(float), cudaMemcpyDeviceToHost), "half shared output"); - check(cudaMemcpy(d_ginpb, basis.data(), basis.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "basis shared gate"); - check(cudaMemcpy(d_xb, witness_bf16.data(), witness_bf16.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "witness shared bf16"); - run(nullptr); - check(cudaMemcpy(legacy.data(), d_out, legacy.size() * sizeof(float), cudaMemcpyDeviceToHost), "legacy witness output"); - shared_expert_set_native_bf16(true); - bool refused_missing = false; - try { run(nullptr); } catch (const std::invalid_argument&) { refused_missing = true; } - if (!refused_missing) ++bad; - cudaStream_t stream; - check(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), "native shared stream"); - run(stream, d_witness); - check(cudaStreamSynchronize(stream), "native shared sync"); - check(cudaMemcpy(native.data(), d_out, native.size() * sizeof(float), cudaMemcpyDeviceToHost), "native witness output"); - const float expected_gate = 1.0f / (1.0f + std::exp(-witness[0])); - double error = 0.0, magnitude = 0.0; - for (size_t i = 0; i < native.size(); ++i) { - const float expected = (half_output[i] * 2.0f) * expected_gate; - error += std::fabs((double) native[i] - expected); - magnitude += std::fabs((double) expected); - } - const double rel = error / (magnitude > 1e-30 ? magnitude : 1e-30); - const double visible = rel_l1(native, legacy); - const bool correct = std::isfinite(rel) && rel < 2e-6 && visible > 1e-5 && refused_missing; - std::printf(" native shared scalar gate: %s (ref rel %.3e, BF16 separation %.3e, missing input %s)\n", - correct ? "pass" : "FAIL", rel, visible, refused_missing ? "refused" : "FAIL"); - if (!correct) ++bad; - cudaGraph_t graph; - cudaGraphExec_t executable; - check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "native shared capture"); - run(stream, d_witness); - check(cudaStreamEndCapture(stream, &graph), "native shared capture end"); - check(cudaGraphInstantiate(&executable, graph, nullptr, nullptr, 0), "native shared graph instantiate"); - shared_expert_set_native_bf16(false); - check(cudaGraphLaunch(executable, stream), "native shared graph replay"); - check(cudaStreamSynchronize(stream), "native shared graph sync"); - check(cudaMemcpy(replay.data(), d_out, replay.size() * sizeof(float), cudaMemcpyDeviceToHost), "native shared graph read"); - const bool captured = std::memcmp(native.data(), replay.data(), native.size() * sizeof(float)) == 0; - std::printf(" native shared captured selection: %s\n", captured ? "byte-identical" : "FAIL"); - if (!captured) ++bad; - check(cudaGraphExecDestroy(executable), "native shared graph exec destroy"); - check(cudaGraphDestroy(graph), "native shared graph destroy"); - check(cudaStreamDestroy(stream), "native shared stream destroy"); - check(cudaMemcpy(d_ginpb, hginp_bf16.data(), hginp_bf16.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "restore shared gate"); - check(cudaMemcpy(d_xb, hx_bf16.data(), hx_bf16.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "restore shared bf16"); - run(nullptr); - check(cudaMemcpy(replay.data(), d_out, replay.size() * sizeof(float), cudaMemcpyDeviceToHost), "restored shared output"); - const bool restored = std::memcmp(got.data(), replay.data(), got.size() * sizeof(float)) == 0; - std::printf(" restored shared default: %s\n", restored ? "byte-identical" : "FAIL"); - if (!restored) ++bad; - 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 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& bytes, std::vector& 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 gb, ub, db; - std::vector 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 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 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 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& x) { - std::vector 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 xq = q8_1_values(x2); - std::vector 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 hq = q8_1_values(h); - std::vector 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 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 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 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(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]` - // (L100). Two rival readings both produce a plausible vector of the right shape: - // - // A. the routed sum is UNWEIGHTED (a plain sum of the k expert outputs), and - // B. the SHARED output is router-weighted like the routed ones. - // - // Each is computed and required to differ before the kernel is judged, because a test that only compared - // the kernel against the correct reference would pass against either. - { - const long long n_embd2 = 256, k2 = 10; - std::mt19937 rng2(31337); - std::normal_distribution g2(0.0f, 1.0f); - std::vector parts((size_t) (k2 * n_embd2)), w((size_t) k2), shared((size_t) n_embd2); - for (auto& v : parts) v = g2(rng2); - // Weights that genuinely VARY, and genuinely miss 1/k: with uniform weights the unweighted reading - // would coincide with the weighted one and the fixture could not see reading A. - double wsum = 0; - for (auto& v : w) { v = std::fabs(g2(rng2)) + 0.05f; wsum += v; } - for (auto& v : w) v = (float) (v / wsum); // already renormalised, as router_top10 emits - for (auto& v : shared) v = g2(rng2) * 3.0f; - - auto ref = [&](bool weight_routed, bool weight_shared) { - std::vector y((size_t) n_embd2, 0.0f); - for (long long j = 0; j < n_embd2; ++j) { - double a = 0; - for (long long e = 0; e < k2; ++e) - a += (weight_routed ? (double) w[(size_t) e] : 1.0) * (double) parts[(size_t) (e * n_embd2 + j)]; - a += weight_shared ? (double) w[0] * (double) shared[(size_t) j] : (double) shared[(size_t) j]; - y[(size_t) j] = (float) a; - } - return y; - }; - const std::vector want = ref(true, false); - - float *d_p = nullptr, *d_w = nullptr, *d_s = nullptr, *d_y = nullptr; - check(cudaMalloc(&d_p, parts.size() * 4), "mc p"); - check(cudaMalloc(&d_w, w.size() * 4), "mc w"); - check(cudaMalloc(&d_s, shared.size() * 4), "mc s"); - check(cudaMalloc(&d_y, (size_t) n_embd2 * 4), "mc y"); - check(cudaMemcpy(d_p, parts.data(), parts.size() * 4, cudaMemcpyHostToDevice), "mc cp"); - check(cudaMemcpy(d_w, w.data(), w.size() * 4, cudaMemcpyHostToDevice), "mc cw"); - check(cudaMemcpy(d_s, shared.data(), shared.size() * 4, cudaMemcpyHostToDevice), "mc cs"); - strata::kernels::moe_combine(d_p, d_w, d_s, d_y, n_embd2, k2, nullptr); - std::vector got((size_t) n_embd2); - check(cudaMemcpy(got.data(), d_y, got.size() * 4, cudaMemcpyDeviceToHost), "mc cy"); - - for (const auto& trap : {std::make_pair(false, false), std::make_pair(true, true)}) { - const std::vector wrong = ref(trap.first, trap.second); - const double rel = rel_l1(want, wrong); - const char* what = (!trap.first && !trap.second) ? "routed sum left UNWEIGHTED is observable" - : "shared output router-WEIGHTED is observable"; - const bool visible = rel > 0.05; - std::printf(" %-42s %-4s (%.2f%% apart)\n", what, visible ? "yes" : "*** NO ***", rel * 100); - if (!visible) ++bad; - } - - const double rel_k = rel_l1(want, got); - std::printf(" %-42s rel %.3e\n", "moe_combine vs reference", rel_k); - // Both sides accumulate in double over the same k terms, so this is order-only. - if (!(rel_k <= 1e-6)) { std::printf(" *** over 1e-6 ***\n"); ++bad; } - - // a null `shared` must mean "no shared expert", not "add nothing but leave it undefined" - strata::kernels::moe_combine(d_p, d_w, nullptr, d_y, n_embd2, k2, nullptr); - check(cudaMemcpy(got.data(), d_y, got.size() * 4, cudaMemcpyDeviceToHost), "mc cy2"); - const double rel_no_shared = rel_l1(want, got); - const bool differs = rel_no_shared > 0.05; - std::printf(" %-42s %s (%.2f%% apart - null shared really omits it)\n", - "a null `shared` is observable", differs ? "yes" : "*** NO ***", rel_no_shared * 100); - if (!differs) ++bad; - cudaFree(d_p); cudaFree(d_w); cudaFree(d_s); cudaFree(d_y); - } - - std::printf("\nshared_expert: %d failures\n", bad); - if (bad) return 1; - if (selftest) std::printf("shared_expert_parity OK\n"); - return 0; -} \ No newline at end of file diff --git a/src/ngram/ple_reader.cpp b/src/ngram/ple_reader.cpp deleted file mode 100644 index a03e4c0..0000000 --- a/src/ngram/ple_reader.cpp +++ /dev/null @@ -1,547 +0,0 @@ -// src/ngram/ple_reader.cpp - see include/strata/ngram/ple_reader.hpp. -#include "strata/ngram/ple_reader.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace strata::ngram { - -using platform::Completion; -using platform::DirectFile; -using platform::now_us; - -double ReaderStats::percentile(double q) const { - if (read_us.empty()) return 0.0; - std::vector v(read_us); - const size_t k = std::min(v.size() - 1, (size_t) (q * (double) (v.size() - 1) + 0.5)); - std::nth_element(v.begin(), v.begin() + (ptrdiff_t) k, v.end()); - return v[k]; -} - -namespace { - -constexpr size_t LATENCY_RING = 65536; -constexpr uint32_t WAYS = 8; -constexpr uint32_t EMPTY = 0xFFFFFFFFu; - -/// Set-associative row cache: 8 ways per set, round-robin replacement inside a set. Bounded by construction. -struct RowCache { - uint64_t sets = 0; - uint32_t rb = ROW_BYTES; // bytes per row - std::vector keys; // sets * WAYS - std::vector data; // sets * WAYS * rb - std::vector next; // per-set replacement pointer - uint64_t used = 0; - - void init(uint64_t rows, uint32_t row_bytes = ROW_BYTES) { - sets = rows / WAYS; - rb = row_bytes; - keys.assign(sets * WAYS, EMPTY); - data.assign(sets * WAYS * rb, 0); - next.assign(sets, 0); - used = 0; - } - static uint64_t mix(uint32_t r) { - uint64_t x = r * 0x9E3779B97F4A7C15ull; - return x ^ (x >> 29); - } - const uint8_t* find(uint32_t row) const { - if (sets == 0) return nullptr; - const uint64_t s = mix(row) % sets; - for (uint32_t w = 0; w < WAYS; ++w) - if (keys[s * WAYS + w] == row) return &data[(s * WAYS + w) * rb]; - return nullptr; - } - void insert(uint32_t row, const uint8_t* bytes) { - if (sets == 0 || find(row) != nullptr) return; - const uint64_t s = mix(row) % sets; - uint32_t w = next[s]; - next[s] = (uint8_t) ((w + 1) % WAYS); - if (keys[s * WAYS + w] == EMPTY) ++used; - keys[s * WAYS + w] = row; - std::memcpy(&data[(s * WAYS + w) * rb], bytes, rb); - } -}; - -struct Use { - uint32_t row; - uint32_t in_page; // byte offset of the row inside the read buffer - uint8_t* dst; -}; - -struct Job { - uint64_t offset = 0; // aligned file offset - uint32_t length = 0; // PAGE or 2 * PAGE (a row that straddles a page boundary) - uint32_t ticket = 0; - std::vector uses; - double issued_us = 0; - bool keepalive = false;// no rows and no ticket: it only keeps the SSD awake (`set_keepalive`) -}; - -struct TicketState { - uint32_t pending = 0; // jobs not yet completed -}; - -} // namespace - -// THREADING. With `io_thread` (the default) one worker thread owns every DirectFile call: it submits queued jobs -// and reaps completions, so `issue` on the caller's thread only builds jobs and wakes it (~11 us per ReadFile -// no longer lands on the host loop). `mu` guards everything below except `file`, which only the worker touches -// (plus `wake`, which is thread-safe). Without `io_thread` the caller does all of it, as before. -struct PleReader::Impl { - DirectFile file; - uint64_t table_offset = 0; - uint64_t n_rows = 0; - uint32_t row_bytes = ROW_BYTES; - uint32_t max_inflight = 0; - uint8_t* slab = nullptr; // max_inflight slots of 2 pages - std::vector free_slots; - std::vector inflight; // indexed by slot - std::vector delayed; // completed but held back by fault injection - std::deque queue; // not yet submitted - std::unordered_map tickets; - uint32_t next_ticket = 1; - RowCache cache; - ReaderStats stats; - size_t ring_pos = 0; - double delay_us = 0; - std::string error; - // the keep-alive (`set_keepalive`), steady-clock microseconds; `keep_us` 0 = off - double keep_us = 0; - double keep_window_us = 0; - double last_issue_us = 0; // the last `issue` - double last_read_us = 0; // the last read that went out, rows or keep-alive - uint64_t rng = 0x9E3779B97F4A7C15ull; - - bool threaded = false; - bool stop = false; - std::mutex mu; - std::condition_variable cv_work; // worker: there is something to submit - std::condition_variable cv_done; // collectors: a ticket may have completed - std::thread worker; - - uint8_t* slot_buf(uint32_t s) { return slab + (size_t) s * 2 * PAGE; } - bool busy() const { return free_slots.size() < max_inflight || !delayed.empty(); } - - void cancel_queued() { - for (const Job& job : queue) { - auto it = tickets.find(job.ticket); - if (it != tickets.end() && it->second.pending > 0) --it->second.pending; - } - queue.clear(); - } - - void record_latency(double us) { - stats.read_us_sum += us; - if (stats.read_us.size() < LATENCY_RING) stats.read_us.push_back((float) us); - else stats.read_us[ring_pos++ % LATENCY_RING] = (float) us; - } - - bool pump() { - while (!queue.empty() && !free_slots.empty()) { - const uint32_t s = free_slots.back(); - free_slots.pop_back(); - inflight[s] = std::move(queue.front()); - queue.pop_front(); - Job& j = inflight[s]; - j.issued_us = now_us(); - std::string kerr; // a keep-alive read that cannot go out must not fail the reader - if (!file.submit(j.offset, slot_buf(s), j.length, s, j.keepalive ? kerr : error)) { - if (j.keepalive) { // no more of them: the SSD may sleep as before - keep_us = 0; - j.keepalive = false; - free_slots.push_back(s); - continue; - } - j.uses.clear(); - auto it = tickets.find(j.ticket); - if (it != tickets.end() && it->second.pending > 0) --it->second.pending; - free_slots.push_back(s); - cancel_queued(); - return false; - } - last_read_us = j.issued_us; - if (!j.keepalive) { // a keep-alive read counts when it completes (`finish`) - stats.submit_us += now_us() - j.issued_us; - ++stats.reads; - } - } - return true; - } - - /// When the next keep-alive read is due, or < 0 when none is: it is off, the reader failed, or no rows - /// were asked for within the window (then the SSD may sleep; the next `issue` re-arms it). - double keepalive_due(double now) const { - if (keep_us <= 0 || !error.empty() || last_issue_us <= 0 || now - last_issue_us > keep_window_us) return -1; - return last_read_us + keep_us; - } - - /// One page of the table, a different one each time, so the SSD really reads (not its controller's buffer). - void queue_keepalive() { - rng ^= rng << 13; - rng ^= rng >> 7; - rng ^= rng << 17; - const uint64_t first = table_offset / PAGE, end = (table_offset + n_rows * (uint64_t) row_bytes) / PAGE; - Job j; - j.offset = (first + (end > first ? rng % (end - first) : 0)) * PAGE; - j.length = PAGE; - j.keepalive = true; - queue.push_back(std::move(j)); - } - - bool finish(const Completion& c) { - const uint32_t s = (uint32_t) c.tag; - if (s >= inflight.size()) { - error = "PleReader: invalid table-read completion"; - cancel_queued(); - return false; - } - Job& j = inflight[s]; - if (j.keepalive) { // no rows: it counts once it is done, with how long it took; - if (c.ok) { // a failed one turns the keep-alive off, not the reader - ++stats.keepalive_reads; - stats.keepalive_us_max = std::max(stats.keepalive_us_max, now_us() - j.issued_us); - } else { - keep_us = 0; - } - j.keepalive = false; - free_slots.push_back(s); - return error.empty() ? pump() : true; - } - if (!c.ok) { - error = "PleReader: a table read failed"; - cancel_queued(); - j.uses.clear(); - auto it = tickets.find(j.ticket); - if (it != tickets.end() && it->second.pending > 0) --it->second.pending; - free_slots.push_back(s); - return false; - } - record_latency(now_us() - j.issued_us); - stats.bytes += c.bytes; - const uint8_t* buf = slot_buf(s); - for (const Use& u : j.uses) { - if (u.in_page + row_bytes > c.bytes) { - error = "PleReader: short read inside the table"; - cancel_queued(); - j.uses.clear(); - auto it = tickets.find(j.ticket); - if (it != tickets.end() && it->second.pending > 0) --it->second.pending; - free_slots.push_back(s); - return false; - } - } - for (const Use& u : j.uses) { - std::memcpy(u.dst, buf + u.in_page, row_bytes); - cache.insert(u.row, buf + u.in_page); - } - auto it = tickets.find(j.ticket); - if (it != tickets.end() && it->second.pending > 0) --it->second.pending; - j.uses.clear(); - free_slots.push_back(s); - return error.empty() ? pump() : true; - } - - /// Completions (or wake packets) just returned by `file.wait`, applying fault injection. - bool process(const Completion* got, int n) { - bool ok = true; - for (int i = 0; i < n; ++i) { - if (got[i].tag == DirectFile::WAKE_TAG) continue; - if (got[i].tag >= inflight.size()) { - error = "PleReader: invalid table-read completion"; - cancel_queued(); - ok = false; - continue; - } - if (delay_us > 0 && now_us() - inflight[(uint32_t) got[i].tag].issued_us < delay_us) { - delayed.push_back(got[i]); - ++stats.late_injected; - continue; - } - if (!finish(got[i])) ok = false; // drain the rest of this batch so no completed slot is stranded - } - return ok; - } - - bool release_delayed() { - const double now = now_us(); - for (size_t i = 0; i < delayed.size();) { - if (now - inflight[(uint32_t) delayed[i].tag].issued_us >= delay_us) { - const Completion c = delayed[i]; - delayed.erase(delayed.begin() + (ptrdiff_t) i); - if (!finish(c)) return false; - } else { - ++i; - } - } - return true; - } - - /// Caller-thread mode: process whatever has completed; blocks up to `timeout_ms` for the first completion. - bool drain(int timeout_ms) { - Completion got[64]; - if (!delayed.empty()) { - if (!release_delayed()) return false; - timeout_ms = 0; // keep polling the held completions - } - const int n = file.wait(got, 64, timeout_ms); - return process(got, n); - } - - void worker_loop() { - std::unique_lock lk(mu); - for (;;) { - // Idle: wait for work. While rows are being asked for, the wait ends in time for a keep-alive read. - while (!(stop || !queue.empty() || busy())) { - const double now = now_us(); - const double due = keepalive_due(now); - if (due < 0) cv_work.wait(lk); - else if (now >= due) queue_keepalive(); - else cv_work.wait_for(lk, std::chrono::microseconds(std::max(1000, (int64_t) (due - now)))); - } - if (stop && !busy()) break; - if (error.empty() && !pump() && error.empty()) error = "PleReader: submit failed"; - if (!delayed.empty() && !release_delayed() && error.empty()) error = "PleReader: read failed"; - if (!error.empty()) { - cv_done.notify_all(); - if (!busy()) { cv_work.wait(lk, [&] { return stop; }); break; } - } - if (!busy()) { cv_done.notify_all(); continue; } - // Block in the port WITHOUT the lock, so `issue` can queue work; `issue` wakes us with a packet. - const int timeout = delayed.empty() ? -1 : 0; - lk.unlock(); - Completion got[64]; - const int n = file.wait(got, 64, timeout); - lk.lock(); - if (!process(got, n) && error.empty()) error = "PleReader: read failed"; - cv_done.notify_all(); - } - } -}; - -PleReader::PleReader() : impl_(new Impl) {} -PleReader::~PleReader() { - close(); - delete impl_; -} - -bool PleReader::open(const std::string& path, uint64_t table_offset, uint64_t n_rows, uint32_t max_inflight, - uint64_t cache_rows, std::string& err, bool io_thread, uint32_t row_bytes) { - close(); - if (max_inflight == 0 || max_inflight > 1024) { err = "PleReader: max_inflight must be 1..1024"; return false; } - if (row_bytes == 0 || row_bytes > PAGE) { err = "PleReader: row_bytes must be 1..4096"; return false; } - if (!impl_->file.open(path, err)) return false; - impl_->row_bytes = row_bytes; - if (table_offset + n_rows * (uint64_t) row_bytes > impl_->file.size()) { - err = "PleReader: the table extends past the end of " + path; - close(); - return false; - } - impl_->table_offset = table_offset; - impl_->n_rows = n_rows; - impl_->max_inflight = max_inflight; - impl_->slab = (uint8_t*) DirectFile::alloc_aligned((size_t) max_inflight * 2 * PAGE); - if (impl_->slab == nullptr) { err = "PleReader: cannot allocate read buffers"; close(); return false; } - impl_->inflight.assign(max_inflight, Job{}); - impl_->free_slots.clear(); - for (uint32_t s = max_inflight; s-- > 0;) impl_->free_slots.push_back(s); - impl_->cache.init(cache_rows, row_bytes); - impl_->error.clear(); - impl_->keep_us = 0; - impl_->last_issue_us = impl_->last_read_us = 0; - impl_->rng = 0x9E3779B97F4A7C15ull ^ (uint64_t) now_us(); - if (impl_->rng == 0) impl_->rng = 1; - reset_stats(); - impl_->stop = false; - impl_->threaded = io_thread; - if (io_thread) { - try { - impl_->worker = std::thread([this] { impl_->worker_loop(); }); - } catch (const std::exception& e) { - err = std::string("PleReader: cannot create I/O worker: ") + e.what(); - close(); - return false; - } catch (...) { - err = "PleReader: cannot create I/O worker"; - close(); - return false; - } - } - return true; -} - -void PleReader::close() { - Impl& m = *impl_; - if (m.worker.joinable()) { - { - std::lock_guard lk(m.mu); - m.stop = true; - m.queue.clear(); // unsubmitted work is dropped; in-flight reads still drain - } - m.cv_work.notify_all(); - m.file.wake(); - m.worker.join(); - } - // Outstanding reads must finish before their buffers are released (caller-thread mode, or a worker that - // stopped on an error). - if (m.file.is_open()) { - while (m.free_slots.size() < m.max_inflight) { - Completion c[64]; - const int n = m.file.wait(c, 64, -1); - if (n == 0) break; - for (int i = 0; i < n; ++i) - if (c[i].tag != DirectFile::WAKE_TAG) m.free_slots.push_back((uint32_t) c[i].tag); - } - } - m.file.close(); - DirectFile::free_aligned(m.slab); - m.slab = nullptr; - m.queue.clear(); - m.tickets.clear(); - m.delayed.clear(); - m.inflight.clear(); - m.free_slots.clear(); - m.cache.init(0); - m.threaded = false; - m.stop = false; - m.keep_us = 0; - m.last_issue_us = m.last_read_us = 0; -} - -bool PleReader::is_open() const { return impl_->file.is_open(); } -uint32_t PleReader::row_bytes() const { return impl_->row_bytes; } - -PleReader::Ticket PleReader::issue(const uint32_t* rows, size_t n, uint8_t* out_raw) { - Impl& m = *impl_; - std::unique_lock lk(m.mu, std::defer_lock); - if (m.threaded) lk.lock(); - const uint32_t id = m.next_ticket++; - if (m.next_ticket == 0) m.next_ticket = 1; - const double now = now_us(); - const bool rearm = m.keep_us > 0 && (m.last_issue_us <= 0 || now - m.last_issue_us > m.keep_window_us); - m.last_issue_us = now; - TicketState& ts = m.tickets[id]; - std::unordered_map by_page; // aligned offset -> index in `jobs` - std::vector jobs; - for (size_t i = 0; i < n; ++i) { - const uint32_t rb = m.row_bytes; - uint8_t* dst = out_raw + i * rb; - ++m.stats.requests; - if (rows[i] >= m.n_rows) { - std::memset(dst, 0, rb); - continue; - } - if (const uint8_t* hit = m.cache.find(rows[i])) { - std::memcpy(dst, hit, rb); - ++m.stats.cache_hits; - continue; - } - const uint64_t at = m.table_offset + (uint64_t) rows[i] * rb; - const uint64_t first = at / PAGE * PAGE; - const uint32_t length = (uint32_t) ((at + rb - 1) / PAGE * PAGE - first + PAGE); - auto f = by_page.find(first); - if (f != by_page.end()) { - Job& j = jobs[f->second]; - j.length = std::max(j.length, length); - j.uses.push_back(Use{rows[i], (uint32_t) (at - first), dst}); - ++m.stats.dedup_rows; - continue; - } - by_page.emplace(first, jobs.size()); - Job j; - j.offset = first; - j.length = length; - j.ticket = id; - j.uses.push_back(Use{rows[i], (uint32_t) (at - first), dst}); - jobs.push_back(std::move(j)); - } - // Sorted by offset: prefill chunks then read the SSD in near-sequential order. - std::sort(jobs.begin(), jobs.end(), [](const Job& a, const Job& b) { return a.offset < b.offset; }); - ts.pending = (uint32_t) jobs.size(); - const bool has_jobs = ts.pending > 0; - for (Job& j : jobs) m.queue.push_back(std::move(j)); - if (m.threaded) { - lk.unlock(); - if (has_jobs) { - m.cv_work.notify_one(); - m.file.wake(); // in case the worker is blocked in the port - } else if (rearm) { - m.cv_work.notify_one(); // the keep-alive had lapsed: start it again - } - } else if (!m.pump() && m.error.empty()) { - m.error = "PleReader: submit failed"; - } - return Ticket{id}; -} - -bool PleReader::collect(Ticket t, std::string& err) { - Impl& m = *impl_; - const double start = now_us(); - if (m.threaded) { - std::unique_lock lk(m.mu); - auto it = m.tickets.find(t.id); - if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; } - m.cv_done.wait(lk, [&] { - const auto current = m.tickets.find(t.id); - return current == m.tickets.end() || current->second.pending == 0; - }); - it = m.tickets.find(t.id); - if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; } - if (!m.error.empty()) { err = m.error; return false; } - m.stats.wait_us += now_us() - start; - m.tickets.erase(it); - return true; - } - auto it = m.tickets.find(t.id); - if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; } - while (it->second.pending > 0) { - const bool drained = m.drain(-1); - if (!drained && m.error.empty()) m.error = "PleReader: read failed"; - it = m.tickets.find(t.id); - if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; } - } - if (!m.error.empty()) { err = m.error; return false; } - m.stats.wait_us += now_us() - start; - m.tickets.erase(it); - return true; -} - -void PleReader::set_keepalive(double period_ms, double window_s) { - Impl& m = *impl_; - { - std::lock_guard lk(m.mu); - m.keep_us = m.threaded && period_ms > 0 ? period_ms * 1000.0 : 0.0; - m.keep_window_us = window_s > 0 ? window_s * 1e6 : 0.0; - } - m.cv_work.notify_all(); -} - -void PleReader::set_injected_delay_us(double delay_us) { - std::lock_guard lk(impl_->mu); - impl_->delay_us = delay_us < 0 ? 0 : delay_us; -} -const ReaderStats& PleReader::stats() const { return impl_->stats; } -ReaderStats PleReader::snapshot() const { - Impl& m = *impl_; - std::unique_lock lk(m.mu, std::defer_lock); - if (m.threaded) lk.lock(); - return m.stats; -} -void PleReader::reset_stats() { - Impl& m = *impl_; - std::unique_lock lk(m.mu, std::defer_lock); - if (m.threaded) lk.lock(); // the worker may be counting a keep-alive read - m.stats = ReaderStats{}; - m.ring_pos = 0; -} -uint64_t PleReader::cache_capacity() const { return impl_->cache.sets * WAYS; } -uint64_t PleReader::cache_size() const { return impl_->cache.used; } - -} // namespace strata::ngram diff --git a/src/ngram/ple_reader_test.cpp b/src/ngram/ple_reader_test.cpp deleted file mode 100644 index 87270fd..0000000 --- a/src/ngram/ple_reader_test.cpp +++ /dev/null @@ -1,298 +0,0 @@ -// src/ngram/ple_reader_test.cpp - plan v0.3 P2: the direct SSD row reader against ground truth. -// -// ple_reader_test --selftest [--dir D] synthetic table file; CPU and disk only, no model, no GPU -// ple_reader_test --gguf SHARD2 [--rows N] the real table: Direct vs Mmap bytes for N random rows (+ the -// 16 rows of every token in --tokens FILE), with read latencies -// -// Every row the synthetic table holds encodes its own index, so a wrong offset, a straddle mishandled or a -// dedup slot mixed up shows as a mismatch rather than as plausible data. -#include "strata/kernels/ngram.hpp" -#include "strata/ngram/ple_reader.hpp" -#include "strata/platform/direct_file.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ng = strata::ngram; -namespace k = strata::kernels; -using strata::platform::now_us; - -namespace { - -int g_fail = 0; -#define CHECK(c, ...) \ - do { \ - if (!(c)) { \ - std::fprintf(stderr, "FAIL %s:%d: ", __FILE__, __LINE__); \ - std::fprintf(stderr, __VA_ARGS__); \ - std::fprintf(stderr, "\n"); \ - ++g_fail; \ - } \ - } while (0) - -constexpr uint64_t HEADER = 192; // the real shard's data offset, so rows are misaligned the same way - -void expected_row(uint32_t row, uint32_t rb, uint8_t* out) { - for (uint32_t b = 0; b < rb; ++b) out[b] = (uint8_t) ((row * 2654435761u + b * 97u) >> 7); - std::memcpy(out, &row, 4); -} - -bool make_table(const std::string& path, uint32_t rows, uint32_t rb) { - std::ofstream f(path, std::ios::binary); - std::vector head(HEADER, 0xAB); - f.write((const char*) head.data(), (std::streamsize) head.size()); - std::vector r(rb); - for (uint32_t i = 0; i < rows; ++i) { - expected_row(i, rb, r.data()); - f.write((const char*) r.data(), rb); - } - return (bool) f; -} - -bool check_rows(ng::PleReader& rd, const std::vector& rows, uint32_t n_rows, uint32_t rb, const char* what) { - std::vector out(rows.size() * rb, 0xCC); - std::string err; - const auto t = rd.issue(rows.data(), rows.size(), out.data()); - if (!rd.collect(t, err)) { CHECK(false, "%s: collect failed: %s", what, err.c_str()); return false; } - std::vector want(rb); - for (size_t i = 0; i < rows.size(); ++i) { - if (rows[i] >= n_rows) std::memset(want.data(), 0, rb); - else expected_row(rows[i], rb, want.data()); - if (std::memcmp(want.data(), &out[i * rb], rb) != 0) { - CHECK(false, "%s: row %u (index %zu) differs", what, rows[i], i); - return false; - } - } - return true; -} - -// row_bytes: ng::ROW_BYTES (90, IQ4_NL) is the production default; 110 (#296, OrcaRouter's Q5_0 PLE rows) is -// run too, through the exact same generic row_bytes path -- nothing here is IQ4_NL-specific, so a second row -// size run here is the correctness evidence for lifting ngram.cpp's "Q5_0 PLE requires --ple-io mmap" refusal. -int selftest(const std::string& dir, uint32_t rb) { - const uint32_t N = 500000; // 45 MB: large enough for thousands of distinct pages - const std::string path = dir + "/ple_reader_selftest_" + std::to_string(rb) + ".bin"; - if (!make_table(path, N, rb)) { std::fprintf(stderr, "cannot write %s\n", path.c_str()); return 2; } - std::mt19937 rng(7); - for (bool thr : {false, true}) - for (uint64_t cache : {0ull, 4096ull}) { - for (uint32_t inflight : {1u, 8u, 64u}) { - ng::PleReader rd; - std::string err; - CHECK(rd.open(path, HEADER, N, inflight, cache, err, thr, rb), "open: %s", err.c_str()); - // decode-shaped tickets: 16 random rows - for (int t = 0; t < 200; ++t) { - std::vector rows(16); - for (auto& r : rows) r = rng() % N; - check_rows(rd, rows, N, rb, "decode"); - } - // rows that straddle a 4 KiB boundary: byte offset of row r is HEADER + rb * r - std::vector straddle; - for (uint32_t r = 0; r < N && straddle.size() < 64; ++r) { - const uint64_t a = HEADER + (uint64_t) r * rb; - if (a / 4096 != (a + rb - 1) / 4096) straddle.push_back(r); - } - check_rows(rd, straddle, N, rb, "straddle"); - // duplicates, neighbours on one page, the first and last rows, and out-of-range rows - check_rows(rd, {5, 5, 6, 7, 5, 0, N - 1, N, 0xFFFFFFFFu, 44, 45}, N, rb, "dedup/edges"); - // a prefill-shaped ticket much larger than the in-flight window - std::vector bulk(20000); - for (auto& r : bulk) r = rng() % N; - check_rows(rd, bulk, N, rb, "bulk"); - // two tickets in flight at once, collected in reverse order - std::vector a(16), b(16); - for (auto& r : a) r = rng() % N; - for (auto& r : b) r = rng() % N; - std::vector oa(16 * rb), ob(16 * rb); - const auto ta = rd.issue(a.data(), 16, oa.data()); - const auto tb = rd.issue(b.data(), 16, ob.data()); - CHECK(rd.collect(tb, err) && rd.collect(ta, err), "two tickets: %s", err.c_str()); - std::vector want(rb); - for (int i = 0; i < 16; ++i) { - expected_row(a[i], rb, want.data()); - CHECK(!std::memcmp(want.data(), &oa[i * rb], rb), "ticket a row %d", i); - expected_row(b[i], rb, want.data()); - CHECK(!std::memcmp(want.data(), &ob[i * rb], rb), "ticket b row %d", i); - } - if (cache > 0) CHECK(rd.stats().cache_hits > 0, "the row cache never hit"); - CHECK(rd.cache_size() <= rd.cache_capacity(), "row cache exceeded its bound"); - } - } - // fault injection: a 3 ms delay must be observed, and must not change the bytes - for (bool thr : {false, true}) { - ng::PleReader rd; - std::string err; - CHECK(rd.open(path, HEADER, N, 16, 0, err, thr, rb), "open: %s", err.c_str()); - rd.set_injected_delay_us(3000); - std::vector rows(16); - for (auto& r : rows) r = rng() % N; - const double t0 = now_us(); - check_rows(rd, rows, N, rb, "delayed"); - CHECK(now_us() - t0 >= 3000, "injected delay not observed (%.0f us)", now_us() - t0); - CHECK(rd.stats().late_injected > 0, "no read was held back"); - } - // keep-alive: while rows are asked for, a page goes out after `period` without a read; it stops once the - // window after the last issue has passed, starts again with the next issue (even one the row cache serves), - // and never shows up as a row read or changes a row - { - ng::PleReader rd; - std::string err; - CHECK(rd.open(path, HEADER, N, 16, 4096, err, true, rb), "open: %s", err.c_str()); - rd.set_keepalive(20.0, 0.5); - std::vector rows(16); - for (auto& r : rows) r = rng() % N; - check_rows(rd, rows, N, rb, "keep-alive, first ticket"); - const uint64_t reads0 = rd.snapshot().reads; - const auto nap = [](int ms) { std::this_thread::sleep_for(std::chrono::milliseconds(ms)); }; - nap(300); - const uint64_t k1 = rd.snapshot().keepalive_reads; - CHECK(k1 >= 8 && k1 <= 20, "keep-alive: %llu reads in 300 ms at a 20 ms period", (unsigned long long) k1); - CHECK(rd.snapshot().reads == reads0, "keep-alive reads were counted as row reads"); - nap(600); // the 0.5 s window has passed - const uint64_t k2 = rd.snapshot().keepalive_reads; - nap(300); - const uint64_t k3 = rd.snapshot().keepalive_reads; - CHECK(k3 == k2, "keep-alive went on after the window (%llu -> %llu)", (unsigned long long) k2, - (unsigned long long) k3); - CHECK(k2 <= k1 + 20, "keep-alive: %llu reads by the end of a 0.5 s window", (unsigned long long) k2); - check_rows(rd, rows, N, rb, "keep-alive, cached ticket"); // the row cache serves all 16: no row read - CHECK(rd.snapshot().reads == reads0, "cached rows were read again"); - nap(200); - CHECK(rd.snapshot().keepalive_reads >= k3 + 5, "the keep-alive did not start again (%llu -> %llu)", - (unsigned long long) k3, (unsigned long long) rd.snapshot().keepalive_reads); - std::vector more(2000); - for (auto& r : more) r = rng() % N; - check_rows(rd, more, N, rb, "keep-alive, rows afterwards"); - rd.set_keepalive(0, 0.5); // off - const uint64_t k4 = rd.snapshot().keepalive_reads; - nap(200); - CHECK(rd.snapshot().keepalive_reads <= k4 + 1, "keep-alive went on after it was turned off"); - rd.reset_stats(); - CHECK(rd.snapshot().keepalive_reads == 0 && rd.snapshot().keepalive_us_max == 0, "reset_stats kept keep-alive counts"); - } - { // the caller's thread does the reads: no worker, so no keep-alive - ng::PleReader rd; - std::string err; - CHECK(rd.open(path, HEADER, N, 16, 0, err, false, rb), "open: %s", err.c_str()); - rd.set_keepalive(20.0, 1.0); - std::vector rows(16); - for (auto& r : rows) r = rng() % N; - check_rows(rd, rows, N, rb, "keep-alive, caller thread"); - std::this_thread::sleep_for(std::chrono::milliseconds(150)); - CHECK(rd.snapshot().keepalive_reads == 0, "keep-alive without the worker thread"); - } - std::filesystem::remove(path); - std::printf("ple_reader selftest (row_bytes=%u): %s\n", rb, g_fail ? "FAILED" : "OK"); - return g_fail ? 1 : 0; -} - -int real(const std::string& gguf, int n_random, const std::string& tokens_path, uint32_t inflight, bool direct_first, - bool direct_only, bool sync_submit) { - k::PleTable mm, direct; - std::string err; - k::PleIoOptions mo; - mo.mode = k::PleIo::Mmap; - k::PleIoOptions dopt; - dopt.cache_rows = 0; // measure the SSD, not the cache - dopt.max_inflight = inflight; - dopt.io_thread = !sync_submit; - // `--direct-only` measures the direct path with NO mapping of the file alive anywhere in the process: a - // live section on the same file forces the file system to keep cached and non-cached views coherent. - if (!direct_only && !mm.open(gguf, err, mo)) { std::fprintf(stderr, "mmap open: %s\n", err.c_str()); return 2; } - if (!direct.open(gguf, err, dopt)) { std::fprintf(stderr, "direct open: %s\n", err.c_str()); return 2; } - std::vector> tickets; - std::mt19937_64 rng(11); - for (int t = 0; t < n_random / 16; ++t) { - std::vector r(16); - for (auto& x : r) x = (uint32_t) (rng() % direct.rows()); - tickets.push_back(r); - } - if (!tokens_path.empty()) { - std::ifstream f(tokens_path); - std::string text((std::istreambuf_iterator(f)), std::istreambuf_iterator()); - for (char& c : text) if (c == ',') c = ' '; - std::istringstream in(text); - std::vector ids; - for (int32_t v; in >> v;) ids.push_back(v); - const k::PleConsts C = k::ple_artifact_consts(); - for (size_t i = 0; i < ids.size(); ++i) { - const int32_t prev[2] = {i >= 2 ? ids[i - 2] : k::TOKEN_NULL, i >= 1 ? ids[i - 1] : k::TOKEN_NULL}; - std::vector r(16); - k::ngram_rows(&ids[i], prev, 1, C, r.data()); - tickets.push_back(r); - } - } - std::vector a(k::NG_N_EMBD), b(k::NG_N_EMBD); - double t_mm = 0, t_dir = 0, t_issue = 0; - for (const auto& r : tickets) { - for (int pass = 0; pass < 2; ++pass) { - const bool do_direct = (pass == 0) == direct_first; - const double t0 = now_us(); - if (!do_direct) { - if (direct_only) continue; - mm.gather(r.data(), a.data()); - t_mm += now_us() - t0; - } else { - const double ti = now_us(); - const bool issued = direct.issue(r.data()); - t_issue += now_us() - ti; - if (!issued || !direct.collect(b.data(), err)) { - std::fprintf(stderr, "direct: %s\n", err.c_str()); - return 1; - } - t_dir += now_us() - t0; - } - } - if (!direct_only) - CHECK(!std::memcmp(a.data(), b.data(), a.size() * sizeof(float)), "token rows differ between mmap and direct"); - } - std::printf("tokens %zu: mmap %.1f us/token, direct %.1f us/token (issue on this thread %.1f us)\n%s\n", - tickets.size(), t_mm / (double) tickets.size(), t_dir / (double) tickets.size(), - t_issue / (double) tickets.size(), direct.io_report().c_str()); - std::printf("ple_reader real-table check: %s\n", g_fail ? "FAILED" : "OK (bit-identical)"); - return g_fail ? 1 : 0; -} - -} // namespace - -int main(int argc, char** argv) { - std::string gguf, dir = std::filesystem::temp_directory_path().string(), tokens; - int rows = 20000; - uint32_t inflight = 64; - bool direct_first = false; - bool direct_only = false; - bool sync_submit = false; - bool self = false; - for (int i = 1; i < argc; ++i) { - const std::string a = argv[i]; - if (a == "--selftest") self = true; - else if (a == "--dir" && i + 1 < argc) dir = argv[++i]; - else if (a == "--gguf" && i + 1 < argc) gguf = argv[++i]; - else if (a == "--rows" && i + 1 < argc) rows = std::atoi(argv[++i]); - else if (a == "--tokens" && i + 1 < argc) tokens = argv[++i]; - else if (a == "--inflight" && i + 1 < argc) inflight = (uint32_t) std::atoi(argv[++i]); - else if (a == "--direct-first") direct_first = true; - else if (a == "--direct-only") direct_only = true; - else if (a == "--sync") sync_submit = true; - else { std::fprintf(stderr, "usage: ple_reader_test --selftest [--dir D] | --gguf SHARD2 [--rows N] [--tokens F]\n"); return 2; } - } - if (self) { - // ng::ROW_BYTES (90, IQ4_NL, production default) and 110 (#296, OrcaRouter's Q5_0 PLE rows) through the - // same generic row_bytes path -- see the comment on selftest(). - const int r90 = selftest(dir, ng::ROW_BYTES); - const int r110 = selftest(dir, 110); - return r90 != 0 ? r90 : r110; - } - if (!gguf.empty()) return real(gguf, rows, tokens, inflight, direct_first, direct_only, sync_submit); - std::fprintf(stderr, "nothing to do\n"); - return 2; -} diff --git a/src/plan/plan_main.cpp b/src/plan/plan_main.cpp deleted file mode 100644 index 5cf1fda..0000000 --- a/src/plan/plan_main.cpp +++ /dev/null @@ -1,73 +0,0 @@ -// src/plan/plan_main.cpp - the `strata-plan` CLI: print the memory plan, or say why it does not close. -// -// The engine must adapt to the GPU it is running on, so the plan is computed from measured free VRAM and the -// requested context rather than configured by hand. This tool is that computation on its own, which is what -// makes it testable without a GPU. -#include "strata/plan/plan.hpp" - -#include -#include -#include -#include - -int main(int argc, char** argv) { - uint64_t ctx = 20480; - uint64_t free_vram = 12ull * 1000 * 1000 * 1000; // RTX 5070 nominal; overridden by --vram - strata::plan::Costs costs; - bool state_given = false; - for (int i = 1; i < argc; ++i) { - const std::string a = argv[i]; - auto next = [&](uint64_t& out) { - if (i + 1 >= argc) { - std::fprintf(stderr, "%s needs a value\n", a.c_str()); - std::exit(2); - } - out = std::strtoull(argv[++i], nullptr, 10); - }; - if (a == "--max-context") - next(ctx); - else if (a == "--vram") - next(free_vram); - else if (a == "--dense") - next(costs.dense_bytes); - else if (a == "--embd") - next(costs.embd_bytes); - else if (a == "--workspace") - next(costs.workspace_bytes); - else if (a == "--state") { - next(costs.state_bytes); - state_given = true; - } else if (a == "--pool") { - uint64_t v = 0; - next(v); - free_vram = v; - } else if (a == "--help" || a == "-h") { - std::printf("usage: strata-plan [--max-context N] [--vram BYTES] [--dense B] [--embd B]\n" - " [--workspace B] [--state B] [--pool B]\n" - " --state defaults to the geometry's own GDN recurrence + conv history, NOT to 0:\n" - " the flag used to default to zero and nothing passed it, so the planner silently\n" - " planned without 117.7 MB (85 expert slots) of non-evictable state.\n"); - return 0; - } else { - std::fprintf(stderr, "unknown argument: %s\n", a.c_str()); - return 2; - } - } - // DEFAULT THE STATE FROM THE GEOMETRY. A `--state` that defaults to 0 and is never passed is not a - // default, it is an omission - and this one was worth 85 cache slots of overcommit. - if (!state_given) costs.state_bytes = strata::plan::state_bytes(strata::plan::Geometry{}); - // The pool is what the KV cache and the expert cache share. Derived from the card's free VRAM less the - // resident dense weights; `--pool` overrides it for reproducing the standard-tier numbers exactly. - const uint64_t pool = free_vram > costs.dense_bytes + costs.embd_bytes - ? free_vram - costs.dense_bytes - costs.embd_bytes - : 0; - try { - const strata::plan::Plan p = strata::plan::make_plan(ctx, strata::plan::Geometry{}, costs, - pool ? pool : strata::plan::vram_pool_bytes()); - std::printf("%s", strata::plan::to_string(p).c_str()); - return 0; - } catch (const strata::plan::DoesNotClose& e) { - std::fprintf(stderr, "strata-plan: %s\n", e.what()); - return 1; - } -} diff --git a/src/platform/direct_file.cpp b/src/platform/direct_file.cpp deleted file mode 100644 index cd4f6a7..0000000 --- a/src/platform/direct_file.cpp +++ /dev/null @@ -1,365 +0,0 @@ -// src/platform/direct_file.cpp - see include/strata/platform/direct_file.hpp. -#include "strata/platform/direct_file.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(_WIN32) -#define WIN32_LEAN_AND_MEAN -#define NOMINMAX -#include -#else -#include -#include -#include -#endif - -namespace strata::platform { - -double now_us() { - using namespace std::chrono; - return (double) duration_cast(steady_clock::now().time_since_epoch()).count() / 1000.0; -} - -void* DirectFile::alloc_aligned(size_t bytes) { -#if defined(_WIN32) - return VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); -#else - void* p = nullptr; - return posix_memalign(&p, alignment(), bytes) == 0 ? p : nullptr; -#endif -} - -void DirectFile::free_aligned(void* p) { - if (p == nullptr) return; -#if defined(_WIN32) - VirtualFree(p, 0, MEM_RELEASE); -#else - std::free(p); -#endif -} - -namespace { -/// A queued read: `submit` only queues it; the pool's threads issue it (perf-review C-4 / F-2). One thread -/// issuing every read was the limit of the n-gram table's prompt reads: ~12 us of kernel time per read, ~80K -/// reads/s, while an NVMe drive serves several times that at depth. -struct Pending { - uint64_t offset; - void* buffer; - uint32_t length; - uint64_t tag; -}; - -/// The number of issuing threads: STRATA_IO_THREADS, else 4 (Windows: overlapped submits) / 16 (Linux: each -/// thread does one blocking pread, so the thread count is the queue depth). -int io_threads(int dflt) { - const char* v = std::getenv("STRATA_IO_THREADS"); - const int n = v ? std::atoi(v) : dflt; - return std::clamp(n, 1, 64); -} -} // namespace - -#if defined(_WIN32) -// ------------------------------------------------------------------------------------------------ Windows -namespace { -/// One in-flight request. The OVERLAPPED must be the first member so a completion packet's OVERLAPPED* -/// converts back to the request. -struct Req { - OVERLAPPED ov; - uint64_t tag; -}; -} // namespace - -struct DirectFile::Impl { - HANDLE file = INVALID_HANDLE_VALUE; - HANDLE port = nullptr; - uint64_t size = 0; - std::mutex mu; // everything below - std::deque free_reqs; - std::vector all_reqs; - std::deque immediate; // requests that completed without a port packet (EOF) or failed - std::deque queue; // submitted, not yet issued - std::condition_variable cv; - bool stop = false; - std::vector pool; - - Req* take() { - if (free_reqs.empty()) { - Req* r = new Req(); - all_reqs.push_back(r); - return r; - } - Req* r = free_reqs.front(); - free_reqs.pop_front(); - return r; - } - - void issue(const Pending& p) { - Req* r; - { - std::lock_guard lk(mu); - r = take(); - } - std::memset(&r->ov, 0, sizeof r->ov); - r->ov.Offset = (DWORD) (p.offset & 0xFFFFFFFFull); - r->ov.OffsetHigh = (DWORD) (p.offset >> 32); - r->tag = p.tag; - if (!ReadFile(file, p.buffer, p.length, nullptr, &r->ov)) { - const DWORD e = GetLastError(); - if (e != ERROR_IO_PENDING) { - std::lock_guard lk(mu); - free_reqs.push_back(r); - // at or past end of file: a zero-byte completion; anything else: a failed one - immediate.push_back(Completion{p.tag, 0, e == ERROR_HANDLE_EOF}); - PostQueuedCompletionStatus(port, 0, 0, nullptr); // wake a waiter to collect it - } - } - } - - void worker() { - std::unique_lock lk(mu); - for (;;) { - cv.wait(lk, [&] { return stop || !queue.empty(); }); - if (stop && queue.empty()) return; - const Pending p = queue.front(); - queue.pop_front(); - lk.unlock(); - issue(p); - lk.lock(); - } - } - - void stop_pool() { - { - std::lock_guard lk(mu); - stop = true; - } - cv.notify_all(); - for (std::thread& t : pool) t.join(); - pool.clear(); - stop = false; - } -}; - -DirectFile::DirectFile() : impl_(new Impl) {} -DirectFile::~DirectFile() { - close(); - for (Req* r : impl_->all_reqs) delete r; - delete impl_; -} - -bool DirectFile::open(const std::string& path, std::string& err) { - close(); - const int wlen = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0); - std::wstring wpath((size_t) (wlen > 0 ? wlen : 1), L'\0'); - MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wlen); - // NO_BUFFERING: the cache manager never holds these pages, so the table cannot grow into RAM. - // RANDOM_ACCESS: no read-ahead. OVERLAPPED: many reads in flight, completed through the port below. - impl_->file = CreateFileW(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, - FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED | FILE_FLAG_RANDOM_ACCESS, nullptr); - if (impl_->file == INVALID_HANDLE_VALUE) { - err = "DirectFile: cannot open " + path + " (error " + std::to_string(GetLastError()) + ")"; - return false; - } - LARGE_INTEGER sz; - if (!GetFileSizeEx(impl_->file, &sz)) { - err = "DirectFile: cannot size " + path; - close(); - return false; - } - impl_->size = (uint64_t) sz.QuadPart; - impl_->port = CreateIoCompletionPort(impl_->file, nullptr, 0, 1); - if (impl_->port == nullptr) { - err = "DirectFile: CreateIoCompletionPort failed (error " + std::to_string(GetLastError()) + ")"; - close(); - return false; - } - // Completions of reads that finish synchronously are still queued to the port, so every issued read - // produces exactly one packet; `wait` is the only completion path. - const int n = io_threads(4); - for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { impl_->worker(); }); - return true; -} - -void DirectFile::close() { - impl_->stop_pool(); - if (impl_->port != nullptr) CloseHandle(impl_->port); - if (impl_->file != INVALID_HANDLE_VALUE) CloseHandle(impl_->file); - impl_->port = nullptr; - impl_->file = INVALID_HANDLE_VALUE; - impl_->size = 0; - impl_->immediate.clear(); - impl_->queue.clear(); -} - -bool DirectFile::is_open() const { return impl_->file != INVALID_HANDLE_VALUE; } -uint64_t DirectFile::size() const { return impl_->size; } - -bool DirectFile::submit(uint64_t offset, void* buffer, uint32_t length, uint64_t tag, std::string& err) { - if (!is_open()) { err = "DirectFile: not open"; return false; } - if (offset % alignment() || length % alignment() || ((uintptr_t) buffer) % alignment() || length == 0) { - err = "DirectFile: unaligned request"; - return false; - } - { - std::lock_guard lk(impl_->mu); - impl_->queue.push_back(Pending{offset, buffer, length, tag}); - } - impl_->cv.notify_one(); - return true; -} - -int DirectFile::wait(Completion* out, int max, int timeout_ms) { - int n = 0; - { - std::lock_guard lk(impl_->mu); - while (n < max && !impl_->immediate.empty()) { - out[n++] = impl_->immediate.front(); - impl_->immediate.pop_front(); - } - } - if (n == max || !is_open()) return n; - OVERLAPPED_ENTRY entries[64]; - const ULONG want = (ULONG) (max - n < 64 ? max - n : 64); - ULONG got = 0; - const DWORD t = timeout_ms < 0 ? INFINITE : (DWORD) timeout_ms; - if (!GetQueuedCompletionStatusEx(impl_->port, entries, want, &got, n > 0 ? 0 : t, FALSE)) return n; - std::lock_guard lk(impl_->mu); - for (ULONG i = 0; i < got; ++i) { - if (entries[i].lpOverlapped == nullptr) { // a wake() packet (or an immediate completion's nudge) - while (n < max && !impl_->immediate.empty()) { - out[n++] = impl_->immediate.front(); - impl_->immediate.pop_front(); - } - if (n < max) out[n++] = Completion{WAKE_TAG, 0, true}; - continue; - } - Req* r = (Req*) entries[i].lpOverlapped; - const uint32_t status = (uint32_t) r->ov.Internal; // an NTSTATUS - Completion c; - c.tag = r->tag; - c.bytes = entries[i].dwNumberOfBytesTransferred; - // STATUS_END_OF_FILE (0xC0000011) is a legal short read at the table's last page. - c.ok = status == 0 || status == 0xC0000011u; - out[n++] = c; - impl_->free_reqs.push_back(r); - } - return n; -} - -void DirectFile::wake() { - if (impl_->port != nullptr) PostQueuedCompletionStatus(impl_->port, 0, 0, nullptr); -} - -#else -// ------------------------------------------------------------------------------------------------ POSIX -// perf-review F-2: a pool of threads, each doing blocking O_DIRECT preads, so reads run in parallel (the thread -// count is the queue depth). It replaced one synchronous pread inside `submit`, which read the n-gram table's -// rows one at a time. -struct DirectFile::Impl { - int fd = -1; - uint64_t size = 0; - std::mutex mu; - std::condition_variable cv_work, cv_done; - std::deque queue; - std::deque done; - bool stop = false; - std::vector pool; - - void worker() { - std::unique_lock lk(mu); - for (;;) { - cv_work.wait(lk, [&] { return stop || !queue.empty(); }); - if (stop && queue.empty()) return; - const Pending p = queue.front(); - queue.pop_front(); - lk.unlock(); - const ssize_t got = pread(fd, p.buffer, p.length, (off_t) p.offset); - lk.lock(); - done.push_back(Completion{p.tag, got < 0 ? 0u : (uint32_t) got, got >= 0}); - cv_done.notify_all(); - } - } - - void stop_pool() { - { - std::lock_guard lk(mu); - stop = true; - } - cv_work.notify_all(); - for (std::thread& t : pool) t.join(); - pool.clear(); - stop = false; - } -}; - -DirectFile::DirectFile() : impl_(new Impl) {} -DirectFile::~DirectFile() { close(); delete impl_; } - -bool DirectFile::open(const std::string& path, std::string& err) { - close(); - impl_->fd = ::open(path.c_str(), O_RDONLY | O_DIRECT); - if (impl_->fd < 0) { err = "DirectFile: cannot open " + path; return false; } - struct stat st; - if (fstat(impl_->fd, &st) != 0) { err = "DirectFile: cannot size " + path; close(); return false; } - impl_->size = (uint64_t) st.st_size; - const int n = io_threads(16); - for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { impl_->worker(); }); - return true; -} - -void DirectFile::close() { - impl_->stop_pool(); - if (impl_->fd >= 0) ::close(impl_->fd); - impl_->fd = -1; - impl_->size = 0; - impl_->done.clear(); - impl_->queue.clear(); -} - -bool DirectFile::is_open() const { return impl_->fd >= 0; } -uint64_t DirectFile::size() const { return impl_->size; } - -bool DirectFile::submit(uint64_t offset, void* buffer, uint32_t length, uint64_t tag, std::string& err) { - if (offset % alignment() || length % alignment() || ((uintptr_t) buffer) % alignment() || length == 0) { - err = "DirectFile: unaligned request"; - return false; - } - { - std::lock_guard lk(impl_->mu); - impl_->queue.push_back(Pending{offset, buffer, length, tag}); - } - impl_->cv_work.notify_one(); - return true; -} - -void DirectFile::wake() { - std::lock_guard lk(impl_->mu); - impl_->done.push_back(Completion{WAKE_TAG, 0, true}); - impl_->cv_done.notify_all(); -} - -int DirectFile::wait(Completion* out, int max, int timeout_ms) { - std::unique_lock lk(impl_->mu); - if (impl_->done.empty() && timeout_ms != 0) { - auto ready = [&] { return !impl_->done.empty(); }; - if (timeout_ms < 0) impl_->cv_done.wait(lk, ready); - else impl_->cv_done.wait_for(lk, std::chrono::milliseconds(timeout_ms), ready); - } - int n = 0; - while (n < max && !impl_->done.empty()) { - out[n++] = impl_->done.front(); - impl_->done.pop_front(); - } - return n; -} -#endif - -} // namespace strata::platform diff --git a/src/platform/memory.cpp b/src/platform/memory.cpp deleted file mode 100644 index f3b40e8..0000000 --- a/src/platform/memory.cpp +++ /dev/null @@ -1,138 +0,0 @@ -// src/platform/memory.cpp - see include/strata/platform/memory.hpp. -#include "strata/platform/memory.hpp" - -#if defined(_WIN32) -#define WIN32_LEAN_AND_MEAN -#define NOMINMAX -#include -#include -#include -#else -#include -#include -#endif - -namespace strata::platform { - -#if defined(_WIN32) -LockResult lock_resident(void* p, uint64_t bytes) { - LockResult r; - if (p == nullptr || bytes == 0) { r.note = "nothing to lock"; return r; } - HANDLE self = GetCurrentProcess(); - SIZE_T min_ws = 0, max_ws = 0; - DWORD flags = 0; - if (!GetProcessWorkingSetSizeEx(self, &min_ws, &max_ws, &flags)) { - r.note = "GetProcessWorkingSetSizeEx failed (error " + std::to_string(GetLastError()) + ")"; - return r; - } - // Locked pages count against the minimum working set, so it must grow by the region plus headroom for the - // rest of the process. Soft limits: the maximum is not enforced, only the minimum is raised. - const SIZE_T margin = (SIZE_T) 512 << 20; - const SIZE_T new_min = min_ws + (SIZE_T) bytes + margin; - const SIZE_T new_max = max_ws > new_min + margin ? max_ws : new_min + margin; - if (!SetProcessWorkingSetSizeEx(self, new_min, new_max, - QUOTA_LIMITS_HARDWS_MIN_DISABLE | QUOTA_LIMITS_HARDWS_MAX_DISABLE)) { - r.note = "SetProcessWorkingSetSizeEx(" + std::to_string((unsigned long long) (new_min >> 20)) + - " MiB) failed (error " + std::to_string(GetLastError()) + ")"; - return r; - } - const uint64_t chunk = 1ull << 30; - uint8_t* base = (uint8_t*) p; - for (uint64_t off = 0; off < bytes; off += chunk) { - const uint64_t n = bytes - off < chunk ? bytes - off : chunk; - if (!VirtualLock(base + off, (SIZE_T) n)) { - r.note = "VirtualLock stopped at " + std::to_string((unsigned long long) (off >> 20)) + " of " + - std::to_string((unsigned long long) (bytes >> 20)) + " MiB (error " + - std::to_string(GetLastError()) + ")"; - r.ok = off > 0; - return r; - } - r.locked_bytes = off + n; - } - r.ok = true; - r.note = "locked " + std::to_string((unsigned long long) (bytes >> 20)) + " MiB via working-set minimum + VirtualLock"; - return r; -} - -void unlock_resident(void* p, uint64_t bytes) { - if (p == nullptr || bytes == 0) return; - const uint64_t chunk = 1ull << 30; - for (uint64_t off = 0; off < bytes; off += chunk) - VirtualUnlock((uint8_t*) p + off, (SIZE_T) (bytes - off < chunk ? bytes - off : chunk)); -} - -bool gpu_shared_memory_budget(const void* luid, uint64_t& budget, uint64_t& usage, std::string& why) { - budget = usage = 0; - // dxgi.dll is loaded when asked, not linked: a start that never needs this keeps the imports it had - HMODULE dxgi = LoadLibraryA("dxgi.dll"); - if (dxgi == nullptr) { why = "dxgi.dll not found"; return false; } - using CreateFactory = HRESULT(WINAPI*)(REFIID, void**); - const auto create = (CreateFactory) (void*) GetProcAddress(dxgi, "CreateDXGIFactory1"); - IDXGIFactory1* factory = nullptr; - if (create == nullptr || FAILED(create(__uuidof(IDXGIFactory1), (void**) &factory)) || factory == nullptr) { - why = "CreateDXGIFactory1 failed"; - FreeLibrary(dxgi); - return false; - } - bool ok = false; - why = "no DXGI adapter has the CUDA device's LUID"; - for (UINT i = 0; !ok; ++i) { - IDXGIAdapter1* a = nullptr; - if (factory->EnumAdapters1(i, &a) == DXGI_ERROR_NOT_FOUND || a == nullptr) break; - DXGI_ADAPTER_DESC1 d{}; - if (SUCCEEDED(a->GetDesc1(&d)) && std::memcmp(&d.AdapterLuid, luid, sizeof d.AdapterLuid) == 0) { - IDXGIAdapter3* a3 = nullptr; - DXGI_QUERY_VIDEO_MEMORY_INFO info{}; - if (SUCCEEDED(a->QueryInterface(__uuidof(IDXGIAdapter3), (void**) &a3)) && a3 != nullptr && - SUCCEEDED(a3->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &info))) { - budget = info.Budget; - usage = info.CurrentUsage; - ok = budget > 0; - why = ok ? "" : "the adapter reports no shared-memory budget"; - } else { - why = "QueryVideoMemoryInfo failed"; - } - if (a3 != nullptr) a3->Release(); - a->Release(); - break; - } - a->Release(); - } - factory->Release(); - FreeLibrary(dxgi); - return ok; -} - -uint64_t total_physical_memory() { - MEMORYSTATUSEX ms{}; - ms.dwLength = sizeof ms; - return GlobalMemoryStatusEx(&ms) ? (uint64_t) ms.ullTotalPhys : 0; -} -#else -LockResult lock_resident(void* p, uint64_t bytes) { - LockResult r; - if (p == nullptr || bytes == 0) { r.note = "nothing to lock"; return r; } - if (mlock(p, bytes) != 0) { r.note = "mlock failed (raise ulimit -l)"; return r; } - r.ok = true; - r.locked_bytes = bytes; - r.note = "mlock"; - return r; -} - -void unlock_resident(void* p, uint64_t bytes) { - if (p != nullptr && bytes != 0) munlock(p, bytes); -} - -bool gpu_shared_memory_budget(const void*, uint64_t& budget, uint64_t& usage, std::string& why) { - budget = usage = 0; - why = "DXGI is Windows-only"; - return false; -} - -uint64_t total_physical_memory() { - const long pages = sysconf(_SC_PHYS_PAGES), page = sysconf(_SC_PAGE_SIZE); - return pages > 0 && page > 0 ? (uint64_t) pages * (uint64_t) page : 0; -} -#endif - -} // namespace strata::platform diff --git a/src/platform/memory_test.cpp b/src/platform/memory_test.cpp deleted file mode 100644 index 7346189..0000000 --- a/src/platform/memory_test.cpp +++ /dev/null @@ -1,72 +0,0 @@ -// src/platform/memory_test.cpp - plan v0.3 P0.1: lock_resident on a 256 MiB region (CPU only, no GPU, no model). -#include "strata/platform/memory.hpp" - -#include -#include -#include - -#if defined(_WIN32) -#define WIN32_LEAN_AND_MEAN -#define NOMINMAX -#include -#include -#pragma comment(lib, "psapi.lib") -#endif - -namespace { -uint64_t gib(double g) { return (uint64_t) (g * 1073741824.0); } - -// #577: the file tier's unbuffered choice (true = the file cache keeps its reads, so they stay buffered) -int file_cache_keeps_cases() { - using strata::platform::file_cache_keeps; - struct Case { const char* what; double avail, arena, read; bool keeps; }; - const double experts = 71.7; // UD-Q4_K_XL's routed experts - const Case cases[] = { - // the reporter's 96 GB PC (83.0 GiB available at start): 0.1.38 passed the budget asked for and every - // shard's bytes (103.7 GiB) and went unbuffered - {"96 GB, 0.1.38's inputs (budget 72, all shards)", 83.0, 72.0, 103.7, false}, - {"96 GB, budget 72, before the copy (arena = all experts)", 83.0, experts, 0.0, true}, - {"96 GB, budget 72, copy built (48.94 resident)", 83.0 - 48.94, 0.0, experts - 48.94, true}, - {"96 GB, budget 40, before the copy", 83.0, 40.0, experts - 40.0, true}, - {"96 GB, budget 40, copy built", 83.0 - 40.0, 0.0, experts - 40.0, true}, - // #357/#362's low-RAM PCs stay unbuffered - {"64 GB, budget 40, before the copy", 55.0, 40.0, experts - 40.0, false}, - {"64 GB, budget 40, copy built", 15.0, 0.0, experts - 40.0, false}, - {"32 GB, budget 16, before the copy", 26.0, 16.0, experts - 16.0, false}, - {"32 GB, budget 16, copy built", 10.0, 0.0, experts - 16.0, false}, - {"32 GB, Q2_0 pack (34 GiB experts), budget 8", 26.0, 8.0, 34.0 - 8.0, false}, - {"nothing available", 0.0, 0.0, 1.0, false}, - {"arena larger than the RAM", 10.0, 20.0, 0.0, true}, - }; - int fail = 0; - for (const Case& c : cases) { - const bool got = file_cache_keeps(gib(c.avail), gib(c.arena), gib(c.read)); - std::printf("file_cache_keeps %-58s -> %s%s\n", c.what, got ? "buffered" : "unbuffered", - got == c.keeps ? "" : " <-- WRONG"); - fail |= got != c.keeps; - } - return fail; -} -} // namespace - -int main() { - int fail_keeps = file_cache_keeps_cases(); - const uint64_t bytes = 256ull << 20; - void* p = std::malloc(bytes); - if (p == nullptr) return 2; - std::memset(p, 1, bytes); - const strata::platform::LockResult r = strata::platform::lock_resident(p, bytes); - std::printf("lock_resident: ok=%d locked=%llu MiB (%s)\n", (int) r.ok, (unsigned long long) (r.locked_bytes >> 20), - r.note.c_str()); - int fail = !(r.ok && r.locked_bytes == bytes) | fail_keeps; -#if defined(_WIN32) - PROCESS_MEMORY_COUNTERS pmc{}; - GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof pmc); - std::printf("working set %llu MiB\n", (unsigned long long) (pmc.WorkingSetSize >> 20)); - fail |= pmc.WorkingSetSize < bytes; -#endif - strata::platform::unlock_resident(p, bytes); - std::free(p); - std::printf("platform_memory_test: %s\n", fail ? "FAILED" : "OK"); - return fail; -} diff --git a/src/prefill/gdn_rec_parity.cu b/src/prefill/gdn_rec_parity.cu deleted file mode 100644 index 3d9de8c..0000000 --- a/src/prefill/gdn_rec_parity.cu +++ /dev/null @@ -1,1094 +0,0 @@ -// 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 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, = <48, 16, 10240> (Flash-Next, -// 3 value heads per key head, the sigmoid(z) output gate) and <32, 16, 8192> (Qwen3.6, 2 per key head, SiLU(z)), and -// the engine's own launches (gdn_conv, gdn_recurrence through their GdnGeom) are held to a double-precision host -// transcription of the recurrence (docs/qwen36-port/oracle-crosscheck.md, "Gated DeltaNet": decay before the rank-1 -// update, v-head h paired with k-head h % HK, the gated RMS-normed output). Negative controls, in the repo's -// discipline (gdn_parity.cpp): each rival reading is computed with the same reference and must sit more than 5 % -// relative L1 from the right one before the kernel is judged - the sigmoid gate on the SiLU model, the interleaved -// head pairing (h // VPK) - and a geometry the kernels are not built for (a third value head per key head on 32 heads, -// i.e. Flash-Next's 48-head channel layout on Qwen3.6's heads) is refused by gdn_geometry_supported, not mis-indexed. -// -// Synthetic inputs of the model's shape (q/k L2-normalized per key head as gdn_l2_kernel leaves them), no model. -// gdn_rec_parity the bit checks (T from 1 to 4099, a non-zero state as after an earlier chunk), both -// geometries; the reference checks and the negative controls -// gdn_rec_parity --bench and the timings at T = 8192 and 32768 (one layer, all value heads, both geometries); -// the two variants' launches alternate, since a card under load steps its clock down -// after a fraction of a second (see native_grouped_parity); then (Flash-Next) both at 1 -// to 6 blocks per SM, as on cards with more or fewer SMs (scale), and both with the -// engine's grids on 32 to all of this card's SMs, the others held by a sleeping kernel -// (fewer_sms) -#include "strata/prefill/kernels.hpp" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { - -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) { - std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); - std::exit(2); - } -} - -__device__ __forceinline__ float warp_sum(float v) { -#pragma unroll - for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); - return v; -} -__device__ __forceinline__ float sigm(float x) { return 1.0f / (1.0f + __expf(-x)); } -__device__ __forceinline__ uint16_t hf(float f) { return __half_as_ushort(__float2half_rn(f)); } - -// ------------------------------------------------------------------ the engine's kernels (src/prefill/kernels.cu) -// 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 -__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, - float* __restrict__ oc_out, int64_t T) { - constexpr int NT = CB * RG, LPT = S / NT; // threads, q/k rows loaded per thread - __shared__ float sk[S], sq[S], red[RG][CB]; - const int head = blockIdx.x / NCB, cb = blockIdx.x % NCB; - const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c; - const int qh = head % HK; - float s[RPG]; - float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col; - const size_t rs = (size_t) HV * S; -#pragma unroll - for (int r = 0; r < RPG; ++r) s[r] = base[r * rs]; - float nq[LPT], nk[LPT], nv = 0.0f, ng = 0.0f, nb = 0.0f; - auto fetch = [&](int64_t t) { - const float* ht = h + t * C; -#pragma unroll - for (int u = 0; u < LPT; ++u) { nq[u] = ht[qh * S + tid + u * NT]; nk[u] = ht[HK * S + qh * S + tid + u * NT]; } - nv = ht[2 * HK * S + head * S + col]; - ng = gate[t * HV + head]; - nb = beta[t * HV + head]; - }; - if (T > 0) fetch(0); - for (int64_t t = 0; t < T; ++t) { - float cq[LPT], ck[LPT]; -#pragma unroll - for (int u = 0; u < LPT; ++u) { cq[u] = nq[u]; ck[u] = nk[u]; } - const float cv = nv, cg = ng, cbt = nb; - __syncthreads(); -#pragma unroll - for (int u = 0; u < LPT; ++u) { sq[tid + u * NT] = cq[u]; sk[tid + u * NT] = ck[u]; } - __syncthreads(); - if (t + 1 < T) fetch(t + 1); - const float g = __expf(cg); - float kv = 0.0f; -#pragma unroll - for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); - red[rg][c] = kv; - __syncthreads(); - const float kv_col = red[0][c] + red[1][c] + red[2][c] + red[3][c]; - const float delta = (cv - g * kv_col) * cbt; - float o = 0.0f; -#pragma unroll - for (int r = 0; r < RPG; ++r) { - s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); - o = fmaf(s[r], sq[rg * RPG + r], o); - } - __syncthreads(); - red[rg][c] = o; - __syncthreads(); - if (rg == 0) oc_out[t * HV * S + head * S + col] = (red[0][c] + red[1][c] + red[2][c] + red[3][c]) * rsqrtf((float) S); - } -#pragma unroll - for (int r = 0; r < RPG; ++r) base[r * rs] = s[r]; -} -// The recurrence with one thread for the three value heads that share a key head (head % HK): column c of heads -// qh, qh + 16 and qh + 32, row group rg. gdn_rec_cols_pipe_kernel spends its time in shared memory, not in -// arithmetic: every thread of a warp needs the same 32 q and k values per token (the k twice), and a warp receives one -// such broadcast value per clock however wide the load. Here every q/k value a thread loads feeds three heads, and a -// token's k row goes into registers once for both of its uses. The inputs come in blocks of GDN_TB tokens, copied to -// shared memory by cp.async while the block before computes (one token ahead is shorter than a load from L2 takes), -// and the two cross-row-group sums have their own arrays, so a token needs 2 __syncthreads instead of 5: the second -// one of a token orders every read of rkv before the next token's writes, the next token's first one every read of ro -// before the writes after it. 64 blocks instead of 192. Per value head and column the same arithmetic in the same -// order: the same bits (src/prefill/gdn_rec_parity.cu checks them and times the variants: 1.41x on a 4080 Super). -// sm_80+ (gdn_keyhead_ok); STRATA_GDN_KEYHEAD=0: gdn_rec_cols_pipe_kernel. -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800 -#define STRATA_GDN_CP_ASYNC 0 // Turing builds: plain copies (never launched there, see gdn_keyhead_ok) -#else -#define STRATA_GDN_CP_ASYNC 1 -#endif -__device__ __forceinline__ void gdn_cp4(float* smem, const float* gmem) { -#if STRATA_GDN_CP_ASYNC - asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem)); -#else - *smem = *gmem; -#endif -} -__device__ __forceinline__ void gdn_cp16(float* smem, const float* gmem) { -#if STRATA_GDN_CP_ASYNC - asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem)); -#else - *reinterpret_cast(smem) = *reinterpret_cast(gmem); -#endif -} -__device__ __forceinline__ void gdn_cp_commit() { -#if STRATA_GDN_CP_ASYNC - asm volatile("cp.async.commit_group;\n" ::); -#endif -} -__device__ __forceinline__ void gdn_cp_wait_prev() { // every group but the newest has landed -#if STRATA_GDN_CP_ASYNC - asm volatile("cp.async.wait_group 1;\n" ::); -#endif -} -constexpr int GDN_TB = 8; // tokens per staged block -template -__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]; - __shared__ __align__(16) float sv[2][TB][VPK][CB]; - __shared__ float sg[2][TB][VPK], sb[2][TB][VPK], rkv[VPK][RG][CB], ro[VPK][RG][CB]; - const int qh = blockIdx.x / NCB, cb = blockIdx.x % NCB; - const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c; - float s[VPK][RPG]; - const size_t rs = (size_t) HV * S; -#pragma unroll - for (int j = 0; j < VPK; ++j) { - const float* base = state + ((size_t) (rg * RPG) * HV + qh + j * HK) * S + col; -#pragma unroll - for (int r = 0; r < RPG; ++r) s[j][r] = base[r * rs]; - } - const int64_t nblk = (T + TB - 1) / TB; - auto stage = [&](int64_t k) { // tokens [k * TB, k * TB + TB) into buffer k & 1 - const int bb = (int) (k & 1); - const int64_t t0 = k * TB; - for (int p = tid; p < TB * 2 * QKP; p += NT) { - const int i = p / (2 * QKP), w = p % (2 * QKP), isk = w / QKP, jj = (w % QKP) * 4; - if (t0 + i < T) - gdn_cp16(isk ? &sk[bb][i][jj] : &sq[bb][i][jj], h + (t0 + i) * C + (isk ? HK * S : 0) + qh * S + jj); - } - for (int p = tid; p < TB * VPK * VP; p += NT) { - const int i = p / (VPK * VP), w = p % (VPK * VP), j = w / VP, jj = (w % VP) * 4; - if (t0 + i < T) - gdn_cp16(&sv[bb][i][j][jj], h + (t0 + i) * C + 2 * HK * S + (qh + j * HK) * S + cb * CB + jj); - } - for (int p = tid; p < 2 * TB * VPK; p += NT) { - const int isb = p / (TB * VPK), w = p % (TB * VPK), i = w / VPK, j = w % VPK; - if (t0 + i < T) - gdn_cp4(isb ? &sb[bb][i][j] : &sg[bb][i][j], (isb ? beta : gate) + (t0 + i) * HV + qh + j * HK); - } - }; - if (nblk > 0) stage(0); - gdn_cp_commit(); - for (int64_t k = 0; k < nblk; ++k) { - // buffer (k + 1) & 1 was read by block k - 1, whose last token's second __syncthreads every thread has passed - if (k + 1 < nblk) stage(k + 1); - gdn_cp_commit(); - gdn_cp_wait_prev(); - __syncthreads(); - const int bb = (int) (k & 1); - const int n = (int) ((T - k * TB) < TB ? (T - k * TB) : TB); - for (int i = 0; i < n; ++i) { - const int64_t t = k * TB + i; - float kc[RPG]; -#pragma unroll - for (int r = 0; r < RPG; ++r) kc[r] = sk[bb][i][rg * RPG + r]; - float g[VPK], kv[VPK], delta[VPK], o[VPK]; -#pragma unroll - for (int j = 0; j < VPK; ++j) { g[j] = __expf(sg[bb][i][j]); kv[j] = 0.0f; o[j] = 0.0f; } -#pragma unroll - for (int r = 0; r < RPG; ++r) -#pragma unroll - for (int j = 0; j < VPK; ++j) kv[j] = fmaf(s[j][r], kc[r], kv[j]); -#pragma unroll - for (int j = 0; j < VPK; ++j) rkv[j][rg][c] = kv[j]; - __syncthreads(); -#pragma unroll - for (int j = 0; j < VPK; ++j) { - const float kv_col = rkv[j][0][c] + rkv[j][1][c] + rkv[j][2][c] + rkv[j][3][c]; - delta[j] = (sv[bb][i][j][c] - g[j] * kv_col) * sb[bb][i][j]; - } -#pragma unroll - for (int r = 0; r < RPG; ++r) { - const float qr = sq[bb][i][rg * RPG + r]; -#pragma unroll - for (int j = 0; j < VPK; ++j) { - s[j][r] = fmaf(g[j], s[j][r], kc[r] * delta[j]); - o[j] = fmaf(s[j][r], qr, o[j]); - } - } -#pragma unroll - for (int j = 0; j < VPK; ++j) ro[j][rg][c] = o[j]; - __syncthreads(); - if (rg < VPK) // row group j writes head j's output - oc_out[t * HV * S + (qh + rg * HK) * S + col] = - (ro[rg][0][c] + ro[rg][1][c] + ro[rg][2][c] + ro[rg][3][c]) * rsqrtf((float) S); - } - } -#pragma unroll - for (int j = 0; j < VPK; ++j) { - float* base = state + ((size_t) (rg * RPG) * HV + qh + j * HK) * S + col; -#pragma unroll - for (int r = 0; r < RPG; ++r) base[r * rs] = s[j][r]; - } -} -template __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 -__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) { - __shared__ float wsum[4]; - const int64_t t = blockIdx.x; - const int head = blockIdx.y, col = threadIdx.x; - const size_t at = (size_t) t * HV * S + (size_t) head * S + col; - const float oc = y[at]; - float sp = warp_sum(oc * oc); - if ((col & 31) == 0) wsum[col >> 5] = sp; - __syncthreads(); - const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; - const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * gdn_gate(z[t * HV * S + head * S + col]); - y16[at] = hf(v); -} - -// ------------------------------------------------------------------ the output norm before (0.1.31) -template -__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) { - __shared__ float wsum[4]; - const int64_t t = blockIdx.x; - const int head = blockIdx.y, col = threadIdx.x; - const size_t at = (size_t) t * HV * S + (size_t) head * S + col; - const float oc = y[at]; - float sp = warp_sum(oc * oc); - if ((col & 31) == 0) wsum[col >> 5] = sp; - __syncthreads(); - const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; - const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * gdn_gate(z[t * HV * S + head * S + col]); - y[at] = v; - y16[at] = hf(v); -} - -// ------------------------------------------------------------------ synthetic inputs -__device__ __forceinline__ uint32_t mix(uint64_t x) { - x ^= x >> 33; x *= 0xff51afd7ed558ccdULL; x ^= x >> 33; x *= 0xc4ceb9fe1a85ec53ULL; x ^= x >> 33; - return (uint32_t) x; -} -__device__ __forceinline__ float uni(uint64_t key) { return ((mix(key) >> 8) + 0.5f) * (1.0f / 16777216.0f); } -__device__ __forceinline__ float gauss(uint64_t key) { - const float u1 = uni(key * 2 + 1), u2 = uni(key * 2 + 2); - return sqrtf(-2.0f * logf(u1)) * cosf(6.2831853f * u2); -} -__global__ void fill_gauss(float* x, int64_t n, float scale, uint64_t seed, float offset = 0.0f) { - for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) - 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 -__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]; - __shared__ float part[4]; - const float sq = warp_sum(v * v); - if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sq; - __syncthreads(); - x[threadIdx.x] = v * rsqrtf(part[0] + part[1] + part[2] + part[3] + eps); -} -// gate = log of the decay (mostly near 1, some strong), beta in (0, 1) -__global__ void fill_gates(float* gate, float* beta, int64_t n, uint64_t seed) { - for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) { - const float u = uni(seed * 0x9E3779B97F4A7C15ULL + 7 * (uint64_t) i); - gate[i] = -0.02f - 0.8f * u * u * u; - beta[i] = 1.0f / (1.0f + expf(-gauss(seed * 0xD1B54A32D192ED03ULL + (uint64_t) i))); - } -} -__global__ void count_diff(const uint32_t* a, const uint32_t* b, int64_t n, unsigned long long* out) { - unsigned long long d = 0; - for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) - d += a[i] != b[i]; - if (d) atomicAdd(out, d); -} - -// ------------------------------------------------------------------ holding SMs (fewer_sms) -__device__ __forceinline__ uint64_t gtime() { - uint64_t t; - asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); - return t; -} -__device__ __forceinline__ int sm_id() { - unsigned id; - asm volatile("mov.u32 %0, %%smid;" : "=r"(id)); - return (int) id; -} -__device__ __forceinline__ void nap(unsigned ns) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 - __nanosleep(ns); -#else - (void) ns; -#endif -} -// limits that a run that works never reaches (a launch here takes milliseconds); they keep a run that does not work -// from waiting forever, and the host drops its time -constexpr uint64_t kHoldLimitNs = 1000000000ull, kWaitLimitNs = 500000000ull; -// One block per SM: it asks for all the shared memory a block may have (launched with that much dynamic shared -// memory), so no block of another kernel fits beside it. It notes its SM and sleeps until release says gen. -__global__ void hold_sm(unsigned long long* sitting, const volatile unsigned* release, unsigned gen, int* where, - unsigned* late) { - where[blockIdx.x] = sm_id(); - __threadfence(); - atomicAdd(sitting, 1ull); - const uint64_t t0 = gtime(); - while (*release != gen) { - if (gtime() - t0 > kHoldLimitNs) { atomicAdd(late, 1u); return; } - nap(20000); - } -} -// on the timed launch's stream, before it: returns once all holding blocks so far sit on their SMs -__global__ void wait_sitting(const volatile unsigned long long* sitting, unsigned long long all, unsigned* late) { - const uint64_t t0 = gtime(); - while (*sitting < all) { - if (gtime() - t0 > kWaitLimitNs) { atomicAdd(late, 1u); return; } - nap(1000); - } -} -__global__ void release_sms(volatile unsigned* release, unsigned gen) { *release = gen; } -// Where the blocks of a grid land: launched like the recurrence it stands for (the same grid and block size, and as -// much dynamic shared memory as lets as many blocks share an SM), every block notes its SM and stays until all of them -// have landed, so they all sit at once as the recurrence's blocks do for the whole chunk. -__global__ void land(int* where, unsigned* landed, unsigned* apart) { - extern __shared__ unsigned char land_smem[]; // only its size matters - if (threadIdx.x != 0 || threadIdx.y != 0) return; - where[blockIdx.x] = sm_id(); - atomicAdd(landed, 1u); - const uint64_t t0 = gtime(); - while (*(volatile unsigned*) landed < gridDim.x) { - if (gtime() - t0 > kWaitLimitNs) { atomicAdd(apart, 1u); return; } // they did not all fit at once - nap(1000); - } - (void) land_smem; -} - -template T* dalloc(size_t n) { - T* p = nullptr; - ck(cudaMalloc((void**) &p, n * sizeof(T) + 16), "cudaMalloc"); - return p; -} -unsigned long long diff_words(const void* a, const void* b, size_t bytes) { - static unsigned long long* d = dalloc(1); - ck(cudaMemset(d, 0, sizeof(*d)), "memset"); - count_diff<<<1024, 256>>>((const uint32_t*) a, (const uint32_t*) b, (int64_t) (bytes / 4), d); - unsigned long long h = 0; - ck(cudaMemcpy(&h, d, sizeof(h), cudaMemcpyDeviceToHost), "diff"); - return h; -} - -template -struct Inputs { - int64_t T = 0; - float *h = nullptr, *gate = nullptr, *beta = nullptr, *z = nullptr, *gamma = nullptr, *state0 = nullptr; - explicit Inputs(int64_t t, uint64_t seed) : T(t) { - h = dalloc((size_t) T * C); - gate = dalloc((size_t) T * HV); - beta = dalloc((size_t) T * HV); - z = dalloc((size_t) T * HV * S); - gamma = dalloc(S); - state0 = dalloc((size_t) S * HV * S); - fill_gauss<<<4096, 256>>>(h, T * C, 1.0f, seed); - l2_rows<<>>(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); - fill_gauss<<<1024, 256>>>(state0, (int64_t) S * HV * S, 0.05f, seed + 4); - ck(cudaDeviceSynchronize(), "inputs"); - } - Inputs(const Inputs&) = delete; - Inputs& operator=(const Inputs&) = delete; - ~Inputs() { cudaFree(h); cudaFree(gate); cudaFree(beta); cudaFree(z); cudaFree(gamma); cudaFree(state0); } -}; - -enum Rec { kBefore, kKeyHead, kRecCount }; -template -void run_rec(Rec v, float* state, const Inputs& in, float* oc, cudaStream_t s = 0) { - if (v == kBefore) - gdn_rec_cols_pipe_kernel<<>>(state, in.h, in.gate, in.beta, oc, in.T); - else - gdn_rec_kh_kernel<<>>(state, in.h, in.gate, in.beta, oc, in.T); -} - -template -int check_bits(int64_t T, uint64_t seed) { - Inputs in(T, seed); - const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S; - float* state[kRecCount]; - float* oc[kRecCount]; - for (int v = 0; v < kRecCount; ++v) { - state[v] = dalloc(st); - oc[v] = dalloc(oc_n); - ck(cudaMemcpy(state[v], in.state0, st * 4, cudaMemcpyDeviceToDevice), "state copy"); - run_rec((Rec) v, state[v], in, oc[v]); - } - ck(cudaDeviceSynchronize(), "recurrence"); - int fails = 0; - const unsigned long long d_oc = diff_words(oc[kBefore], oc[kKeyHead], oc_n * 4), - d_st = diff_words(state[kBefore], state[kKeyHead], st * 4); - if (d_oc || d_st) { - std::printf("FAIL T=%lld recurrence: %llu of %zu outputs and %llu of %zu state values differ\n", (long long) T, - d_oc, oc_n, d_st, st); - ++fails; - } - // the output norm: before (in place, with the FP32 store) against now (the FP16 store only), on the same output - uint16_t* y16a = dalloc(oc_n); - uint16_t* y16b = dalloc(oc_n); - float* yb = dalloc(oc_n); - ck(cudaMemcpy(yb, oc[kBefore], oc_n * 4, cudaMemcpyDeviceToDevice), "y copy"); - constexpr bool SILU = HV == 32; // the Qwen3.6 geometry gates with SiLU - gdn_out_norm_kernel<<>>(in.z, in.gamma, 1e-6f, yb, y16b); - gdn_out_norm_old_kernel<<>>(in.z, in.gamma, 1e-6f, oc[kBefore], y16a); - ck(cudaDeviceSynchronize(), "norm"); - const unsigned long long d16 = diff_words(y16a, y16b, oc_n * 2); - if (d16) { - std::printf("FAIL T=%lld output norm: %llu of %zu FP16 pairs differ\n", (long long) T, d16, oc_n / 2); - ++fails; - } - std::printf("%d/%d/%d T=%-6lld %s\n", HV, HK, C, (long long) T, fails ? "DIFFERENT" : "the same bits (output, state, FP16 output)"); - for (int v = 0; v < kRecCount; ++v) { cudaFree(state[v]); cudaFree(oc[v]); } - cudaFree(y16a); cudaFree(y16b); cudaFree(yb); - return fails; -} - -float median(std::vector v) { - std::sort(v.begin(), v.end()); - return v.empty() ? 0.0f : v[v.size() / 2]; -} - -template -void bench(int64_t T) { - constexpr bool SILU = HV == 32; - Inputs in(T, 0xB3); - const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S; - float* state = dalloc(st); - float* oc = dalloc(oc_n); - uint16_t* y16 = dalloc(oc_n); - cudaEvent_t e0, e1; - ck(cudaEventCreate(&e0), "event"); - ck(cudaEventCreate(&e1), "event"); - auto timed = [&](auto&& launch) { - ck(cudaMemcpy(state, in.state0, st * 4, cudaMemcpyDeviceToDevice), "state"); - cudaEventRecord(e0); - launch(); - cudaEventRecord(e1); - ck(cudaEventSynchronize(e1), "timed"); - float ms = 0.0f; - cudaEventElapsedTime(&ms, e0, e1); - return ms; - }; - const int warm = 3, rounds = T >= 16384 ? 10 : 20; - std::vector t_rec[kRecCount], t_norm[2]; - 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); }); - if (i >= warm) t_rec[v].push_back(ms); - } - } - for (int i = 0; i < warm + rounds; ++i) { - 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<<>>(in.z, in.gamma, 1e-6f, oc, y16); - else gdn_out_norm_kernel<<>>(in.z, in.gamma, 1e-6f, oc, y16); - }); - if (i >= warm) t_norm[v].push_back(ms); - } - } - const float r0 = median(t_rec[kBefore]), r1 = median(t_rec[kKeyHead]), n0 = median(t_norm[0]), n1 = median(t_norm[1]); - std::printf(" T = %lld tokens, one layer (%d value heads / %d key heads), medians of %d alternating runs:\n", (long long) T, HV, HK, rounds); - std::printf(" recurrence, before (gdn_rec_cols_pipe_kernel) %8.2f ms (%.3f us per token)\n", r0, - 1000.0f * r0 / (float) T); - std::printf(" recurrence, gdn_rec_kh_kernel %8.2f ms (%.3f us per token) %.2fx\n", r1, - 1000.0f * r1 / (float) T, r0 / r1); - std::printf(" output norm, before (FP32 and FP16 store) %8.2f ms\n", n0); - std::printf(" output norm, FP16 store only %8.2f ms %.2fx\n", n1, n0 / n1); - const float nl = HV == 32 ? 30.0f : 36.0f; // the model's DeltaNet layers (Qwen3.6: 30 of 40; Flash-Next: 36 of 48) - std::printf(" %.0f DeltaNet layers per %lld-token block: recurrence + norm %.0f ms -> %.0f ms (-%.0f ms)\n", - nl, (long long) T, nl * (r0 + n0), nl * (r1 + n1), nl * (r0 + n0 - r1 - n1)); - cudaEventDestroy(e0); - cudaEventDestroy(e1); - cudaFree(state); cudaFree(oc); cudaFree(y16); -} - -// The two kernels at a given number of blocks per SM, as on cards with more or fewer SMs than this one: the kernel -// before puts ceil(192 / SMs) of its blocks on an SM, gdn_rec_kh_kernel ceil(64 / SMs), and the busiest SM sets the -// pace (every block walks the whole chunk). b blocks per SM here: b rounds of one block per SM, each round one launch -// of SMs blocks (the first heads; split in launches of at most the engine's grid), every launch on its own stream with -// 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"); - 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); - const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S; - float* state[kMaxLaunches]; - float* oc[kMaxLaunches]; - cudaStream_t stream[kMaxLaunches]; - cudaEvent_t e0, e1, done[kMaxLaunches]; - ck(cudaEventCreate(&e0), "event"); - ck(cudaEventCreate(&e1), "event"); - for (int c = 0; c < kMaxLaunches; ++c) { - state[c] = dalloc(st); - oc[c] = dalloc(oc_n); - ck(cudaStreamCreateWithFlags(&stream[c], cudaStreamNonBlocking), "stream"); - ck(cudaEventCreate(&done[c]), "event"); - } - struct Case { int v, b; }; - std::vector cases; - for (int v = 0; v < kRecCount; ++v) - for (int b = 1; b <= std::min(kMaxB, per_sm[v]); ++b) - if (b * parts(v) <= kMaxLaunches) cases.push_back({v, b}); - auto run = [&](const Case& cs) { - for (int c = 0; c < kMaxLaunches; ++c) ck(cudaMemcpy(state[c], in.state0, st * 4, cudaMemcpyDeviceToDevice), "state"); - ck(cudaDeviceSynchronize(), "sync"); - const int np = parts(cs.v), n = cs.b * np; - cudaEventRecord(e0, stream[0]); - for (int c = 0; c < n; ++c) { - 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<<>>(state[c], in.h, in.gate, in.beta, oc[c], T); - else - gdn_rec_kh_kernel<<>>(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); - cudaEventRecord(e1, stream[0]); - ck(cudaEventSynchronize(e1), "scale"); - float ms = 0.0f; - cudaEventElapsedTime(&ms, e0, e1); - return ms; - }; - const int warm = 2, rounds = 9; - std::vector> t(cases.size()); - for (int i = 0; i < warm + rounds; ++i) - for (size_t j = 0; j < cases.size(); ++j) { - const size_t k = (i + j) % cases.size(); // a different case first in each round - const float ms = run(cases[k]); - if (i >= warm) t[k].push_back(ms); - } - auto us = [&](int v, int b) { // per token, or < 0 if not measured - for (size_t k = 0; k < cases.size(); ++k) - if (cases[k].v == v && cases[k].b == b) return 1000.0f * median(t[k]) / (float) T; - return -1.0f; - }; - std::printf(" per token at a given number of blocks per SM (%lld tokens, medians of %d alternating runs; this card has " - "%d SMs):\n", (long long) T, rounds, sms); - std::printf(" blocks per SM before gdn_rec_kh_kernel\n"); - for (int b = 1; b <= kMaxB; ++b) { - const float u0 = us(kBefore, b), u1 = us(kKeyHead, b); - if (u0 < 0 && u1 < 0) continue; - char a0[32] = "-", a1[32] = "-"; - if (u0 >= 0) std::snprintf(a0, sizeof a0, "%.3f us", u0); - if (u1 >= 0) std::snprintf(a1, sizeof a1, "%.3f us", u1); - std::printf(" %8d %-11s %s\n", b, a0, a1); - } - std::printf(" so on a card with N SMs (the kernel before puts ceil(192 / N) blocks on an SM, gdn_rec_kh_kernel " - "ceil(64 / N), at most %d):\n", per_sm[kKeyHead]); - const int bands[][2] = {{192, 0}, {96, 191}, {64, 95}, {48, 63}, {39, 47}, {32, 38}}; - for (const auto& bd : bands) { - const int nsm = bd[0], b0 = (192 + nsm - 1) / nsm, b1 = (64 + nsm - 1) / nsm; - const float u0 = us(kBefore, b0), u1 = us(kKeyHead, b1); - char range[32]; - if (bd[1]) std::snprintf(range, sizeof range, "%d-%d SMs", bd[0], bd[1]); - else std::snprintf(range, sizeof range, "%d+ SMs", bd[0]); - if (u0 < 0 || u1 < 0) - std::printf(" %-12s before %d / new %d per SM: not measured on this card\n", range, b0, b1); - else - std::printf(" %-12s before %d / new %d per SM: %.3f -> %.3f us per token, %.2fx\n", range, b0, b1, u0, u1, - u0 / u1); - } - for (int c = 0; c < kMaxLaunches; ++c) { - cudaFree(state[c]); - cudaFree(oc[c]); - cudaStreamDestroy(stream[c]); - cudaEventDestroy(done[c]); - } - cudaEventDestroy(e0); - cudaEventDestroy(e1); -} - -// The engine's grids on N of this card's SMs. scale() puts as many blocks on every SM as the busiest SM of a card with -// N SMs gets; on that card only some SMs get that many (192 blocks on 80 SMs: 3 on 32 SMs, 2 on the other 48), the -// rest of the card has less to do, and the estimate came out 4-9 % above the real launch on two cards. Here the -// recurrences run as the engine launches them, while hold_sm keeps all but N SMs: its blocks go out first, a small -// kernel on the timed launch's stream waits until they all sit, and one after the timed launch lets them go. land() -// 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"); - ck(cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev), "shared memory"); - ck(cudaDeviceGetAttribute(&smem_sm, cudaDevAttrMaxSharedMemoryPerMultiprocessor, dev), "shared memory"); - ck(cudaDeviceGetAttribute(&reserved, cudaDevAttrReservedSharedMemoryPerBlock, dev), "shared memory"); - for (const void* f : {(const void*) hold_sm, (const void*) land}) { - ck(cudaFuncSetAttribute(f, cudaFuncAttributeMaxDynamicSharedMemorySize, optin), "shared memory"); - ck(cudaFuncSetAttribute(f, cudaFuncAttributePreferredSharedMemoryCarveout, (int) cudaSharedmemCarveoutMaxShared), - "carveout"); - } - // 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"); - 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"); - 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); - const int left = smem_sm - optin - reserved; // shared memory a holding block leaves on its SM - if (hold_per_sm != 1 || (int) fa[kBefore].sharedSizeBytes + reserved <= left || - (int) fa[kKeyHead].sharedSizeBytes + reserved <= left) { - std::printf(" not on this card: a block of a recurrence would fit beside a holding block (%d bytes left)\n", - left); - return; - } - // land(): as much dynamic shared memory as still lets as many of its blocks share an SM as of the recurrence - int land_smem[kRecCount]; - for (int v = 0; v < kRecCount; ++v) { - int lo = 0, hi = optin; - while (lo < hi) { - const int mid = (lo + hi + 1) / 2; - int nb = 0; - ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&nb, land, CB * RG, mid), "occupancy"); - if (nb >= per_sm[v]) lo = mid; - else hi = mid - 1; - } - land_smem[v] = lo; - } - // N: all SMs, and below that the SM counts of cards and the band edges, as long as both grids fit at once - std::vector ns = {sms}; - for (const int n : {170, 144, 132, 128, 112, 108, 96, 95, 84, 82, 80, 76, 72, 70, 66, 64, 63, 60, 56, 52, 48, 47, 46, 44, - 40, 39, 38, 36, 34, 32}) - 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); - const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S; - float* state = dalloc(st); - float* oc = dalloc(oc_n); - unsigned long long* sitting = dalloc(1); - unsigned* flags = dalloc(4); - unsigned *release = flags, *late = flags + 1, *landed = flags + 2, *apart = flags + 3; - int* where = dalloc((size_t) sms + grid[kBefore]); // the holding blocks' SMs, then land()'s - ck(cudaMemset(sitting, 0, sizeof(*sitting)), "memset"); - ck(cudaMemset(flags, 0, 4 * sizeof(unsigned)), "memset"); - cudaStream_t s_hold, s_run; - ck(cudaStreamCreateWithFlags(&s_hold, cudaStreamNonBlocking), "stream"); - ck(cudaStreamCreateWithFlags(&s_run, cudaStreamNonBlocking), "stream"); - cudaEvent_t e0, e1; - ck(cudaEventCreate(&e0), "event"); - ck(cudaEventCreate(&e1), "event"); - unsigned long long all = 0; // holding blocks launched so far: sitting counts every one that sat down - unsigned gen = 0; - auto hold = [&](int n) { // all but n SMs, before the next launch on s_run - if (n >= sms) return; - ++gen; - all += (unsigned long long) (sms - n); - hold_sm<<>>(sitting, release, gen, where, late); - ck(cudaGetLastError(), "hold_sm"); - const cudaError_t q = cudaStreamQuery(s_hold); // hands the launch to the GPU now (Windows collects launches) - if (q != cudaErrorNotReady) ck(q, "hold_sm"); - (void) cudaGetLastError(); // not ready is no error - wait_sitting<<<1, 1, 0, s_run>>>(sitting, all, late); - }; - auto let_go = [&](int n) { - if (n < sms) release_sms<<<1, 1, 0, s_run>>>(release, gen); - }; - auto settle = [&](const char* what) { - ck(cudaStreamSynchronize(s_run), what); - ck(cudaStreamSynchronize(s_hold), what); - }; - auto count = [&](const unsigned* c) { // after settle() - unsigned h = 0; - ck(cudaMemcpy(&h, c, sizeof(h), cudaMemcpyDeviceToHost), "count"); - return h; - }; - auto done = [&] { - cudaEventDestroy(e0); - cudaEventDestroy(e1); - cudaStreamDestroy(s_hold); - cudaStreamDestroy(s_run); - cudaFree(state); cudaFree(oc); cudaFree(sitting); cudaFree(flags); cudaFree(where); - }; - - // where the grids land, once per N - struct Landing { bool held = true; int busiest[kRecCount] = {}, on[kRecCount] = {}; }; - std::vector lands(ns.size()); - for (size_t i = 0; i < ns.size(); ++i) { - const int n = ns[i]; - for (int v = 0; v < kRecCount; ++v) { - bool sat = false; - unsigned apart0 = 0; - for (int attempt = 0; attempt < 2 && !sat; ++attempt) { - const unsigned late0 = count(late); - apart0 = count(apart); - ck(cudaMemsetAsync(landed, 0, sizeof(unsigned), s_run), "memset"); - hold(n); - land<<>>(where + sms, landed, apart); - ck(cudaGetLastError(), "land"); - let_go(n); - settle("land"); - sat = count(late) == late0; - } - if (!sat) { // twice: the holding kernel and the launches beside it do not run at the same time here - std::printf(" not on this card: the other SMs could not be held (the kernel holding them and the " - "launches beside it did not run at the same time)\n"); - done(); - return; - } - std::vector w((size_t) sms + grid[v]); - ck(cudaMemcpy(w.data(), where, w.size() * sizeof(int), cudaMemcpyDeviceToHost), "where"); - std::map held, blocks; - for (int b = 0; b < (n < sms ? sms - n : 0); ++b) ++held[w[b]]; - for (int b = 0; b < grid[v]; ++b) ++blocks[w[sms + b]]; - bool ok = count(apart) == apart0 && (int) held.size() == (n < sms ? sms - n : 0) && (int) blocks.size() <= n; - int most = 0, on = 0; - for (const auto& sb : blocks) { - if (held.count(sb.first)) ok = false; - if (sb.second > most) { most = sb.second; on = 0; } - if (sb.second == most) ++on; - } - lands[i].held = lands[i].held && ok; - lands[i].busiest[v] = most; - lands[i].on[v] = on; - } - } - - // the timings: every N and recurrence once per round, a different one first in each round - struct Case { size_t i; Rec v; }; - std::vector cases; - for (size_t i = 0; i < ns.size(); ++i) - if (lands[i].held) - for (int v = 0; v < kRecCount; ++v) cases.push_back({i, (Rec) v}); - auto run = [&](const Case& cs) { // ms, or < 0 if the SMs were not held for the whole launch - const int n = ns[cs.i]; - const unsigned late0 = count(late); - 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); - ck(cudaEventRecord(e1, s_run), "event"); - let_go(n); - settle("fewer SMs"); - if (count(late) != late0) return -1.0f; - float ms = 0.0f; - ck(cudaEventElapsedTime(&ms, e0, e1), "event"); - return ms; - }; - const int warm = 2, rounds = 15, max_dropped = 5; - std::vector> t(cases.size()); - int dropped = 0; - for (int r = 0; r < warm + rounds && dropped <= max_dropped; ++r) - for (size_t j = 0; j < cases.size() && dropped <= max_dropped; ++j) { - const size_t k = (r + j) % cases.size(); - const float ms = run(cases[k]); - if (ms < 0.0f) ++dropped; - else if (r >= warm) t[k].push_back(ms); - } - if (dropped > max_dropped) { // each such run waits for a limit of a second or so - std::printf(" stopped: in %d runs the other SMs were not held for the whole launch\n", dropped); - done(); - return; - } - auto us = [&](size_t i, int v) { // per token, or < 0 if not measured - for (size_t k = 0; k < cases.size(); ++k) - if (cases[k].i == i && cases[k].v == v && !t[k].empty()) return 1000.0f * median(t[k]) / (float) T; - return -1.0f; - }; - auto blocks_on = [](char* out, size_t size, int most, int on) { - std::snprintf(out, size, "%d block%s on %d SM%s", most, most == 1 ? "" : "s", on, on == 1 ? "" : "s"); - }; - std::printf(" (medians of %d alternating runs; L2, memory and clock stay this card's)\n", rounds); - std::printf(" N before: busiest SM new: busiest SM us per token, before -> new\n"); - for (size_t i = 0; i < ns.size(); ++i) { - if (!lands[i].held) { - std::printf(" %3d the other SMs were not held (a block landed on one, or a wait ran out)\n", ns[i]); - continue; - } - char b0[40], b1[40]; - blocks_on(b0, sizeof b0, lands[i].busiest[kBefore], lands[i].on[kBefore]); - blocks_on(b1, sizeof b1, lands[i].busiest[kKeyHead], lands[i].on[kKeyHead]); - const float u0 = us(i, kBefore), u1 = us(i, kKeyHead); - if (u0 < 0.0f || u1 < 0.0f) std::printf(" %3d %-20s %-20s not measured\n", ns[i], b0, b1); - else std::printf(" %3d %-20s %-20s %.3f -> %.3f %.2fx\n", ns[i], b0, b1, u0, u1, u0 / u1); - } - if (dropped) std::printf(" (%d runs dropped: the other SMs were not held for the whole launch)\n", dropped); - std::printf(" so on a card with N SMs, as measured here (the kernel before puts ceil(192 / N) blocks on the busiest SM, " - "gdn_rec_kh_kernel ceil(64 / N)):\n"); - const int bands[][2] = {{96, 191}, {64, 95}, {48, 63}, {39, 47}, {32, 38}}; - for (const auto& bd : bands) { - const int b0 = (192 + bd[0] - 1) / bd[0], b1 = (64 + bd[0] - 1) / bd[0]; - float lo = 0.0f, hi = 0.0f; - int cnt = 0, nmin = 0, nmax = 0; - for (size_t i = 0; i < ns.size(); ++i) { - const float u0 = us(i, kBefore), u1 = us(i, kKeyHead); - if (ns[i] < bd[0] || ns[i] > bd[1] || u0 < 0.0f || u1 < 0.0f) continue; - const float x = u0 / u1; - if (cnt == 0 || x < lo) lo = x; - if (cnt == 0 || x > hi) hi = x; - if (cnt == 0 || ns[i] < nmin) nmin = ns[i]; - if (cnt == 0 || ns[i] > nmax) nmax = ns[i]; - ++cnt; - } - char range[32]; - std::snprintf(range, sizeof range, "%d-%d SMs", bd[0], bd[1]); - if (cnt > 0) - std::printf(" %-12s before %d / new %d per SM: %.2fx to %.2fx (%d to %d SMs)\n", range, b0, b1, lo, hi, nmin, - nmax); - else if (bd[0] > sms) - std::printf(" %-12s before %d / new %d per SM: more SMs than this card has (see the estimate above)\n", range, - b0, b1); - else - std::printf(" %-12s before %d / new %d per SM: not measured\n", range, b0, b1); - } - 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 h, gate, beta, z, gamma, state0; - template explicit HostIn(const Inputs& 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& y, std::vector& 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 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& a, const std::vector& 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 check_reference(int64_t T, uint64_t seed) { - constexpr bool SILU = HV == 32; - Inputs 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(st); - float* y = dalloc(n); - uint16_t* y16 = dalloc(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 hy16(n); - std::vector hstate(st); - ck(cudaMemcpy(hy16.data(), y16, n * 2, cudaMemcpyDeviceToHost), "y16"); - ck(cudaMemcpy(hstate.data(), state, st * 4, cudaMemcpyDeviceToHost), "state"); - std::vector ey(n), es(hstate.begin(), hstate.end()); - for (size_t i = 0; i < n; ++i) ey[i] = h2f(hy16[i]); - std::vector 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 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 check_conv(int64_t T, uint64_t seed) { - float* qkv = dalloc((size_t) T * C); - float* w = dalloc((size_t) C * 4); - float* hist = dalloc((size_t) C * 3); - float* h = dalloc((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 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 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 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 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) { - bool do_bench = false; - for (int i = 1; i < argc; ++i) - if (std::strcmp(argv[i], "--bench") == 0) do_bench = true; - cudaDeviceProp p{}; - ck(cudaGetDeviceProperties(&p, 0), "device"); - std::printf("gdn_rec_parity on %s (sm_%d%d)\n", p.name, p.major, p.minor); - int fails = 0; - // the geometries: built for exactly these two; a third value head per key head on 32 heads (Flash-Next's 48-head - // channel layout, C 10240, on Qwen3.6's heads) and 4 per key head are refused by name - const bool g1 = strata::prefill::gdn_geometry_supported(48, 16, 10240), g2 = strata::prefill::gdn_geometry_supported(32, 16, 8192); - const bool r1 = strata::prefill::gdn_geometry_supported(32, 16, 10240), r2 = strata::prefill::gdn_geometry_supported(32, 8, 8192), - r3 = strata::prefill::gdn_geometry_supported(48, 16, 8192); - std::printf("geometries: 48/16/10240 %s, 32/16/8192 %s; refused: 32 heads with the 48-head channel layout (32/16/10240) %s, " - "4 value heads per key head (32/8/8192) %s, 48/16/8192 %s\n", g1 ? "built" : "*** MISSING ***", - g2 ? "built" : "*** MISSING ***", r1 ? "*** NO ***" : "yes", r2 ? "*** NO ***" : "yes", r3 ? "*** NO ***" : "yes"); - fails += !g1 + !g2 + r1 + r2 + r3; - const int64_t Ts[] = {1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17, 31, 33, 257, 1000, 4099}; - uint64_t seed = 11; - for (const int64_t T : Ts) fails += check_bits<48, 16, 10240>(T, seed++); - for (const int64_t T : Ts) fails += check_bits<32, 16, 8192>(T, seed++); - const int64_t Tr[] = {1, 7, 33, 257}; - for (const int64_t T : Tr) fails += check_reference<48, 16, 10240>(T, seed++); - for (const int64_t T : Tr) fails += check_reference<32, 16, 8192>(T, seed++); - for (const int64_t T : {1, 2, 5, 70, 257}) fails += check_conv<48, 16, 10240>(T, seed++) + check_conv<32, 16, 8192>(T, seed++); - if (do_bench) { - std::printf("--bench: the prompt path's DeltaNet recurrence\n"); - bench<48, 16, 10240>(8192); - bench<48, 16, 10240>(32768); - bench<32, 16, 8192>(8192); - bench<32, 16, 8192>(32768); - scale(8192); - fewer_sms(8192); - } - std::printf("gdn_rec_parity: %d failures\n", fails); - return fails ? 1 : 0; -} diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu deleted file mode 100644 index a35daeb..0000000 --- a/src/prefill/gemm.cu +++ /dev/null @@ -1,556 +0,0 @@ -// src/prefill/gemm.cu - see include/strata/prefill/gemm.hpp. -#include "strata/prefill/gemm.hpp" -#include "strata/kernels/dequant_bf16.hpp" - -#include -#include -#include - -#include -#include - -#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) -// The HIP compatibility shim maps CUDA shuffle spellings to Strata helpers. -// hipBLASLt's public headers declare native HIP shuffle functions, so keep -// those declarations from being macro-expanded in this translation unit. -#undef __shfl_xor_sync -#undef __shfl_down_sync -#undef __shfl_up_sync -#undef __shfl_sync -#undef __ballot_sync -#endif - -#include -#include -#include -#include -#include - -#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) -#include "hipblaslt_tuning.hpp" -#include -#include -#include -#include -#include -#include -#endif - -namespace strata::prefill { -namespace { - -void ck(cublasStatus_t s, const char* what) { - if (s != CUBLAS_STATUS_SUCCESS) { - std::fprintf(stderr, "prefill gemm: %s: cuBLAS status %d\n", what, (int) s); - std::exit(1); - } -} - -// #247/#325: on Windows (seen on gfx1201), hipBLAS can return success with the correct BF16/FP16 product for some -// shapes (hc up once T >= 96, the router) and still leave hipErrorInvalidValue set, which the next kernel's error -// check turns into an exit. The multiply has finished, so that one stale error is cleared after a GEMM that succeeded; -// any other error still stops the engine. Windows only: on Linux a stale hipErrorInvalidValue is a real error from -// an earlier call and keeps being reported. A no-op everywhere else (CUDA compiles none of it). -#if defined(__HIPCC__) && defined(_WIN32) -void absorb_hipblas_sticky(const char* what) { - const hipError_t sticky = hipGetLastError(); - if (sticky == hipSuccess || sticky == hipErrorInvalidValue) return; - std::fprintf(stderr, "prefill gemm: %s left %s\n", what, hipGetErrorString(sticky)); - std::exit(1); -} -#define STRATA_ABSORB_HIPBLAS_STICKY(what) absorb_hipblas_sticky(what) -#else -#define STRATA_ABSORB_HIPBLAS_STICKY(what) ((void) 0) -#endif - -// A setup call whose failure the engine survives (the handle keeps its defaults), as before #240 - but said. -void note(cublasStatus_t s, const char* what) { - if (s != CUBLAS_STATUS_SUCCESS) std::fprintf(stderr, "prefill gemm: %s: cuBLAS status %d (continuing)\n", what, (int) s); -} - -#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) -struct HipLtCallKey { - strata::prefill::hipblaslt::InputType type; - int t; - int n; - int k; - int ldy; - uint32_t beta_bits; - - bool operator<(const HipLtCallKey& other) const { - return std::tie(type, n, k, ldy, t, beta_bits) < - std::tie(other.type, other.n, other.k, other.ldy, other.t, other.beta_bits); - } -}; - -struct HipLtCachedAlgo { - bool supported = false; - hipblasLtMatmulAlgo_t algo{}; - size_t workspace_bytes = 0; -}; - -struct HipLtState { - hipblasLtHandle_t handle = nullptr; - void* workspace = nullptr; - size_t workspace_bytes = 0; - strata::prefill::hipblaslt::TuningTable table; - std::map cache; - uint64_t lt_launches = 0; - uint64_t fallbacks = 0; - std::set> fallback_shapes; - - ~HipLtState() { - if (std::getenv("STRATA_HIPBLASLT_VERBOSE")) { - std::fprintf(stderr, "prefill gemm: hipBLASLt summary launches=%llu fallbacks=%llu unique_fallback_shapes=%zu\n", - (unsigned long long) lt_launches, (unsigned long long) fallbacks, fallback_shapes.size()); - for (const auto& shape : fallback_shapes) { - const auto type = std::get<0>(shape); - std::fprintf(stderr, "prefill gemm: fallback shape dtype=%s T=%d N=%d K=%d ldy=%d\n", - type == strata::prefill::hipblaslt::InputType::bf16 ? "bf16" : "f16", - std::get<1>(shape), std::get<2>(shape), std::get<3>(shape), std::get<4>(shape)); - } - } - if (handle) hipblasLtDestroy(handle); - } -}; - -struct HipLtDescriptors { - hipblasLtMatmulDesc_t op = nullptr; - hipblasLtMatrixLayout_t a = nullptr; - hipblasLtMatrixLayout_t b = nullptr; - hipblasLtMatrixLayout_t c = nullptr; - - ~HipLtDescriptors() { - if (op) hipblasLtMatmulDescDestroy(op); - if (a) hipblasLtMatrixLayoutDestroy(a); - if (b) hipblasLtMatrixLayoutDestroy(b); - if (c) hipblasLtMatrixLayoutDestroy(c); - } - - bool init(hipDataType type, int t, int n, int k, int ldy) { - const hipblasOperation_t trans_a = HIPBLAS_OP_T; - const hipblasOperation_t trans_b = HIPBLAS_OP_N; - if (hipblasLtMatmulDescCreate(&op, HIPBLAS_COMPUTE_32F, HIP_R_32F) != HIPBLAS_STATUS_SUCCESS || - hipblasLtMatmulDescSetAttribute(op, HIPBLASLT_MATMUL_DESC_TRANSA, &trans_a, sizeof(trans_a)) != - HIPBLAS_STATUS_SUCCESS || - hipblasLtMatmulDescSetAttribute(op, HIPBLASLT_MATMUL_DESC_TRANSB, &trans_b, sizeof(trans_b)) != - HIPBLAS_STATUS_SUCCESS || - hipblasLtMatrixLayoutCreate(&a, type, k, n, k) != HIPBLAS_STATUS_SUCCESS || - hipblasLtMatrixLayoutCreate(&b, type, k, t, k) != HIPBLAS_STATUS_SUCCESS || - hipblasLtMatrixLayoutCreate(&c, HIP_R_32F, n, t, ldy) != HIPBLAS_STATUS_SUCCESS) { - return false; - } - return true; - } -}; - -std::unique_ptr create_hipblaslt_state(void* workspace, size_t workspace_bytes) { - const char* path = std::getenv("STRATA_HIPBLASLT_TUNING"); - if (!path || !*path) return nullptr; - - auto state = std::make_unique(); - state->workspace = workspace; - state->workspace_bytes = workspace_bytes; - if (hipblasLtCreate(&state->handle) != HIPBLAS_STATUS_SUCCESS) { - std::fprintf(stderr, "prefill gemm: hipBLASLt handle creation failed; using hipBLASEx\n"); - return nullptr; - } - - int version = 0; - if (hipblasLtGetVersion(state->handle, &version) != HIPBLAS_STATUS_SUCCESS) { - std::fprintf(stderr, "prefill gemm: hipBLASLt version query failed; using hipBLASEx\n"); - return nullptr; - } - int device = 0; - hipDeviceProp_t properties{}; - if (hipGetDevice(&device) != hipSuccess || hipGetDeviceProperties(&properties, device) != hipSuccess) { - std::fprintf(stderr, "prefill gemm: HIP device query failed; using hipBLASEx\n"); - return nullptr; - } - std::string arch(properties.gcnArchName); - const auto suffix = arch.find(':'); - if (suffix != std::string::npos) arch.resize(suffix); - - std::string error; - if (!state->table.load(path, arch, version, error)) { - std::fprintf(stderr, "prefill gemm: %s; using hipBLASEx\n", error.c_str()); - return nullptr; - } - std::fprintf(stderr, "prefill gemm: hipBLASLt tuning enabled (%zu rows, %s, version %d)\n", - state->table.rows().size(), arch.c_str(), version); - return state; -} - -HipLtCachedAlgo resolve_hipblaslt_algo(HipLtState& state, strata::prefill::hipblaslt::InputType type, int t, - int n, int k, int ldy, float beta) { - uint32_t beta_bits = 0; - static_assert(sizeof(beta_bits) == sizeof(beta)); - std::memcpy(&beta_bits, &beta, sizeof(beta)); - const HipLtCallKey key{type, t, n, k, ldy, beta_bits}; - const auto cached = state.cache.find(key); - if (cached != state.cache.end()) return cached->second; - - HipLtCachedAlgo resolved; - const bool verbose = std::getenv("STRATA_HIPBLASLT_VERBOSE") != nullptr; - const auto* row = state.table.closest(type, n, k, ldy, t); - if (!row) { - if (verbose) { - std::fprintf(stderr, "prefill gemm: Lt fallback; no calibration for dtype=%s T=%d N=%d K=%d ldy=%d\n", - type == strata::prefill::hipblaslt::InputType::bf16 ? "bf16" : "f16", t, n, k, ldy); - } - return state.cache.emplace(key, resolved).first->second; - } - - HipLtDescriptors desc; - const hipDataType input_type = type == strata::prefill::hipblaslt::InputType::bf16 ? HIP_R_16BF : HIP_R_16F; - if (!desc.init(input_type, t, n, k, ldy)) { - return state.cache.emplace(key, resolved).first->second; - } - - std::vector solution_ids{row->solution_id}; - std::vector candidates; - if (hipblaslt_ext::getAlgosFromIndex(state.handle, solution_ids, candidates) != HIPBLAS_STATUS_SUCCESS || - candidates.empty() || candidates.front().state != HIPBLAS_STATUS_SUCCESS || - hipblaslt_ext::getIndexFromAlgo(candidates.front().algo) != row->solution_id) { - if (verbose) { - std::fprintf(stderr, "prefill gemm: Lt fallback; solution %d unavailable for T=%d N=%d K=%d ldy=%d\n", - row->solution_id, t, n, k, ldy); - } - return state.cache.emplace(key, resolved).first->second; - } - - const float alpha = 1.0f; - size_t required_workspace = 0; - auto algo = candidates.front().algo; - if (hipblaslt_ext::matmulIsAlgoSupported(state.handle, desc.op, &alpha, desc.a, desc.b, &beta, desc.c, desc.c, - algo, required_workspace) != HIPBLAS_STATUS_SUCCESS) { - if (verbose) { - std::fprintf(stderr, "prefill gemm: Lt fallback; solution %d rejects actual T=%d N=%d K=%d ldy=%d beta=%.9g\n", - row->solution_id, t, n, k, ldy, beta); - } - return state.cache.emplace(key, resolved).first->second; - } - - resolved.supported = true; - resolved.algo = algo; - resolved.workspace_bytes = required_workspace; - if (verbose) { - std::fprintf(stderr, - "prefill gemm: Lt solution=%d dtype=%s T=%d N=%d K=%d ldy=%d beta=%.9g workspace=%zu\n", - row->solution_id, type == strata::prefill::hipblaslt::InputType::bf16 ? "bf16" : "f16", t, n, - k, ldy, beta, required_workspace); - } - return state.cache.emplace(key, resolved).first->second; -} - -bool try_hipblaslt(void* opaque_state, strata::prefill::hipblaslt::InputType type, const uint16_t* x, - const uint16_t* w, float* y, int64_t t, int64_t n, int64_t k, int64_t ldy, float beta, - void* stream) { - auto* state = static_cast(opaque_state); - if (!state || t <= 0 || n <= 0 || k <= 0 || t > INT_MAX || n > INT_MAX || k > INT_MAX || ldy > INT_MAX || - ldy < n) { - return false; - } - const auto resolved = resolve_hipblaslt_algo(*state, type, (int) t, (int) n, (int) k, (int) ldy, beta); - if (!resolved.supported) { - ++state->fallbacks; - state->fallback_shapes.emplace(type, (int) t, (int) n, (int) k, (int) ldy); - return false; - } - if (resolved.workspace_bytes > state->workspace_bytes) { - ++state->fallbacks; - state->fallback_shapes.emplace(type, (int) t, (int) n, (int) k, (int) ldy); - if (std::getenv("STRATA_HIPBLASLT_VERBOSE")) { - std::fprintf(stderr, "prefill gemm: Lt fallback; solution needs %zu workspace bytes, have %zu\n", - resolved.workspace_bytes, state->workspace_bytes); - } - return false; - } - - HipLtDescriptors desc; - const hipDataType input_type = type == strata::prefill::hipblaslt::InputType::bf16 ? HIP_R_16BF : HIP_R_16F; - if (!desc.init(input_type, (int) t, (int) n, (int) k, (int) ldy)) return false; - const float alpha = 1.0f; - const hipblasStatus_t status = hipblasLtMatmul(state->handle, desc.op, &alpha, w, desc.a, x, desc.b, &beta, y, - desc.c, y, desc.c, &resolved.algo, state->workspace, - state->workspace_bytes, (hipStream_t) stream); - if (status == HIPBLAS_STATUS_SUCCESS) { - ++state->lt_launches; - return true; - } - - std::fprintf(stderr, "prefill gemm: hipBLASLt launch failed with status %d\n", (int) status); - if (beta != 0.0f) { - std::fprintf(stderr, "prefill gemm: refusing a fallback after hipBLASLt failed with nonzero beta\n"); - std::exit(1); - } - auto* mutable_state = static_cast(opaque_state); - uint32_t beta_bits = 0; - std::memcpy(&beta_bits, &beta, sizeof(beta_bits)); - auto cached = mutable_state->cache.find(HipLtCallKey{type, (int) t, (int) n, (int) k, (int) ldy, beta_bits}); - if (cached != mutable_state->cache.end()) cached->second.supported = false; - ++mutable_state->fallbacks; - mutable_state->fallback_shapes.emplace(type, (int) t, (int) n, (int) k, (int) ldy); - return false; -} -#endif - -} // namespace - -Gemm::~Gemm() { -#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) - delete static_cast(hipblaslt_state_); -#endif - if (handle_) cublasDestroy((cublasHandle_t) handle_); - if (tc_w_) cudaFree(tc_w_); - if (tc_x_) cudaFree(tc_x_); - if (!external_) { - if (scratch_) cudaFree(scratch_); - if (workspace_) cudaFree(workspace_); - } -} - -bool Gemm::init_external(void* stream, uint16_t* scratch, int64_t scratch_elems, void* workspace, size_t ws_bytes, - std::string& err) { - cublasHandle_t h = nullptr; - if (const cublasStatus_t s = cublasCreate(&h); s != CUBLAS_STATUS_SUCCESS) { - err = "prefill gemm: cublasCreate: cuBLAS status " + std::to_string((int) s); - return false; - } - handle_ = h; - stream_ = stream; - external_ = true; - note(cublasSetStream(h, (cudaStream_t) stream), "cublasSetStream"); - workspace_ = workspace; - note(cublasSetWorkspace(h, workspace_, ws_bytes), "cublasSetWorkspace"); - note(cublasSetMathMode(h, CUBLAS_DEFAULT_MATH), "cublasSetMathMode"); - scratch_ = scratch; - scratch_elems_ = scratch_elems; -#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) - hipblaslt_state_ = create_hipblaslt_state(workspace_, ws_bytes).release(); -#endif - return true; -} - -void Gemm::rebind(uint16_t* scratch, int64_t scratch_elems, void* workspace, size_t ws_bytes) { - scratch_ = scratch; - scratch_elems_ = scratch_elems; - workspace_ = workspace; - cublasSetWorkspace((cublasHandle_t) handle_, workspace_, ws_bytes); -#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) - if (hipblaslt_state_) { - auto* state = static_cast(hipblaslt_state_); - state->workspace = workspace_; - state->workspace_bytes = ws_bytes; - } -#endif -} - -bool Gemm::init(void* stream, int64_t scratch_elems, std::string& err) { - // #240: every failure names the call and the real status, so "no VRAM" can be told from a broken install - cublasHandle_t h = nullptr; - if (const cublasStatus_t s = cublasCreate(&h); s != CUBLAS_STATUS_SUCCESS) { - err = "prefill gemm: cublasCreate: cuBLAS status " + std::to_string((int) s); - return false; - } - handle_ = h; - stream_ = stream; - note(cublasSetStream(h, (cudaStream_t) stream), "cublasSetStream"); - // A fixed workspace so the handle never allocates on the way (and graphs could capture it later). - const size_t ws = 32u << 20; - if (const cudaError_t e = cudaMalloc(&workspace_, ws); e != cudaSuccess) { - err = std::string("prefill gemm: workspace of 32 MiB: ") + cudaGetErrorString(e); - return false; - } - note(cublasSetWorkspace(h, workspace_, ws), "cublasSetWorkspace"); - note(cublasSetMathMode(h, CUBLAS_DEFAULT_MATH), "cublasSetMathMode"); -#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) - hipblaslt_state_ = create_hipblaslt_state(workspace_, ws).release(); -#endif - if (scratch_elems > 0) { - if (const cudaError_t e = cudaMalloc((void**) &scratch_, (size_t) scratch_elems * 2); e != cudaSuccess) { - err = "prefill gemm: dequant scratch of " + std::to_string(scratch_elems * 2 >> 20) + " MiB: " + - cudaGetErrorString(e); - return false; - } - } - scratch_elems_ = scratch_elems; - return true; -} - -#if !defined(__HIPCC__) -// ---- below sm_80: BF16 GEMMs without BF16 tensor cores (PR #655, #540, #395) ---------------------------------------- -// Turing and Volta have no BF16 tensor cores: cublasGemmEx on CUDA_R_16BF inputs falls back to a SIMT fp32 kernel -// (magma_sgemmEx), a fifth of a 4K prompt on an RTX 2080 Ti (#655) and ~10% of a V100's prompt (#540). BF16 -> FP16 -// is exact for every value inside FP16's normal range (the 7-bit mantissa fits in 10 bits); weights and normalized -// activations sit there. With the FP16 path, the weight is converted once per call and the activations in row -// slices, into the instance's own buffers, and the product runs as the FP16 GEMM (fp32 accumulate) on the tensor -// cores. Finite values beyond FP16's range are clamped to +-65504 (#540) instead of becoming Inf. A beta = 1 -// product (STRATA_PREFILL_BF16X2's remainder, ~2^-9 of the original, deep in FP16's subnormal band) keeps cuBLAS. -// Default: on for compute capability 7.0 - 7.4 (Volta: only the experimental STRATA_EXPERIMENTAL_SM60 build runs -// there), OFF for 7.5 (RTX 20 in the ready-made engine: the sums round differently, so it is opt-in until it has -// been gated). STRATA_BF16_TC=1 / =0 turns it on / off on any 7.x card (=2, a test mode: on any card). -// Pascal (6.x) has no tensor cores and cuBLAS has no BF16 GEMM for it (#395, measured NOT_SUPPORTED on a P40): both -// operands are widened to fp32 by an exact shift and the product is cublasSgemm with the same fp32 accumulator. -namespace { -__global__ void bf16_to_f16_kernel(const uint16_t* __restrict__ in, __half* __restrict__ out, int64_t n) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) { - float f = __uint_as_float((uint32_t) in[i] << 16); - if (f > 65504.0f && !isinf(f)) f = 65504.0f; - else if (f < -65504.0f && !isinf(f)) f = -65504.0f; - out[i] = __float2half_rn(f); - } -} -void bf16_to_f16(const uint16_t* in, uint16_t* out, int64_t n, cudaStream_t st) { - if (n <= 0) return; - bf16_to_f16_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, st>>>(in, reinterpret_cast<__half*>(out), n); -} -#if defined(STRATA_EXPERIMENTAL_SM60) // Pascal runs only the experimental build -__global__ void bf16_to_f32_kernel(const uint16_t* __restrict__ in, float* __restrict__ out, int64_t n) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) out[i] = __uint_as_float((uint32_t) in[i] << 16); -} -void bf16_to_f32(const uint16_t* in, float* out, int64_t n, cudaStream_t st) { - if (n <= 0) return; - bf16_to_f32_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, st>>>(in, out, n); -} -#endif -// The current device's compute capability as 10 * major + minor, per device (a layer split can mix cards); 0: not -// known, read as "not an old card" so a failed query keeps the cuBLAS BF16 call. -int current_cc() { - static std::atomic cc[64] = {}; - int dev = 0; - if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return 0; } - int v = cc[dev].load(std::memory_order_relaxed); - if (v == 0) { - int major = 0, minor = 0; - if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess || - cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) { - cudaGetLastError(); - return 0; - } - v = 10 * major + minor; - cc[dev].store(v, std::memory_order_relaxed); - } - return v; -} -// 0: cuBLAS's BF16 GEMM, 1: through FP16 (tensor cores), 2: through FP32 (Pascal) -int bf16_path() { - static const int forced = [] { - const char* v = std::getenv("STRATA_BF16_TC"); - return v != nullptr && v[0] != '\0' ? std::atoi(v) : -1; - }(); - const int cc = current_cc(); - if (forced == 2 && cc > 0) return 1; // a test mode: the FP16 path on any card (gemm_bf16_parity on sm_80+) - if (cc <= 0 || cc >= 80) return 0; - if (cc < 70) return 2; - if (forced >= 0) return forced != 0 ? 1 : 0; - return cc < 75 ? 1 : 0; -} -bool grow(uint16_t*& p, int64_t& have, int64_t want) { // `have`, `want`: 2-byte elements - if (have >= want) return true; - if (p) cudaFree(p); - p = nullptr; - have = 0; - if (cudaMalloc((void**) &p, (size_t) want * 2) != cudaSuccess) { cudaGetLastError(); p = nullptr; return false; } - have = want; - return true; -} -constexpr int64_t kXSliceElems = 16ll << 20; // 32 MiB of FP16 activations per slice (64 MiB as fp32) -} // namespace -#endif - -void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, - float beta) { - if (T <= 0 || N <= 0) return; - if (ldy <= 0) ldy = N; - const float alpha = 1.0f; -#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) - if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::bf16, X, W, Y, T, N, K, ldy, - beta, stream_)) { - STRATA_ABSORB_HIPBLAS_STICKY("hipBLASLt bf16"); - return; - } -#endif -#if !defined(__HIPCC__) - if (const int path = K > 0 ? bf16_path() : 0; path == 1 && N > 1 && beta == 0.0f) { - // a single output row stays cuBLAS's GEMV, faster than the conversions; beta = 1: see above - const int64_t x_rows = std::max(1, std::min(T, kXSliceElems / K)); - if (grow(tc_w_, tc_w_elems_, N * K) && grow(tc_x_, tc_x_elems_, x_rows * K)) { - bf16_to_f16(W, tc_w_, N * K, (cudaStream_t) stream_); - for (int64_t t0 = 0; t0 < T; t0 += x_rows) { - const int64_t n = std::min(x_rows, T - t0); - bf16_to_f16(X + t0 * K, tc_x_, n * K, (cudaStream_t) stream_); - f16(tc_x_, tc_w_, Y + t0 * ldy, n, N, K, ldy, beta); - } - return; - } - } -#if defined(STRATA_EXPERIMENTAL_SM60) - else if (path == 2) { - // Pascal: fp32 copies (2 elements of the 2-byte buffers each). Every tile is a disjoint block of Y, so each - // gets the caller's beta. - const int64_t x_rows = std::max(1, std::min(T, kXSliceElems / K)); - if (grow(tc_w_, tc_w_elems_, 2 * N * K) && grow(tc_x_, tc_x_elems_, 2 * x_rows * K)) { - float* const wf = reinterpret_cast(tc_w_); - float* const xf = reinterpret_cast(tc_x_); - bf16_to_f32(W, wf, N * K, (cudaStream_t) stream_); - for (int64_t t0 = 0; t0 < T; t0 += x_rows) { - const int64_t n = std::min(x_rows, T - t0); - bf16_to_f32(X + t0 * K, xf, n * K, (cudaStream_t) stream_); - ck(cublasSgemm((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) n, (int) K, &alpha, - wf, (int) K, xf, (int) K, &beta, Y + t0 * ldy, (int) ldy), - "cublasSgemm (bf16 on Pascal)"); - } - return; - } - } -#endif -#endif - // Column-major view: Y^T[N, T] = W[N, K] (stored K x N col-major, transposed) . X^T[K, T]. - ck(cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &alpha, W, - CUDA_R_16BF, (int) K, X, CUDA_R_16BF, (int) K, &beta, Y, CUDA_R_32F, (int) ldy, - CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT), - "cublasGemmEx"); - STRATA_ABSORB_HIPBLAS_STICKY("cublasGemmEx"); -} - -void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, - float beta) { - if (T <= 0 || N <= 0) return; - if (ldy <= 0) ldy = N; - const float alpha = 1.0f; -#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) - if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::f16, X, W, Y, T, N, K, ldy, - beta, stream_)) { - STRATA_ABSORB_HIPBLAS_STICKY("hipBLASLt f16"); - return; - } -#endif - ck(cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &alpha, W, - CUDA_R_16F, (int) K, X, CUDA_R_16F, (int) K, &beta, Y, CUDA_R_32F, (int) ldy, - CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT), - "cublasGemmEx f16"); - STRATA_ABSORB_HIPBLAS_STICKY("cublasGemmEx f16"); -} - -void Gemm::native(const uint16_t* X, int ggml_type, const void* W_blocks, float* Y, int64_t T, int64_t N, int64_t K, - int64_t ldy, float beta) { - if (N * K > scratch_elems_) { - // Too large for the scratch at once: in row slices. - const int64_t rows = scratch_elems_ / K; - if (rows <= 0) { std::fprintf(stderr, "prefill gemm: scratch too small for K=%lld\n", (long long) K); std::exit(1); } - if (ldy <= 0) ldy = N; - for (int64_t r0 = 0; r0 < N; r0 += rows) { - const int64_t n = (N - r0 < rows) ? N - r0 : rows; - strata::kernels::dequant_f16(ggml_type, W_blocks, r0, n, K, scratch_, stream_); - f16(X, scratch_, Y + r0, T, n, K, ldy, beta); - } - return; - } - strata::kernels::dequant_f16(ggml_type, W_blocks, 0, N, K, scratch_, stream_); - f16(X, scratch_, Y, T, N, K, ldy, beta); -} - -} // namespace strata::prefill diff --git a/src/prefill/gemm_bf16_parity.cu b/src/prefill/gemm_bf16_parity.cu deleted file mode 100644 index a947005..0000000 --- a/src/prefill/gemm_bf16_parity.cu +++ /dev/null @@ -1,155 +0,0 @@ -// src/prefill/gemm_bf16_parity.cu - Gemm::bf16 against cuBLAS's own BF16 product (GPU, synthetic, no model). -// -// Below sm_80 (no BF16 tensor cores) Gemm::bf16 converts the weight and the activations to FP16 and runs the FP16 -// tensor-core GEMM (Volta by default, Turing with STRATA_BF16_TC=1) or widens them to fp32 (Pascal); everywhere else -// it is the cuBLAS BF16 call itself. (On Pascal the cuBLAS BF16 reference itself may be refused: the test then fails -// at the reference, which says so.) This -// checks the result against cublasGemmEx on the same BF16 inputs, within fp32-accumulation rounding, over the prompt -// path's shapes: the hyper-connection down / up projections, the router and indexer rows, the PLE value matrix, a T -// large enough to slice the activations, beta = 1 accumulation (the bf16x2 low parts) and an output row stride wider -// than N. --bench adds the time of each against the cuBLAS BF16 product. -#include "strata/prefill/gemm.hpp" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { - -uint16_t to_bf16(float f) { // round to nearest even - uint32_t u; - std::memcpy(&u, &f, 4); - u += 0x7fffu + ((u >> 16) & 1u); - return (uint16_t) (u >> 16); -} - -bool ok_or(cudaError_t e, const char* what) { - if (e != cudaSuccess) std::printf("FAIL: %s: %s\n", what, cudaGetErrorString(e)); - return e == cudaSuccess; -} - -struct Shape { - int64_t T, N, K, ldy; - const char* what; -}; - -} // namespace - -int main(int argc, char** argv) { - const bool bench = argc > 1 && std::string(argv[1]) == "--bench"; - int dev = 0, maj = 0, min = 0; - cudaGetDevice(&dev); - cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev); - cudaDeviceGetAttribute(&min, cudaDevAttrComputeCapabilityMinor, dev); - std::printf("gemm_bf16_parity: compute capability %d.%d\n", maj, min); - - cudaStream_t st = nullptr; - if (!ok_or(cudaStreamCreate(&st), "stream")) return 1; - strata::prefill::Gemm gemm; - std::string err; - if (!gemm.init(st, 0, err)) { std::printf("FAIL: %s\n", err.c_str()); return 1; } - cublasHandle_t h = nullptr; - if (cublasCreate(&h) != CUBLAS_STATUS_SUCCESS) { std::printf("FAIL: cublasCreate\n"); return 1; } - cublasSetStream(h, st); - - const Shape shapes[] = { - {4096, 320, 10240, 0, "hc down (activations sliced)"}, - {4096, 10240, 320, 0, "hc up"}, - {777, 2560, 2560, 0, "PLE value"}, - {512, 512, 2560, 0, "router / indexer q"}, - {300, 4, 10240, 0, "hc inject"}, - {2048, 1, 2560, 0, "single row"}, - {333, 128, 2560, 136, "row stride wider than N"}, - }; - std::mt19937 rng(1234); - std::normal_distribution nd(0.0f, 1.0f); - int failures = 0; - for (const Shape& s : shapes) { - const int64_t ldy = s.ldy > 0 ? s.ldy : s.N; - std::vector x((size_t) (s.T * s.K)), xlo(x.size()), w((size_t) (s.N * s.K)); - for (size_t i = 0; i < x.size(); ++i) { - const float v = 3.0f * nd(rng); // activations: normalized, a few units - x[i] = to_bf16(v); - xlo[i] = to_bf16(1e-3f * nd(rng)); // a bf16x2 low part - } - for (auto& v : w) v = to_bf16(0.02f * nd(rng)); - uint16_t *dx = nullptr, *dxlo = nullptr, *dw = nullptr; - float *dy = nullptr, *dr = nullptr; - const size_t ybytes = (size_t) (s.T * ldy) * 4; - bool ok = ok_or(cudaMalloc((void**) &dx, x.size() * 2), "x") && ok_or(cudaMalloc((void**) &dxlo, x.size() * 2), "xlo") && - ok_or(cudaMalloc((void**) &dw, w.size() * 2), "w") && ok_or(cudaMalloc((void**) &dy, ybytes), "y") && - ok_or(cudaMalloc((void**) &dr, ybytes), "ref"); - if (!ok) return 1; - cudaMemcpy(dx, x.data(), x.size() * 2, cudaMemcpyHostToDevice); - cudaMemcpy(dxlo, xlo.data(), xlo.size() * 2, cudaMemcpyHostToDevice); - cudaMemcpy(dw, w.data(), w.size() * 2, cudaMemcpyHostToDevice); - cudaMemset(dy, 0, ybytes); - cudaMemset(dr, 0, ybytes); - - // the product under test: X . W^T, then the low part added with beta = 1 - gemm.bf16(dx, dw, dy, s.T, s.N, s.K, ldy); - gemm.bf16(dxlo, dw, dy, s.T, s.N, s.K, ldy, 1.0f); - // the reference: cuBLAS on the BF16 inputs, the same two calls - const float one = 1.0f, zero = 0.0f; - auto ref = [&](const uint16_t* X, float beta) { - return cublasGemmEx(h, CUBLAS_OP_T, CUBLAS_OP_N, (int) s.N, (int) s.T, (int) s.K, &one, dw, CUDA_R_16BF, - (int) s.K, X, CUDA_R_16BF, (int) s.K, &beta, dr, CUDA_R_32F, (int) ldy, - CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT); - }; - if (ref(dx, zero) != CUBLAS_STATUS_SUCCESS || ref(dxlo, one) != CUBLAS_STATUS_SUCCESS) { - std::printf("FAIL: reference cublasGemmEx\n"); - return 1; - } - if (!ok_or(cudaStreamSynchronize(st), "sync")) return 1; - std::vector y((size_t) (s.T * ldy)), r(y.size()); - cudaMemcpy(y.data(), dy, ybytes, cudaMemcpyDeviceToHost); - cudaMemcpy(r.data(), dr, ybytes, cudaMemcpyDeviceToHost); - double worst = 0.0, mag = 1e-30; - int bad = 0; - for (int64_t t = 0; t < s.T; ++t) - for (int64_t c = 0; c < s.N; ++c) { - const float a = y[(size_t) (t * ldy + c)], b = r[(size_t) (t * ldy + c)]; - if (!std::isfinite(a)) ++bad; - worst = std::max(worst, (double) std::fabs(a - b)); - mag = std::max(mag, (double) std::fabs(b)); - } - // the untouched columns of a wider row stride stay as they were - for (int64_t t = 0; t < s.T && ldy > s.N; ++t) - for (int64_t c = s.N; c < ldy; ++c) - if (y[(size_t) (t * ldy + c)] != 0.0f) ++bad; - const bool pass = bad == 0 && worst <= 1e-4 * mag; - if (!pass) ++failures; - std::printf(" %-32s T %5lld N %5lld K %5lld ldy %5lld: worst |diff| %.3e of max |ref| %.3e (rel %.2e) %s\n", - s.what, (long long) s.T, (long long) s.N, (long long) s.K, (long long) ldy, worst, mag, worst / mag, - pass ? "pass" : "FAIL"); - - if (bench) { - auto time = [&](auto&& f) { - for (int i = 0; i < 3; ++i) f(); - cudaStreamSynchronize(st); - const auto t0 = std::chrono::steady_clock::now(); - for (int i = 0; i < 20; ++i) f(); - cudaStreamSynchronize(st); - return std::chrono::duration(std::chrono::steady_clock::now() - t0).count() / 20; - }; - const double us_gemm = time([&] { gemm.bf16(dx, dw, dy, s.T, s.N, s.K, ldy); }); - const double us_ref = time([&] { ref(dx, zero); }); - std::printf(" bench: Gemm::bf16 %9.1f us cuBLAS BF16 %9.1f us (%.2fx)\n", us_gemm, us_ref, - us_ref / us_gemm); - } - cudaFree(dx); cudaFree(dxlo); cudaFree(dw); cudaFree(dy); cudaFree(dr); - } - cublasDestroy(h); - cudaStreamDestroy(st); - std::printf("gemm_bf16_parity: %d failures\n", failures); - return failures == 0 ? 0 : 1; -} diff --git a/src/prefill/ggml_cuda_host.cu b/src/prefill/ggml_cuda_host.cu deleted file mode 100644 index 1245c2b..0000000 --- a/src/prefill/ggml_cuda_host.cu +++ /dev/null @@ -1,147 +0,0 @@ -// src/prefill/ggml_cuda_host.cu - prompt-speed plan step 2b: the host-side symbols of llama.cpp's ggml-cuda that its MMQ -// and quantize code reference, for the MMQ kernels compiled into strata_mmq without the rest of ggml-cuda.cu. -#include "strata/core/emulate.hpp" -#include "common.cuh" - -#include -#include -#include -#include -#include - -[[noreturn]] void ggml_cuda_error(const char * stmt, const char * func, const char * file, int line, const char * msg) { - std::fprintf(stderr, "ggml-cuda (strata mmq): %s: %s\n in %s at %s:%d\n", msg, stmt, func, file, line); - std::abort(); -} - -int ggml_cuda_get_device() { - int id = 0; - CUDA_CHECK(cudaGetDevice(&id)); - return id; -} - -#if defined(GGML_USE_HIP) -namespace { - -unsigned parse_hex(const std::string& value) { - if (value.empty()) return 0; - char* end = nullptr; - const unsigned long parsed = std::strtoul(value.c_str(), &end, 16); - return end == value.c_str() || *end != '\0' ? 0 : static_cast(parsed); -} - -// Match GGML's AMD cc encoding: OFFSET_AMD + gfx major * 0x100 + minor/stepping. -// For example, gfx1100 maps to GGML_CUDA_CC_RDNA3 (0x01001100). -int ggml_cuda_parse_amd_id(const char* device_name) { - if (device_name == nullptr) return GGML_CUDA_CC_OFFSET_AMD; - - std::string arch(device_name); - if (arch.compare(0, 3, "gfx") == 0) arch.erase(0, 3); - const size_t suffix = arch.find(':'); - if (suffix != std::string::npos) arch.resize(suffix); - - const size_t generic = arch.rfind("-generic"); - if (generic != std::string::npos && generic + 8 == arch.size()) arch.resize(generic); - - unsigned major = 0; - unsigned minor = 0; - const size_t separator = arch.find('-'); - if (separator != std::string::npos) { - major = parse_hex(arch.substr(0, separator)); - minor = parse_hex(arch.substr(separator + 1)) * 0x10; - } else if (arch.size() >= 3) { - minor = parse_hex(arch.substr(arch.size() - 2)); - major = parse_hex(arch.substr(0, arch.size() - 2)); - } - return GGML_CUDA_CC_OFFSET_AMD + static_cast(major * 0x100 + minor); -} - -} // namespace -#endif - -const ggml_cuda_device_info & ggml_cuda_info() { - static ggml_cuda_device_info info = [] { - ggml_cuda_device_info in = {}; - int n = 0; - if (cudaGetDeviceCount(&n) != cudaSuccess) n = 0; - n = n > GGML_CUDA_MAX_DEVICES ? GGML_CUDA_MAX_DEVICES : n; - in.device_count = n; - in.physical_device_count = n; - for (int id = 0; id < n; ++id) { - cudaDeviceProp prop; - CUDA_CHECK(cudaGetDeviceProperties(&prop, id)); - auto & d = in.devices[id]; -#if defined(GGML_USE_HIP) - d.cc = ggml_cuda_parse_amd_id(prop.gcnArchName); - if ((d.cc & 0xff00) == 0) { - // Fall back to HIP's device version fields if its architecture name is unavailable. - d.cc = GGML_CUDA_CC_OFFSET_AMD + prop.major * 0x100 + prop.minor * 0x10; - } - d.smpbo = prop.sharedMemPerBlock; - d.integrated = false; - d.supports_cooperative_launch = false; - d.nsm = prop.multiProcessorCount; - d.smpb = prop.sharedMemPerBlock; - d.warp_size = prop.warpSize; -#else - // #542: the fields MMQ's choices read come from cudaDeviceGetAttribute, which is ABI-stable: a - // cudaDeviceProp filled by an older libcudart than the headers (a CUDA 13 build that links a CUDA 12 - // libcudart.so) is shifted - sharedMemPerBlockOptin read 1 there, and every i-quant lost MMQ (#420's - // fits()). In a matched build both give the same values. - auto attr = [id](cudaDeviceAttr a) { - int v = 0; - CUDA_CHECK(cudaDeviceGetAttribute(&v, a, id)); - return v; - }; - d.cc = 100 * strata::cc_major_of(attr(cudaDevAttrComputeCapabilityMajor)) + - 10 * strata::cc_minor_of(attr(cudaDevAttrComputeCapabilityMinor)); // STRATA_EMULATE_CC - d.smpbo = strata::smem_optin_of(attr(cudaDevAttrMaxSharedMemoryPerBlockOptin)); - d.integrated = attr(cudaDevAttrIntegrated) != 0; - d.supports_cooperative_launch = attr(cudaDevAttrCooperativeLaunch) != 0; - d.nsm = attr(cudaDevAttrMultiProcessorCount); - d.smpb = (size_t) attr(cudaDevAttrMaxSharedMemoryPerBlock); - d.warp_size = attr(cudaDevAttrWarpSize); -#endif - d.vmm = false; - d.total_vram = prop.totalGlobalMem; - d.physical_device = id; - d.physical_share_count = 1; - d.virtual_index = 0; - } - return in; - }(); - return info; -} - -namespace { -// Buffers are kept and reused: MMQ asks for the same few sizes every launch (its stream-k fixup tiles). -struct CachingPool : ggml_cuda_pool { - struct Buf { void * p; size_t size; bool used; }; - std::vector bufs; - std::mutex mu; - void * alloc(size_t size, size_t * actual_size) override { - std::lock_guard lk(mu); - for (auto & b : bufs) - if (!b.used && b.size >= size) { b.used = true; *actual_size = b.size; return b.p; } - void * p = nullptr; - CUDA_CHECK(cudaMalloc(&p, size)); - bufs.push_back({p, size, true}); - *actual_size = size; - return p; - } - void free(void * ptr, size_t) override { - std::lock_guard lk(mu); - for (auto & b : bufs) - if (b.p == ptr) { b.used = false; return; } - } - ~CachingPool() override { - for (auto & b : bufs) cudaFree(b.p); - } -}; -} // namespace - -std::unique_ptr ggml_backend_cuda_context::new_pool_for_device(int, int) { - return std::unique_ptr(new CachingPool()); -} - -ggml_backend_cuda_context::~ggml_backend_cuda_context() {} diff --git a/src/prefill/hipblaslt_tuning.hpp b/src/prefill/hipblaslt_tuning.hpp deleted file mode 100644 index b9d7f54..0000000 --- a/src/prefill/hipblaslt_tuning.hpp +++ /dev/null @@ -1,123 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -namespace strata::prefill::hipblaslt { - -enum class InputType : uint8_t { f16, bf16 }; - -struct TuningRow { - InputType type = InputType::bf16; - int n = 0; - int k = 0; - int ldy = 0; - int t_bucket = 0; - int solution_id = -1; -}; - -class TuningTable { -public: - bool load(const std::string& path, const std::string& expected_arch, int expected_version, std::string& err) { - std::ifstream input(path); - if (!input) { - err = "cannot open tuning file"; - return false; - } - - bool saw_header = false; - std::string line; - size_t line_number = 0; - while (std::getline(input, line)) { - ++line_number; - const auto first = line.find_first_not_of(" \t\r\n"); - if (first == std::string::npos || line[first] == '#') continue; - - std::istringstream row(line.substr(first)); - if (!saw_header) { - std::string magic; - std::string arch; - int version = 0; - std::string extra; - if (!(row >> magic >> arch >> version) || (row >> extra) || magic != "STRATA_HIPBLASLT_TUNING_V1") { - err = "invalid tuning header at line " + std::to_string(line_number); - return false; - } - if (arch != expected_arch) { - err = "tuning architecture mismatch: file=" + arch + " runtime=" + expected_arch; - return false; - } - if (version != expected_version) { - err = "hipBLASLt version mismatch: file=" + std::to_string(version) + - " runtime=" + std::to_string(expected_version); - return false; - } - arch_ = std::move(arch); - version_ = version; - saw_header = true; - continue; - } - - std::string type_name; - int n = 0, k = 0, ldy = 0, t_bucket = 0, solution_id = -1; - std::string extra; - if (!(row >> type_name >> n >> k >> ldy >> t_bucket >> solution_id) || (row >> extra) || - (type_name != "f16" && type_name != "bf16") || n <= 0 || k <= 0 || ldy < n || t_bucket <= 0 || - solution_id < 0) { - err = "invalid tuning row at line " + std::to_string(line_number); - return false; - } - TuningRow parsed; - parsed.type = type_name == "f16" ? InputType::f16 : InputType::bf16; - parsed.n = n; - parsed.k = k; - parsed.ldy = ldy; - parsed.t_bucket = t_bucket; - parsed.solution_id = solution_id; - for (const auto& existing : rows_) { - if (existing.type == parsed.type && existing.n == parsed.n && existing.k == parsed.k && - existing.ldy == parsed.ldy && existing.t_bucket == parsed.t_bucket) { - err = "duplicate tuning key at line " + std::to_string(line_number); - return false; - } - } - rows_.push_back(parsed); - } - if (!saw_header) { - err = "tuning file has no header"; - return false; - } - return true; - } - - const TuningRow* closest(InputType type, int n, int k, int ldy, int t) const { - const TuningRow* best = nullptr; - int64_t best_distance = std::numeric_limits::max(); - for (const auto& row : rows_) { - if (row.type != type || row.n != n || row.k != k || row.ldy != ldy) continue; - const int64_t distance = row.t_bucket >= t ? int64_t(row.t_bucket) - t : int64_t(t) - row.t_bucket; - if (distance < best_distance || - (distance == best_distance && (!best || row.t_bucket < best->t_bucket))) { - best = &row; - best_distance = distance; - } - } - return best; - } - - const std::vector& rows() const { return rows_; } - const std::string& arch() const { return arch_; } - int version() const { return version_; } - -private: - std::string arch_; - int version_ = 0; - std::vector rows_; -}; - -} // namespace strata::prefill::hipblaslt diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu deleted file mode 100644 index 870bf1c..0000000 --- a/src/prefill/kernels.cu +++ /dev/null @@ -1,1130 +0,0 @@ -// src/prefill/kernels.cu - see include/strata/prefill/kernels.hpp. -#include "strata/prefill/kernels.hpp" -#include "strata/kernels/mrope.hpp" -#include "strata/kernels/router_top10.hpp" - -#include -#include -#include - -#include -#include -#include -#include - -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 -// (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; - -__device__ __forceinline__ float warp_sum(float v) { -#pragma unroll - for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); - return v; -} -__device__ __forceinline__ float warp_max(float v) { -#pragma unroll - for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o)); - return v; -} -__device__ __forceinline__ uint16_t bf(float f) { - uint32_t u = __float_as_uint(f); - u += 0x7fffu + ((u >> 16) & 1u); - return (uint16_t) (u >> 16); -} -// The BF16 GEMMs' second operand (STRATA_PREFILL_BF16X2): what the BF16 image `hi` left out of f, itself in BF16. -// W.hi + W.lo carries ~16 mantissa bits of the activation - the decode path's FP32 x to within ~1e-5. -__device__ __forceinline__ uint16_t bf_lo(float f, uint16_t hi) { return bf(f - __uint_as_float((uint32_t) hi << 16)); } -__device__ __forceinline__ float sigm(float x) { return 1.0f / (1.0f + __expf(-x)); } -__device__ __forceinline__ uint16_t hf(float f) { return __half_as_ushort(__float2half_rn(f)); } -// A SwiGLU product for an FP16 GEMM: saturated, so a token with a massive activation cannot turn into inf and then -// NaN in the down projection (decode's q8_1 has room to ~8e6; FP16 ends at 65504). A NaN stays NaN (fminf/fmaxf -// would make it -65504 and hide where it came from); finite values below 65504 round exactly as before. -__device__ __forceinline__ uint16_t hf_sat(float f) { return hf(isnan(f) ? f : fminf(fmaxf(f, -65504.0f), 65504.0f)); } -// block-wide sum for blockDim.x <= 1024, result broadcast -__device__ float block_sum(float v, float* sh) { - const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; - v = warp_sum(v); - __syncthreads(); - if (lane == 0) sh[w] = v; - __syncthreads(); - const int nw = (blockDim.x + 31) >> 5; - float t = (threadIdx.x < nw) ? sh[threadIdx.x] : 0.0f; - if (w == 0) t = warp_sum(t); - if (threadIdx.x == 0) sh[0] = t; - __syncthreads(); - return sh[0]; -} -void check(const char* what) { - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { std::fprintf(stderr, "prefill %s: %s\n", what, cudaGetErrorString(e)); std::exit(1); } -} -unsigned blocks_for(int64_t n, int t = 256) { return (unsigned) ((n + t - 1) / t); } - -// ---------------------------------------------------------------- hyper-connection -__global__ void gr_norm_kernel(const float* __restrict__ R, const float* __restrict__ w, float eps, - float* __restrict__ xn, uint16_t* __restrict__ xn16, uint16_t* __restrict__ xn16_lo) { - __shared__ float sh[32]; - const int64_t row = blockIdx.x; // t * 4 + c - const int c = (int) (row % HC); - const float* r = R + row * N; - float ss = 0.0f; - for (int 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 (int d = threadIdx.x; d < N; d += blockDim.x) { - const float v = r[d] * rs * w[c * N + d]; - xn[row * N + d] = v; - const uint16_t h = bf(v); - xn16[row * N + d] = h; - if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h); - } -} -// F-1: the row scale only (and the BF16 image); gr_mix_r_kernel recomputes r * rs * w itself, in the same order, -// so the FP32 copy of the normalized rows (T x 10240 floats) is neither written nor read -__global__ void gr_norm_rs_kernel(const float* __restrict__ R, const float* __restrict__ w, float eps, - float* __restrict__ rs_out, uint16_t* __restrict__ xn16, - uint16_t* __restrict__ xn16_lo) { - __shared__ float sh[32]; - const int64_t row = blockIdx.x; // t * 4 + c - const int c = (int) (row % HC); - const float* r = R + row * N; - float ss = 0.0f; - for (int d = threadIdx.x; d < N; d += blockDim.x) ss += r[d] * r[d]; - const float rs = rsqrtf(block_sum(ss, sh) / (float) N + eps); - if (threadIdx.x == 0) rs_out[row] = rs; - for (int d = threadIdx.x; d < N; d += blockDim.x) { - const float v = r[d] * rs * w[c * N + d]; - const uint16_t h = bf(v); - xn16[row * N + d] = h; - if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h); - } -} -__global__ void gr_mix_r_kernel(const float* __restrict__ R, const float* __restrict__ rs, const float* __restrict__ w, - const float* __restrict__ g, float* __restrict__ mixed, uint16_t* __restrict__ mixed16, - int64_t T, uint16_t* __restrict__ mixed_h, uint16_t* __restrict__ mixed16_lo) { - 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; - float s = 0.0f; -#pragma unroll - for (int c = 0; c < HC; ++c) { - const int64_t j = t * D + c * N + d; - const float x = R[j] * rs[t * HC + c] * w[c * N + d]; // gr_norm_kernel's value, bit for bit - s = fmaf(x, sigm(g[j]), s); - } - s /= (float) HC; - mixed[i] = s; - if (mixed16) { - const uint16_t h = bf(s); - mixed16[i] = h; - if (mixed16_lo) mixed16_lo[i] = bf_lo(s, h); - } - if (mixed_h) mixed_h[i] = hf(s); -} -// F-2: gr_write_kernel for one row (t, c), then gr_norm_rs_kernel's reduction over it with the next half's norm -// weights - the same thread-to-element mapping (256 threads, stride 256) and block_sum, so rs and the BF16 image are -// the same bits, and R is not read back -constexpr int GRW_PER = (N + 255) / 256; -__global__ void __launch_bounds__(256) gr_write_norm_rs_kernel(float* __restrict__ R, const float* __restrict__ bo, - const float* __restrict__ inj, int64_t inj_ld, - const float* __restrict__ w, float eps, - float* __restrict__ rs_out, uint16_t* __restrict__ xn16, - uint16_t* __restrict__ xn16_lo) { - __shared__ float sh[32]; - const int64_t row = blockIdx.x; // t * 4 + c - const int64_t t = row / HC; - const int c = (int) (row % HC); - float* r = R + row * N; - const float sc = 2.0f * sigm(inj[t * inj_ld + c] / (float) HC); - float v[GRW_PER]; - float ss = 0.0f; - int k = 0; -#pragma unroll - for (int d = threadIdx.x; d < N; d += 256, ++k) { - const float x = fmaf(bo[t * N + d], sc, r[d]); - r[d] = x; - v[k] = x; - ss += x * x; - } - const float rs = rsqrtf(block_sum(ss, sh) / (float) N + eps); - if (threadIdx.x == 0) rs_out[row] = rs; - k = 0; -#pragma unroll - for (int d = threadIdx.x; d < N; d += 256, ++k) { - const float x = v[k] * rs * w[c * N + d]; - const uint16_t h = bf(x); - xn16[row * N + d] = h; - if (xn16_lo) xn16_lo[row * N + d] = bf_lo(x, h); - } -} -__global__ void gr_silu_kernel(const float* __restrict__ lo, uint16_t* __restrict__ lo16, uint16_t* __restrict__ lo16_lo, - int64_t n) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n) return; - const float x = lo[i] / (float) HC; - const float v = x / (1.0f + __expf(-x)); - const uint16_t h = bf(v); - lo16[i] = h; - if (lo16_lo) lo16_lo[i] = bf_lo(v, h); -} -__global__ void gr_mix_kernel(const float* __restrict__ xn, const float* __restrict__ g, float* __restrict__ mixed, - uint16_t* __restrict__ mixed16, int64_t T, uint16_t* __restrict__ mixed_h, - uint16_t* __restrict__ mixed16_lo) { - 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; - float s = 0.0f; -#pragma unroll - for (int c = 0; c < HC; ++c) { - const int64_t j = t * D + c * N + d; - s = fmaf(xn[j], sigm(g[j]), s); - } - s /= (float) HC; - mixed[i] = s; - if (mixed16) { - const uint16_t h = bf(s); - mixed16[i] = h; - if (mixed16_lo) mixed16_lo[i] = bf_lo(s, h); - } - if (mixed_h) mixed_h[i] = hf(s); -} -__global__ void gr_write_kernel(float* __restrict__ R, const float* __restrict__ bo, const float* __restrict__ inj, - int64_t inj_ld, int64_t T) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= T * D) return; - const int64_t t = i / D, c = (i % D) / N, d = i % N; - R[i] = fmaf(bo[t * N + d], 2.0f * sigm(inj[t * inj_ld + c] / (float) HC), R[i]); -} -__global__ void gr_broadcast_kernel(const float* __restrict__ e, float* __restrict__ R, int64_t T) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= T * D) return; - const int64_t t = i / D, d = i % N; - R[i] = e[t * N + d]; -} - -// ---------------------------------------------------------------- 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 __device__ __forceinline__ float gdn_gate(float z) { return SILU ? z * sigm(z) : sigm(z); } - -template -__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) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= T * HV) return; - const int64_t t = i / HV, h = i % HV; - const float v = ab[t * 2 * HV + h] + dt[h]; - gate[i] = (v > 20.0f ? v : log1pf(__expf(v))) * ssm_a[h]; - beta[i] = sigm(ab[t * 2 * HV + HV + h]); -} -// one thread per channel, walks the chunk; then a second kernel normalises -template -__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; - if (c >= C) return; - float v0 = hist[c * 3], v1 = hist[c * 3 + 1], v2 = hist[c * 3 + 2]; - const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3]; - for (int64_t t = 0; t < T; ++t) { - const float x = qkv[t * C + c]; - const float s = v0 * w0 + v1 * w1 + v2 * w2 + x * w3; - h[t * C + c] = s / (1.0f + __expf(-s)); - v0 = v1; v1 = v2; v2 = x; - } - hist[c * 3] = v0; hist[c * 3 + 1] = v1; hist[c * 3 + 2] = v2; -} -// C-3: the same 4-tap causal conv, tiled over tokens: thread (c, tile) reads its tile's 3 predecessors from the -// 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 -__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; - if (c >= C) return; - const int64_t t0 = (int64_t) blockIdx.y * CONV_TILE; - if (t0 >= T) return; - const int64_t t1 = t0 + CONV_TILE < T ? t0 + CONV_TILE : T; - auto input = [&](int64_t t) -> float { return t >= 0 ? qkv[t * C + c] : hist[c * 3 + (int) (t + 3)]; }; - float v0 = input(t0 - 3), v1 = input(t0 - 2), v2 = input(t0 - 1); - const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3]; - for (int64_t t = t0; t < t1; ++t) { - const float x = qkv[t * C + c]; - const float s = v0 * w0 + v1 * w1 + v2 * w2 + x * w3; - h[t * C + c] = s / (1.0f + __expf(-s)); - v0 = v1; v1 = v2; v2 = x; - } -} -// the history after the chunk: its last three inputs (the older history where the chunk is shorter than 3) -template -__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; - float v[3]; - for (int k = 0; k < 3; ++k) { - const int64_t t = T - 3 + k; - v[k] = t >= 0 ? qkv[t * C + c] : hist[c * 3 + (int) (t + 3)]; - } - hist[c * 3] = v[0]; hist[c * 3 + 1] = v[1]; hist[c * 3 + 2] = v[2]; -} -template -__global__ void gdn_l2_kernel(float* __restrict__ h, float eps) { - // 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; - const float v = x[threadIdx.x]; - float sq = warp_sum(v * v); - __shared__ float part[4]; - if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sq; - __syncthreads(); - const float ss = part[0] + part[1] + part[2] + part[3]; - x[threadIdx.x] = v * rsqrtf(ss + eps); -} -constexpr int RG = 4, RPG = S / RG; -template -__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, - const float* __restrict__ gamma, float eps, - float* __restrict__ y, uint16_t* __restrict__ y16, int64_t T) { - __shared__ float sk[S], sq[S], red[RG][S], wsum[16]; - const int head = blockIdx.x, col = threadIdx.x, rg = threadIdx.y, tid = rg * S + col; - const int qh = head % HK; - float s[RPG]; - float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col; - const size_t rs = (size_t) HV * S; -#pragma unroll - for (int r = 0; r < RPG; ++r) s[r] = base[r * rs]; - const float g_col = gamma[col]; - for (int64_t t = 0; t < T; ++t) { - const float* ht = h + t * C; - __syncthreads(); - if (tid < S) { sq[tid] = ht[qh * S + tid]; sk[tid] = ht[HK * S + qh * S + tid]; } - __syncthreads(); - const float g = __expf(gate[t * HV + head]); - float kv = 0.0f; -#pragma unroll - for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); - red[rg][col] = kv; - __syncthreads(); - const float kv_col = red[0][col] + red[1][col] + red[2][col] + red[3][col]; - const float delta = (ht[2 * HK * S + head * S + col] - g * kv_col) * beta[t * HV + head]; - float o = 0.0f; -#pragma unroll - for (int r = 0; r < RPG; ++r) { - s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); - o = fmaf(s[r], sq[rg * RPG + r], o); - } - __syncthreads(); - red[rg][col] = o; - __syncthreads(); - float oc = 0.0f, sp = 0.0f; - if (rg == 0) { - oc = (red[0][col] + red[1][col] + red[2][col] + red[3][col]) * rsqrtf((float) S); - sp = oc * oc; - } - sp = warp_sum(sp); - if ((tid & 31) == 0) wsum[tid >> 5] = sp; - __syncthreads(); - if (rg == 0) { - const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; - const float v = oc * rsqrtf(ss / (float) S + eps) * g_col * gdn_gate(z[t * HV * S + head * S + col]); - y[t * HV * S + head * S + col] = v; - y16[t * HV * S + head * S + col] = hf(v); - } - } -#pragma unroll - for (int r = 0; r < RPG; ++r) base[r * rs] = s[r]; -} - -// D-2: the recurrence with the value columns split over 4 blocks per head (4x the blocks of the kernel above, a -// quarter of its threads per __syncthreads), and the output norm - the only step that couples the head's columns - -// 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 -__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, - float* __restrict__ oc_out, int64_t T) { - __shared__ float sk[S], sq[S], red[RG][CB]; - const int head = blockIdx.x / NCB, cb = blockIdx.x % NCB; - const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c; - const int qh = head % HK; - float s[RPG]; - float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col; - const size_t rs = (size_t) HV * S; -#pragma unroll - for (int r = 0; r < RPG; ++r) s[r] = base[r * rs]; - for (int64_t t = 0; t < T; ++t) { - const float* ht = h + t * C; - __syncthreads(); - if (tid < S) { sq[tid] = ht[qh * S + tid]; sk[tid] = ht[HK * S + qh * S + tid]; } - __syncthreads(); - const float g = __expf(gate[t * HV + head]); - float kv = 0.0f; -#pragma unroll - for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); - red[rg][c] = kv; - __syncthreads(); - const float kv_col = red[0][c] + red[1][c] + red[2][c] + red[3][c]; - const float delta = (ht[2 * HK * S + head * S + col] - g * kv_col) * beta[t * HV + head]; - float o = 0.0f; -#pragma unroll - for (int r = 0; r < RPG; ++r) { - s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); - o = fmaf(s[r], sq[rg * RPG + r], o); - } - __syncthreads(); - red[rg][c] = o; - __syncthreads(); - if (rg == 0) oc_out[t * HV * S + head * S + col] = (red[0][c] + red[1][c] + red[2][c] + red[3][c]) * rsqrtf((float) S); - } -#pragma unroll - for (int r = 0; r < RPG; ++r) base[r * rs] = s[r]; -} -// 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 -__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, - float* __restrict__ oc_out, int64_t T) { - constexpr int NT = CB * RG, LPT = S / NT; // threads, q/k rows loaded per thread - __shared__ float sk[S], sq[S], red[RG][CB]; - const int head = blockIdx.x / NCB, cb = blockIdx.x % NCB; - const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c; - const int qh = head % HK; - float s[RPG]; - float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col; - const size_t rs = (size_t) HV * S; -#pragma unroll - for (int r = 0; r < RPG; ++r) s[r] = base[r * rs]; - float nq[LPT], nk[LPT], nv = 0.0f, ng = 0.0f, nb = 0.0f; - auto fetch = [&](int64_t t) { - const float* ht = h + t * C; -#pragma unroll - for (int u = 0; u < LPT; ++u) { nq[u] = ht[qh * S + tid + u * NT]; nk[u] = ht[HK * S + qh * S + tid + u * NT]; } - nv = ht[2 * HK * S + head * S + col]; - ng = gate[t * HV + head]; - nb = beta[t * HV + head]; - }; - if (T > 0) fetch(0); - for (int64_t t = 0; t < T; ++t) { - float cq[LPT], ck[LPT]; -#pragma unroll - for (int u = 0; u < LPT; ++u) { cq[u] = nq[u]; ck[u] = nk[u]; } - const float cv = nv, cg = ng, cbt = nb; - __syncthreads(); -#pragma unroll - for (int u = 0; u < LPT; ++u) { sq[tid + u * NT] = cq[u]; sk[tid + u * NT] = ck[u]; } - __syncthreads(); - if (t + 1 < T) fetch(t + 1); - const float g = __expf(cg); - float kv = 0.0f; -#pragma unroll - for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); - red[rg][c] = kv; - __syncthreads(); - const float kv_col = red[0][c] + red[1][c] + red[2][c] + red[3][c]; - const float delta = (cv - g * kv_col) * cbt; - float o = 0.0f; -#pragma unroll - for (int r = 0; r < RPG; ++r) { - s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); - o = fmaf(s[r], sq[rg * RPG + r], o); - } - __syncthreads(); - red[rg][c] = o; - __syncthreads(); - if (rg == 0) oc_out[t * HV * S + head * S + col] = (red[0][c] + red[1][c] + red[2][c] + red[3][c]) * rsqrtf((float) S); - } -#pragma unroll - for (int r = 0; r < RPG; ++r) base[r * rs] = s[r]; -} -#if !defined(__HIPCC__) -// The recurrence with one thread for the three value heads that share a key head (head % HK): column c of heads -// qh, qh + 16 and qh + 32, row group rg. gdn_rec_cols_pipe_kernel spends its time in shared memory, not in -// arithmetic: every thread of a warp needs the same 32 q and k values per token (the k twice), and a warp receives one -// such broadcast value per clock however wide the load. Here every q/k value a thread loads feeds three heads, and a -// token's k row goes into registers once for both of its uses. The inputs come in blocks of GDN_TB tokens, copied to -// shared memory by cp.async while the block before computes (one token ahead is shorter than a load from L2 takes), -// and the two cross-row-group sums have their own arrays, so a token needs 2 __syncthreads instead of 5: the second -// one of a token orders every read of rkv before the next token's writes, the next token's first one every read of ro -// before the writes after it. 64 blocks instead of 192. Per value head and column the same arithmetic in the same -// order: the same bits (src/prefill/gdn_rec_parity.cu checks them and times the variants: 1.41x on a 4080 Super). -// sm_80+ cards that hold its 64 blocks at once (gdn_keyhead_ok); STRATA_GDN_KEYHEAD=0: gdn_rec_cols_pipe_kernel. -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800 -#define STRATA_GDN_CP_ASYNC 0 // Turing builds: plain copies (never launched there, see gdn_keyhead_ok) -#else -#define STRATA_GDN_CP_ASYNC 1 -#endif -__device__ __forceinline__ void gdn_cp4(float* smem, const float* gmem) { -#if STRATA_GDN_CP_ASYNC - asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem)); -#else - *smem = *gmem; -#endif -} -__device__ __forceinline__ void gdn_cp16(float* smem, const float* gmem) { -#if STRATA_GDN_CP_ASYNC - asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem)); -#else - *reinterpret_cast(smem) = *reinterpret_cast(gmem); -#endif -} -__device__ __forceinline__ void gdn_cp_commit() { -#if STRATA_GDN_CP_ASYNC - asm volatile("cp.async.commit_group;\n" ::); -#endif -} -__device__ __forceinline__ void gdn_cp_wait_prev() { // every group but the newest has landed -#if STRATA_GDN_CP_ASYNC - asm volatile("cp.async.wait_group 1;\n" ::); -#endif -} -constexpr int GDN_TB = 8; // tokens per staged block -template -__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]; - __shared__ __align__(16) float sv[2][TB][VPK][CB]; - __shared__ float sg[2][TB][VPK], sb[2][TB][VPK], rkv[VPK][RG][CB], ro[VPK][RG][CB]; - const int qh = blockIdx.x / NCB, cb = blockIdx.x % NCB; - const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c; - float s[VPK][RPG]; - const size_t rs = (size_t) HV * S; -#pragma unroll - for (int j = 0; j < VPK; ++j) { - const float* base = state + ((size_t) (rg * RPG) * HV + qh + j * HK) * S + col; -#pragma unroll - for (int r = 0; r < RPG; ++r) s[j][r] = base[r * rs]; - } - const int64_t nblk = (T + TB - 1) / TB; - auto stage = [&](int64_t k) { // tokens [k * TB, k * TB + TB) into buffer k & 1 - const int bb = (int) (k & 1); - const int64_t t0 = k * TB; - for (int p = tid; p < TB * 2 * QKP; p += NT) { - const int i = p / (2 * QKP), w = p % (2 * QKP), isk = w / QKP, jj = (w % QKP) * 4; - if (t0 + i < T) - gdn_cp16(isk ? &sk[bb][i][jj] : &sq[bb][i][jj], h + (t0 + i) * C + (isk ? HK * S : 0) + qh * S + jj); - } - for (int p = tid; p < TB * VPK * VP; p += NT) { - const int i = p / (VPK * VP), w = p % (VPK * VP), j = w / VP, jj = (w % VP) * 4; - if (t0 + i < T) - gdn_cp16(&sv[bb][i][j][jj], h + (t0 + i) * C + 2 * HK * S + (qh + j * HK) * S + cb * CB + jj); - } - for (int p = tid; p < 2 * TB * VPK; p += NT) { - const int isb = p / (TB * VPK), w = p % (TB * VPK), i = w / VPK, j = w % VPK; - if (t0 + i < T) - gdn_cp4(isb ? &sb[bb][i][j] : &sg[bb][i][j], (isb ? beta : gate) + (t0 + i) * HV + qh + j * HK); - } - }; - if (nblk > 0) stage(0); - gdn_cp_commit(); - for (int64_t k = 0; k < nblk; ++k) { - // buffer (k + 1) & 1 was read by block k - 1, whose last token's second __syncthreads every thread has passed - if (k + 1 < nblk) stage(k + 1); - gdn_cp_commit(); - gdn_cp_wait_prev(); - __syncthreads(); - const int bb = (int) (k & 1); - const int n = (int) ((T - k * TB) < TB ? (T - k * TB) : TB); - for (int i = 0; i < n; ++i) { - const int64_t t = k * TB + i; - float kc[RPG]; -#pragma unroll - for (int r = 0; r < RPG; ++r) kc[r] = sk[bb][i][rg * RPG + r]; - float g[VPK], kv[VPK], delta[VPK], o[VPK]; -#pragma unroll - for (int j = 0; j < VPK; ++j) { g[j] = __expf(sg[bb][i][j]); kv[j] = 0.0f; o[j] = 0.0f; } -#pragma unroll - for (int r = 0; r < RPG; ++r) -#pragma unroll - for (int j = 0; j < VPK; ++j) kv[j] = fmaf(s[j][r], kc[r], kv[j]); -#pragma unroll - for (int j = 0; j < VPK; ++j) rkv[j][rg][c] = kv[j]; - __syncthreads(); -#pragma unroll - for (int j = 0; j < VPK; ++j) { - const float kv_col = rkv[j][0][c] + rkv[j][1][c] + rkv[j][2][c] + rkv[j][3][c]; - delta[j] = (sv[bb][i][j][c] - g[j] * kv_col) * sb[bb][i][j]; - } -#pragma unroll - for (int r = 0; r < RPG; ++r) { - const float qr = sq[bb][i][rg * RPG + r]; -#pragma unroll - for (int j = 0; j < VPK; ++j) { - s[j][r] = fmaf(g[j], s[j][r], kc[r] * delta[j]); - o[j] = fmaf(s[j][r], qr, o[j]); - } - } -#pragma unroll - for (int j = 0; j < VPK; ++j) ro[j][rg][c] = o[j]; - __syncthreads(); - if (rg < VPK) // row group j writes head j's output - oc_out[t * HV * S + (qh + rg * HK) * S + col] = - (ro[rg][0][c] + ro[rg][1][c] + ro[rg][2][c] + ro[rg][3][c]) * rsqrtf((float) S); - } - } -#pragma unroll - for (int j = 0; j < VPK; ++j) { - float* base = state + ((size_t) (rg * RPG) * HV + qh + j * HK) * S + col; -#pragma unroll - for (int r = 0; r < RPG; ++r) base[r * rs] = s[j][r]; - } -} -// gdn_rec_kh_kernel where it pays: a CUDA card with cp.async (sm_80+) that holds all 64 of its blocks at once (each -// walks the whole chunk, so blocks left for a second wave would double the time). The busiest SM sets the pace: from -// 64 SMs up this kernel has one block per SM, below that two on some SMs, while the kernel before has ceil(192 / SMs). -// With the engine's grids on fewer SMs (gdn_rec_parity --bench), on a 4080 SUPER / a 3090: 1.40-1.42x / 1.28-1.29x at -// 64 SMs and more, 1.02-1.04x / 1.03-1.06x at 48 to 63 (two blocks against four: a draw, slower on neither), -// 1.28-1.31x / 1.28-1.30x at 39 to 47, 1.53-1.57x / 1.54-1.55x at 32 to 38. Per call, from the current device (a -// layer split can mix cards). Per geometry: the grid is HK * NCB blocks either way (64 at 16 key heads). -template -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; - static int known[64] = {}; // per device: 0 not asked yet, 1 yes, 2 no - int dev = 0; - if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } - if (known[dev] == 0) { - 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) == - cudaSuccess && - (int64_t) per_sm * sms >= (int64_t) HK * NCB; - if (!yes) cudaGetLastError(); - known[dev] = yes ? 1 : 2; - } - return known[dev] == 1; -} -#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 -__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) { - __shared__ float wsum[4]; - const int64_t t = blockIdx.x; - const int head = blockIdx.y, col = threadIdx.x; - const size_t at = (size_t) t * HV * S + (size_t) head * S + col; - const float oc = y[at]; - float sp = warp_sum(oc * oc); - if ((col & 31) == 0) wsum[col >> 5] = sp; - __syncthreads(); - const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; - const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * gdn_gate(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 struct GdnTag { static constexpr int HV = HV_, HK = HK_, C = C_; }; -template 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 -__global__ void route_kernel(const float* __restrict__ logits, int32_t* __restrict__ ids, float* __restrict__ wout, - 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; - const float* lg = logits + t * (REG * 32); - float v[REG]; -#pragma unroll - for (int i = 0; i < REG; ++i) v[i] = lg[lane + i * 32]; - float mx = -INFINITY; -#pragma unroll - for (int i = 0; i < REG; ++i) mx = fmaxf(mx, v[i]); - mx = warp_max(mx); - float sum = 0.0f; -#pragma unroll - for (int i = 0; i < REG; ++i) { v[i] = expf(v[i] - mx); sum += v[i]; } - const float rcp = 1.0f / warp_sum(sum); -#pragma unroll - for (int i = 0; i < REG; ++i) { v[i] *= rcp; if (isnan(v[i])) v[i] = -FLT_MAX; } - float selected = 0.0f, selected_sum = 0.0f; - for (int rank = 0; rank < k; ++rank) { - float best = v[0]; - int ex = lane; -#pragma unroll - for (int i = 1; i < REG; ++i) if (v[i] > best) { best = v[i]; ex = lane + i * 32; } -#pragma unroll - for (int m = 16; m; m >>= 1) { - const float ob = __shfl_xor_sync(0xffffffffu, best, m); - const int oi = __shfl_xor_sync(0xffffffffu, ex, m); - if (ob > best || (ob == best && oi < ex)) { best = ob; ex = oi; } - } - if ((ex & 31) == lane) { v[ex / 32] = -INFINITY; selected_sum += best; } - if (lane == 0) ids[t * k + rank] = ex; - if (rank == lane) selected = best; - } - selected_sum = fmaxf(warp_sum(selected_sum), 6.103515625e-5f); - 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 -__global__ void blob_dequant_kernel(const uint8_t* __restrict__ blob, uint16_t* __restrict__ gu16, - uint16_t* __restrict__ d16) { - constexpr size_t O_D_CODES = (size_t) 1280 * 640, O_GU_SC = O_D_CODES + (size_t) 2560 * 160, - O_D_SC = O_GU_SC + (size_t) 1280 * 40 * 2; - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; // one thread per 4 weights (one code byte) - const int64_t n_gu = 1280LL * 640, n_d = 2560LL * 160; - if (i < n_gu) { - const int64_t row = i / 640, byte = i % 640; - const uint8_t c = blob[row * 640 + byte]; - const uint8_t* sp = blob + O_GU_SC + (size_t) (row * 40 + (byte * 4) / 64) * 2; - const float d = __half2float(__ushort_as_half((uint16_t) (sp[0] | (sp[1] << 8)))); - uint16_t* o = gu16 + row * 2560 + byte * 4; -#pragma unroll - for (int k = 0; k < 4; ++k) { const float v = (float) (((c >> (2 * k)) & 3) - 1) * d; o[k] = HALF ? hf(v) : bf(v); } - } else if (i < n_gu + n_d) { - const int64_t j = i - n_gu, row = j / 160, byte = j % 160; - const uint8_t c = blob[O_D_CODES + row * 160 + byte]; - const uint8_t* sp = blob + O_D_SC + (size_t) (row * 10 + (byte * 4) / 64) * 2; - const float d = __half2float(__ushort_as_half((uint16_t) (sp[0] | (sp[1] << 8)))); - uint16_t* o = d16 + row * 640 + byte * 4; -#pragma unroll - for (int k = 0; k < 4; ++k) { const float v = (float) (((c >> (2 * k)) & 3) - 1) * d; o[k] = HALF ? hf(v) : bf(v); } - } -} -__global__ void swiglu_il_kernel(const float* __restrict__ gu, uint16_t* __restrict__ h16, int64_t n, int64_t n_ff) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n * n_ff) return; - const int64_t r = i / n_ff, k = i % n_ff; - const float g = gu[r * 2 * n_ff + 2 * k], u = gu[r * 2 * n_ff + 2 * k + 1]; - h16[i] = hf_sat(g / (1.0f + __expf(-g)) * u); -} -__global__ void swiglu_pair_kernel(const float* __restrict__ g, const float* __restrict__ u, uint16_t* __restrict__ h16, - int64_t n) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n) return; - const float a = g[i]; - h16[i] = hf_sat(a / (1.0f + __expf(-a)) * u[i]); -} -__global__ void gather_rows16_kernel(const uint16_t* __restrict__ x, const int32_t* __restrict__ src, - uint16_t* __restrict__ dst, int64_t n, int64_t width) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; // one uint4 (8 bf16) - const int64_t per = width / 8; - if (i >= n * per) return; - const int64_t r = i / per, j = i % per; - reinterpret_cast(dst)[r * per + j] = reinterpret_cast(x)[(int64_t) src[r] * per + j]; -} -// the routed sum in rank order (as the decode combine and llama.cpp's sum over the top-k), plus the gated shared expert -__global__ void moe_combine_kernel(const float* __restrict__ Dm, const int32_t* __restrict__ slot, - const float* __restrict__ w, const float* __restrict__ shared, - const float* __restrict__ sg, float* __restrict__ bo, int64_t T, int64_t n, int k) { - const 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; - float s = 0.0f; - for (int j = 0; j < k; ++j) s = fmaf(w[t * k + j], Dm[(int64_t) slot[t * k + j] * n + d], s); - bo[i] = s + shared[i] * sigm(sg[t]); -} - -// ---------------------------------------------------------------- QSA helpers -__global__ void rms_rows_kernel(float* __restrict__ x, const float* __restrict__ w, int64_t cols, int64_t ld, float eps) { - __shared__ float sh[32]; - float* r = x + (int64_t) blockIdx.x * ld; - float ss = 0.0f; - for (int64_t c = threadIdx.x; c < cols; c += blockDim.x) ss += r[c] * r[c]; - const float s = rsqrtf(block_sum(ss, sh) / (float) cols + eps); - __syncthreads(); - for (int64_t c = threadIdx.x; c < cols; c += blockDim.x) r[c] = s * r[c] * w[c]; -} -// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table. The host launches whenever -// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it; -// with it merely skipped at run time, the compiled default path changed its results). -template -__global__ void rope_kernel(float* __restrict__ x, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, - float theta_scale, float freq_scale, float corr_low, float corr_high, - float ext_factor, float mscale, const int32_t* __restrict__ mtab, - strata::kernels::RopeTab rt) { - const int64_t row = blockIdx.x; // t * heads + h - const int pair = threadIdx.x; // 0..31 - const int64_t t = row / heads, h = row % heads; - float* p = x + t * ld + h * dim; - float c, s; - if (!(TAB && strata::kernels::rope_tab_cs(rt, strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair), pair, c, - s))) { - const float theta_extrap = - (float) strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair) * powf(theta_scale, (float) pair); - strata::kernels::rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, - pair, c, s); - } - const float a = p[pair], b = p[pair + 32]; - p[pair] = a * c - b * s; - p[pair + 32] = a * s + b * c; -} -// attn_q is [n_head, 2, 256] per token: the query is the first 256 of each head's 512, the gate the second (both models) -__global__ void split_q_kernel(const float* __restrict__ qf, float* __restrict__ q, int64_t T, int64_t n_head) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= T * n_head * 256) return; - const int64_t t = i / (n_head * 256), h = (i / 256) % n_head, d = i % 256; - q[i] = qf[t * n_head * 512 + h * 512 + d]; -} -__global__ void gate_attn_kernel(const float* __restrict__ a, const float* __restrict__ qf, uint16_t* __restrict__ o16, - int64_t T, int64_t n_head) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= T * n_head * 256) return; - const int64_t t = i / (n_head * 256), h = (i / 256) % n_head, d = i % 256; - o16[i] = hf(a[i] * (1.0f / (1.0f + expf(-qf[t * n_head * 512 + h * 512 + 256 + d])))); -} - -// one block per (token, kv head, 64-value group); 64 threads. KV streaming: the pool page only if the block is -// resident (table >= 0), and the host copy and the prompt path's staging pool (both identity layout) when given. -__global__ void kv_append_kernel(const float* __restrict__ K, const float* __restrict__ V, int64_t pos0, - const int32_t* __restrict__ table, int64_t page_size, uint16_t* k_pool, - uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, - strata::kernels::KvHostPools host, strata::kernels::KvHostPools stage) { - const int64_t t = blockIdx.x; - const int kvh = blockIdx.y, g = blockIdx.z >> 1; - const bool is_v = (blockIdx.z & 1) != 0; - const int d = g * 64 + threadIdx.x; - const float x = (is_v ? V : K)[t * 512 + kvh * 256 + d]; - const int64_t pos = pos0 + t; - const int64_t page = table[pos / page_size]; - const int64_t row = (page * 2 + kvh) * page_size + pos % page_size; - const int64_t row_id = ((pos / page_size) * 2 + kvh) * page_size + pos % page_size; - if (k_pool != nullptr) { - const uint16_t h = hf(x); - if (page >= 0) (is_v ? v_pool : k_pool)[row * 256 + d] = h; - if (host.k_pool != nullptr) (is_v ? host.v_pool : host.k_pool)[row_id * 256 + d] = h; - if (stage.k_pool != nullptr) (is_v ? stage.v_pool : stage.k_pool)[row_id * 256 + d] = h; - return; - } - float a = fabsf(x); - for (int o = 16; o > 0; o >>= 1) a = fmaxf(a, __shfl_xor_sync(0xffffffffu, a, o)); - __shared__ float wm[2]; - if ((threadIdx.x & 31) == 0) wm[threadIdx.x >> 5] = a; - __syncthreads(); - const float amax = fmaxf(wm[0], wm[1]); - const uint16_t sb = hf(amax / 127.0f); - const float sf = __half2float(__ushort_as_half(sb)); - int q = 0; - if (sf > 0.0f) { q = __float2int_rn(x / sf); q = q < -127 ? -127 : (q > 127 ? 127 : q); } - if (page >= 0) { - (is_v ? v_q : k_q)[row * 256 + d] = (int8_t) q; - if (threadIdx.x == 0) (is_v ? v_scale : k_scale)[row * 4 + g] = sb; - } - if (host.k_q != nullptr) { - (is_v ? host.v_q : host.k_q)[row_id * 256 + d] = (int8_t) q; - if (threadIdx.x == 0) (is_v ? host.v_scale : host.k_scale)[row_id * 4 + g] = sb; - } - if (stage.k_q != nullptr) { - (is_v ? stage.v_q : stage.k_q)[row_id * 256 + d] = (int8_t) q; - if (threadIdx.x == 0) (is_v ? stage.v_scale : stage.k_scale)[row_id * 4 + g] = sb; - } -} -__global__ void to_f16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, int64_t n) { - for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) - y[i] = hf(x[i]); -} -__global__ void round_f16_kernel(const float* __restrict__ x, float* __restrict__ y, int64_t n) { - for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) - y[i] = __half2float(__float2half_rn(x[i])); -} -__global__ void to_bf16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, uint16_t* __restrict__ ylo, - int64_t n) { - for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) { - const uint16_t h = bf(x[i]); - y[i] = h; - if (ylo) ylo[i] = bf_lo(x[i], h); - } -} - -} // namespace - -void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const int32_t* page_table, int64_t page_size, - uint16_t* k_pool, uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, - void* stream, const strata::kernels::KvHostPools* host, const strata::kernels::KvHostPools* stage) { - if (T <= 0) return; - kv_append_kernel<<>>( - K, V, pos0, page_table, page_size, k_pool, v_pool, k_q, v_q, k_scale, v_scale, - host ? *host : strata::kernels::KvHostPools{}, stage ? *stage : strata::kernels::KvHostPools{}); - check("kv_append"); -} -void to_f16(const float* x, uint16_t* y, int64_t n, void* stream) { - if (n <= 0) return; - to_f16_kernel<<<(unsigned) ((n + 255) / 256 < 4096 ? (n + 255) / 256 : 4096), 256, 0, (cudaStream_t) stream>>>(x, y, n); - check("to_f16"); -} -void round_f16(const float* x, float* y, int64_t n, void* stream) { - if (n <= 0) return; - round_f16_kernel<<<(unsigned) ((n + 255) / 256 < 4096 ? (n + 255) / 256 : 4096), 256, 0, (cudaStream_t) stream>>>(x, y, n); - check("round_f16"); -} -void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream, uint16_t* ylo) { - if (n <= 0) return; - to_bf16_kernel<<<(unsigned) ((n + 255) / 256 < 4096 ? (n + 255) / 256 : 4096), 256, 0, (cudaStream_t) stream>>>(x, y, ylo, n); - check("to_bf16"); -} - -void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream, - uint16_t* xn16_lo) { - gr_norm_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, xn, xn16, xn16_lo); - check("gr_norm"); -} -void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream, - uint16_t* xn16_lo) { - gr_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, rs, xn16, xn16_lo); - check("gr_norm_rs"); -} -void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16, - int64_t T, void* stream, uint16_t* mixed_h, uint16_t* mixed16_lo) { - gr_mix_r_kernel<<>>(R, rs, w_norm, gated, mixed, mixed16, T, - mixed_h, mixed16_lo); - check("gr_mix_r"); -} -void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps, - float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo) { - gr_write_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, bo, inj, inj_ld, w_norm_next, eps, - rs, xn16, xn16_lo); - check("gr_write_norm_rs"); -} -void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo) { - gr_silu_kernel<<>>(lo, lo16, lo16_lo, T * LR); - check("gr_silu"); -} -void gr_mix(const float* xn, const float* gated, float* mixed, uint16_t* mixed16, int64_t T, void* stream, - uint16_t* mixed_h, uint16_t* mixed16_lo) { - gr_mix_kernel<<>>(xn, gated, mixed, mixed16, T, mixed_h, mixed16_lo); - check("gr_mix"); -} -void gr_write(float* R, const float* bo, const float* inj, int64_t inj_ld, int64_t T, void* stream) { - gr_write_kernel<<>>(R, bo, inj, inj_ld, T); - check("gr_write"); -} -void gr_broadcast(const float* e, float* R, int64_t T, void* stream) { - gr_broadcast_kernel<<>>(e, R, T); - check("gr_broadcast"); -} -bool gdn_geometry_supported(int hv, int hk, int c) { - return (hv == 48 && hk == 16 && c == 10240) || (hv == 32 && hk == 16 && c == 8192); -} -void gdn_gates(const float* ab, const float* dt, const float* ssm_a, float* gate, float* beta, int64_t T, const GdnGeom& g, - void* stream) { - gdn_dispatch(g, "gdn_gates", [&](auto tag) { - constexpr int HV = decltype(tag)::HV; - gdn_gates_kernel<<>>(ab, dt, ssm_a, gate, beta, T); - }); - check("gdn_gates"); -} -void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, int64_t T, float eps, const GdnGeom& g, - void* stream) { - static const bool serial = std::getenv("STRATA_GDN_CONV_SERIAL") != nullptr; // the old walk (A/B) - gdn_dispatch(g, "gdn_conv", [&](auto tag) { - constexpr int HK = decltype(tag)::HK, C = decltype(tag)::C; - if (serial || T <= CONV_TILE) { - gdn_conv_kernel<<>>(history, qkv, conv_w, h, T); - } else { - gdn_conv_tiled_kernel<<>>(history, qkv, conv_w, h, T); - gdn_conv_hist_kernel<<>>(history, qkv, T); - } - gdn_l2_kernel<<>>(h, eps); - }); - check("gdn_conv"); -} -void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z, - const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, const GdnGeom& g, void* stream) { - static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr; // the one-block-per-head kernel (A/B) - static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }(); - const cudaStream_t cs = (cudaStream_t) stream; - gdn_dispatch(g, "gdn_recurrence", [&](auto tag) { - constexpr int HV = decltype(tag)::HV, HK = decltype(tag)::HK, C = decltype(tag)::C; - const bool silu = g.gate == strata::kernels::GdnGate::Silu; - if (serial || T <= 0) { - if (silu) - gdn_rec_kernel<<>>(state, h, gate, beta, z, gamma, eps, y, y16, T); - else - gdn_rec_kernel<<>>(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<<>>(state, h, gate, beta, y, T); - else -#endif - if (pipe) // the software-pipelined loads (same bits) - gdn_rec_cols_pipe_kernel<<>>(state, h, gate, beta, y, T); - else - gdn_rec_cols_kernel<<>>(state, h, gate, beta, y, T); - if (silu) gdn_out_norm_kernel<<>>(z, gamma, eps, y, y16); - else gdn_out_norm_kernel<<>>(z, gamma, eps, y, y16); - }); - check("gdn_recurrence"); -} -void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, int64_t k, void* stream) { - if (k < 1 || k > 32 || k > n_expert) { // Prefill::init refuses this first, with an error string - std::fprintf(stderr, "prefill route: top-%lld of %lld experts (k must be 1..32 and at most n_expert)\n", - (long long) k, (long long) n_expert); - std::exit(1); - } - if (n_expert == 512) - 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, (int) k); - else - 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<<>>(blob, gu16, down16); - check("blob_dequant"); -} -void blob_dequant_f16(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream) { - blob_dequant_kernel<<>>(blob, gu16, down16); - check("blob_dequant_f16"); -} -void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, int64_t n_ff, void* stream) { - if (n <= 0) return; - swiglu_il_kernel<<>>(gu, h16, n, n_ff); - check("swiglu_interleaved"); -} -void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, int64_t n_ff, void* stream) { - if (n <= 0) return; - swiglu_pair_kernel<<>>(g, u, h16, n * n_ff); - check("swiglu_pair"); -} -namespace { -__global__ void copy_i32_kernel(int32_t* __restrict__ dst, const int32_t* __restrict__ src, int64_t n) { - for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) - dst[i] = src[i]; -} -} // namespace -namespace { -__global__ void copy_f4_kernel(float4* __restrict__ dst, const float4* __restrict__ src, int64_t n4) { - for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n4; i += (int64_t) gridDim.x * blockDim.x) - dst[i] = src[i]; -} -} // namespace -void copy_f32_wide(float* dst, const float* src, int64_t n, void* stream) { - if (n <= 0) return; - const int64_t n4 = n / 4, b = std::min((n4 + 255) / 256, 4096); - if (n4 > 0) copy_f4_kernel<<<(unsigned) b, 256, 0, (cudaStream_t) stream>>>((float4*) dst, (const float4*) src, n4); - if (n % 4) copy_i32((int32_t*) dst + n4 * 4, (const int32_t*) src + n4 * 4, n % 4, stream); - check("copy_f32_wide"); -} -void copy_i32(int32_t* dst, const int32_t* src, int64_t n, void* stream) { - if (n <= 0) return; - const int64_t b = (n + 255) / 256; - copy_i32_kernel<<<(unsigned) (b < 256 ? b : 256), 256, 0, (cudaStream_t) stream>>>(dst, src, n); - check("copy_i32"); -} -void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, int64_t n, int64_t width, void* stream) { - if (n <= 0) return; - gather_rows16_kernel<<>>(x16, src, dst16, n, width); - check("gather_rows16"); -} -void moe_combine(const float* Dm, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo, - int64_t T, int64_t n, int64_t k, void* stream) { - moe_combine_kernel<<>>(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) { - if (rows <= 0) return; - rms_rows_kernel<<<(unsigned) rows, 256, 0, (cudaStream_t) stream>>>(x, w, cols, ld, eps); - check("rms_rows"); -} -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) { - // The engine validates the resolved config at startup with the same rule (generate.cpp), so this only - // fires for a caller that bypassed it; the prompt path has no error return here, so it stops the process. - if (const char* why = strata::kernels::rope_scaling_invalid(scaling)) { - std::fprintf(stderr, "prefill rope: invalid rope scaling: %s\n", why); - std::exit(1); - } - const float theta_scale = powf((float) scaling.freq_base, -2.0f / 64.0f); - const strata::kernels::RopeKernelArgs k = scaling.kernel_args(64); // none: the identity constants - const strata::kernels::RopeTab rt = strata::kernels::rope_table_for(scaling); - if (rt.cos != nullptr) - rope_kernel<<<(unsigned) (T * heads), 32, 0, (cudaStream_t) stream>>>( - x, heads, dim, ld, pos0, theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, - strata::kernels::mrope_table(), rt); - else - rope_kernel<<<(unsigned) (T * heads), 32, 0, (cudaStream_t) stream>>>( - x, heads, dim, ld, pos0, theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, - strata::kernels::mrope_table(), rt); - check("rope"); -} -void split_q(const float* q_full, float* q, int64_t T, int64_t n_head, void* stream) { - split_q_kernel<<>>(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, int64_t n_head, void* stream) { - gate_attn_kernel<<>>(attn, q_full, out16, T, n_head); - check("gate_attn"); -} - -} // namespace strata::prefill diff --git a/src/prefill/moe_fused.cu b/src/prefill/moe_fused.cu deleted file mode 100644 index 19d1c94..0000000 --- a/src/prefill/moe_fused.cu +++ /dev/null @@ -1,465 +0,0 @@ -// src/prefill/moe_fused.cu - see include/strata/prefill/moe_fused.hpp (#136: the Q2_0 pack's prompt experts on -// Strata's own int8 tensor-core kernels, with the grouping on the GPU). -// -// The arithmetic. A Q2_0 block is 64 weights w = d_w * (q - 1), q in 0..3, four codes per byte, weight j of a block -// in byte j / 4 at bits 2 * (j % 4). An activation block of 32 values is x = d_x * a with a = round(x / d_x) in -// -127..127. Over one 32-value half-block -// sum w x = d_w * d_x * (sum q a - sum a), -// so the int8 product takes the codes as they are (0..3 is a valid s8) and the offset is the activations' own sum, -// stored with the block. The dot product (|sum q a| <= 32 * 3 * 127 < 2^22) becomes a float exactly with one -// integer add: as_float(0x4B400000 + dot) = 1.5 * 2^23 + dot, and the block stores c = -(1.5 * 2^23 + sum a), so -// as_float(0x4B400000 + dot) + c = dot - sum a with no rounding. Per output and 64-block that is -// acc += d_w * (d_x0 * t0 + d_x1 * t1) (t = dot - sum a of each half) -// - two integer adds, two float adds and three multiply-adds. -// -// The K order. mma.sync m16n8k32 takes four consecutive k of a row (A) or column (B) per register. Four consecutive -// weights are one code byte; four codes of one register instead come from the same 2-bit field of four consecutive -// bytes - (word >> 2t) & 0x03030303 holds weights t, t+4, t+8, t+12 of a 16-weight word. So the kernels use that order -// for the k of a half-block: mma k index 16h + 4t + j stands for weight (and activation) 16h + t + 4j. The -// activations are stored in it (perm32), and a lane's two B registers (h = 0 and 1) are adjacent: one 8-byte load. -#include "strata/prefill/moe_fused.hpp" - -#include -#include - -#include -#include -#include -#include - -namespace strata::prefill::fused { -namespace { - -void ck(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "prefill fused experts: %s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -constexpr int AB = 80; // activation bytes per 64 values: 64 codes, then {d0, c0, d1, c1} -constexpr int MAGIC = 0x4B400000; // the bits of 1.5 * 2^23 -constexpr float MAGICF = 12582912.0f; -// The Strata Q2_0 blob (moe_mmq.cu strata_q2_kernel, kernels.cu blob_dequant_kernel): gate/up codes [1280][640 B] -// (rows interleaved: gate of feature f at row 2f, its up at 2f + 1), down codes [2560][160 B], gate/up scales -// [1280][40] fp16, down scales [2560][10] fp16. -constexpr size_t O_GU_CODES = 0, O_D_CODES = (size_t) 1280 * 640, O_GU_SC = O_D_CODES + (size_t) 2560 * 160, - O_D_SC = O_GU_SC + (size_t) 1280 * 40 * 2; -constexpr int THREADS = 512; // 16 warps: 4 along the weight rows (64 each) x 4 along the tile rows (16 each) -constexpr int WROWS = 256; // weight rows per work item: 128 features of gate/up, or 256 outputs of down -constexpr int STAGES = 4; // cp.async pipeline depth, one 64-weight block of K per stage -constexpr int STAGE_BYTES = WROWS * 16 + kTileRows * AB; -constexpr size_t smem_bytes(bool gu) { - return (size_t) WROWS * (gu ? 40 : 10) * 2 + STAGES * STAGE_BYTES + kTileRows * 4; -} - -// the stored position of value k of a 32-value half-block (see "The K order") -__host__ __device__ __forceinline__ int perm32(int k) { return 8 * (k & 3) + 4 * (k >> 4) + ((k & 15) >> 2); } - -struct Tables { - int32_t *cnt, *off, *fill, *ts; // per expert: rows, first row (E + 1), placement cursor, first tile (E + 1) - int2* tiles; // {expert, first row}, in expert order -}; -size_t tiles_at(int n_expert) { return ((size_t) (4 * n_expert + 2) * 4 + 15) / 16 * 16; } -Tables tables(void* scratch, int n_expert) { - int32_t* p = (int32_t*) scratch; - return {p, p + n_expert, p + 2 * n_expert + 1, p + 3 * n_expert + 1, - (int2*) ((uint8_t*) scratch + tiles_at(n_expert))}; -} - -// ---- activations: one warp per 64 values -__global__ void quant_act_kernel(const float* __restrict__ x, int64_t nblk, uint8_t* __restrict__ xa) { - const int64_t w = (int64_t) blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32; - const int lane = threadIdx.x & 31; - if (w >= nblk) return; - const float v0 = x[w * 64 + lane], v1 = x[w * 64 + 32 + lane]; - float a0 = fabsf(v0), a1 = fabsf(v1); -#pragma unroll - for (int o = 16; o > 0; o >>= 1) { - a0 = fmaxf(a0, __shfl_xor_sync(0xffffffffu, a0, o)); - a1 = fmaxf(a1, __shfl_xor_sync(0xffffffffu, a1, o)); - } - const int q0 = a0 > 0.0f ? __float2int_rn(v0 * (127.0f / a0)) : 0; - const int q1 = a1 > 0.0f ? __float2int_rn(v1 * (127.0f / a1)) : 0; - int s0 = q0, s1 = q1; -#pragma unroll - for (int o = 16; o > 0; o >>= 1) { - s0 += __shfl_xor_sync(0xffffffffu, s0, o); - s1 += __shfl_xor_sync(0xffffffffu, s1, o); - } - uint8_t* out = xa + w * AB; - out[perm32(lane)] = (uint8_t) (int8_t) q0; - out[32 + perm32(lane)] = (uint8_t) (int8_t) q1; - if (lane == 0) - *(float4*) (out + 64) = make_float4(a0 / 127.0f, -(MAGICF + (float) s0), a1 / 127.0f, -(MAGICF + (float) s1)); -} - -// ---- grouping: counts, offsets and tiles, placement -__global__ void count_kernel(const int32_t* __restrict__ ids, int64_t n, int E, int32_t* __restrict__ cnt) { - extern __shared__ int32_t hist[]; - for (int e = threadIdx.x; e < E; e += blockDim.x) hist[e] = 0; - __syncthreads(); - for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) { - const int e = ids[i]; - if ((unsigned) e < (unsigned) E) atomicAdd(&hist[e], 1); - } - __syncthreads(); - for (int e = threadIdx.x; e < E; e += blockDim.x) - if (hist[e]) atomicAdd(&cnt[e], hist[e]); -} - -// exclusive prefix sum over the block (blockDim a multiple of 32); *total = the block's sum -__device__ int block_excl_sum(int v, int* total, int* sh) { - const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, nw = blockDim.x >> 5; - int x = v; -#pragma unroll - for (int o = 1; o < 32; o <<= 1) { - const int y = __shfl_up_sync(0xffffffffu, x, o); - if (lane >= o) x += y; - } - if (lane == 31) sh[w] = x; - __syncthreads(); - if (w == 0) { - int s = lane < nw ? sh[lane] : 0; -#pragma unroll - for (int o = 1; o < 32; o <<= 1) { - const int y = __shfl_up_sync(0xffffffffu, s, o); - if (lane >= o) s += y; - } - sh[lane] = s; - } - __syncthreads(); - const int r = x - v + (w > 0 ? sh[w - 1] : 0); - *total = sh[nw - 1]; - __syncthreads(); // sh is reused by the next call - return r; -} - -// one block, a thread per expert (E <= 1024) -__global__ void scan_kernel(Tables tb, int E) { - __shared__ int sh[32]; - const int e = threadIdx.x; - const int c = e < E ? tb.cnt[e] : 0, nt = (c + kTileRows - 1) / kTileRows; - int rows = 0, tiles = 0; - const int o = block_excl_sum(c, &rows, sh), to = block_excl_sum(nt, &tiles, sh); - if (e < E) { - tb.off[e] = o; - tb.fill[e] = o; - tb.ts[e] = to; - for (int i = 0; i < nt; ++i) tb.tiles[to + i] = make_int2(e, o + i * kTileRows); - } - if (e == 0) { - tb.off[E] = rows; - tb.ts[E] = tiles; - } -} - -__global__ void place_kernel(const int32_t* __restrict__ ids, int64_t n, int k, int E, Tables tb, - int32_t* __restrict__ slot, int32_t* __restrict__ src) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n) return; - const int e = ids[i]; - if ((unsigned) e >= (unsigned) E) { slot[i] = 0; return; } // (the router never writes one) - const int p = atomicAdd(&tb.fill[e], 1); - slot[i] = p; - src[p] = (int32_t) (i / k); -} - -// ---- the expert products -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 -__device__ __forceinline__ void cp16(void* dst, const void* src) { - asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"((unsigned) __cvta_generic_to_shared(dst)), - "l"(src)); -} -__device__ __forceinline__ void cp4(void* dst, const void* src) { - asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"((unsigned) __cvta_generic_to_shared(dst)), - "l"(src)); -} -__device__ __forceinline__ void cp_commit() { asm volatile("cp.async.commit_group;\n" ::); } -template __device__ __forceinline__ void cp_wait() { asm volatile("cp.async.wait_group %0;\n" ::"n"(N)); } -// d = A (16 x 32 s8, row) * B (32 x 8 s8, col), int32, from zero -__device__ __forceinline__ void mma_s8(int (&d)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) { - asm("mma.sync.aligned.m16n8k32.row.col.s32.s8.s8.s32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%10,%10,%10,%10};\n" - : "=r"(d[0]), "=r"(d[1]), "=r"(d[2]), "=r"(d[3]) - : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1), "r"(0)); -} -#endif - -// One work item = (tile of up to 64 routed rows of expert e, a block of 256 weight rows); a persistent grid walks -// the batch's items (their count is on the device). GU: gate/up rows of 128 features against the rows' tokens' -// activations (`act` per token, 2560 values), SwiGLU, H to int8 per 32 features into `out` (per row, 640 values). -// !GU: down rows (256 outputs) against H (`act` per row), FP32 into `dm` per row. -// Warp (wf, wt): weight rows 64 wf.. as four m16 tiles (GU: a tile = 8 features, its gate rows as mma rows 0-7 and -// its up rows as 8-15, so a lane holds gate and up of one feature: SwiGLU in registers), tile rows 16 wt.. as two n8. -template -__global__ void __launch_bounds__(THREADS, 1) -expert_kernel(const Batch b, const Tables tb, const uint8_t* __restrict__ act, const int32_t* __restrict__ src, - uint8_t* __restrict__ out, float* __restrict__ dm) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 - constexpr int NKB = GU ? 40 : 10; // 64-weight blocks along K - constexpr int NFB = GU ? 5 : 10; // weight-row blocks per tile - constexpr int CODE_LD = GU ? 640 : 160; // code bytes per weight row - constexpr size_t O_CODES = GU ? O_GU_CODES : O_D_CODES, O_SC = GU ? O_GU_SC : O_D_SC; - constexpr int ACT_LD = NKB * AB; // bytes per activation row: 3200 (a token), 800 (a row's H) - constexpr unsigned M2 = 0x03030303u; - extern __shared__ __align__(16) uint8_t smem[]; - const __half* wsc = (const __half*) smem; // [256][NKB] the work item's weight scales - uint8_t* stages = smem + WROWS * NKB * 2; // [STAGES] x {codes [256][16], act [64][AB]} - int* srow = (int*) (stages + STAGES * STAGE_BYTES); // [64] the activation row of each tile row - - const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5, g = lane >> 2, tig = lane & 3; - const int wf = warp & 3, nb0 = 16 * (warp >> 2); - int ra[4], rb[4]; // the local weight rows of mma rows g and g + 8 -#pragma unroll - for (int i = 0; i < 4; ++i) { - if (GU) { ra[i] = 2 * (32 * wf + 8 * i + g); rb[i] = ra[i] + 1; } - else { ra[i] = 64 * wf + 16 * i + g; rb[i] = ra[i] + 8; } - } - const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB; - for (int w = blockIdx.x; w < nwork; w += gridDim.x) { - const int2 tl = tb.tiles[t0 + w / NFB]; - const int fb = w % NFB, e = tl.x, row0 = tl.y, nrows = min(kTileRows, tb.off[e + 1] - row0); - const uint8_t* blob = b.blob[e - b.e0]; - const int rbase = fb * WROWS; - __syncthreads(); // the previous item is done with the buffers - if (tid < kTileRows) { - const int r = row0 + min(tid, nrows - 1); // rows past the tile's end repeat its last one - srow[tid] = GU ? src[r] : r; - } - for (int c = tid; c < WROWS * 5; c += THREADS) { // the scales: 5 x 16 B (GU) or 5 x 4 B a row - const int r = c / 5, q = c % 5; - if (GU) cp16(smem + r * 80 + q * 16, blob + O_SC + (size_t) (rbase + r) * 80 + q * 16); - else cp4(smem + r * 20 + q * 4, blob + O_SC + (size_t) (rbase + r) * 20 + q * 4); - } - __syncthreads(); // srow - auto load = [&](int kb) { - uint8_t* st = stages + (kb % STAGES) * STAGE_BYTES; - if (tid < WROWS) cp16(st + tid * 16, blob + O_CODES + (size_t) (rbase + tid) * CODE_LD + kb * 16); - const int a = tid - (THREADS - kTileRows * 5); // the last 320 threads: 64 rows x 5 x 16 B - if (a >= 0) { - const int r = a / 5, q = a % 5; - cp16(st + WROWS * 16 + r * AB + q * 16, act + (size_t) srow[r] * ACT_LD + kb * AB + q * 16); - } - }; -#pragma unroll - for (int s = 0; s < STAGES - 1; ++s) { - if (s < NKB) load(s); - cp_commit(); - } - // a warp whose rows are all past the tile's end only takes part in the loads - const bool on0 = nb0 < nrows, on1 = nb0 + 8 < nrows; - float acc[4][2][4]; -#pragma unroll - for (int i = 0; i < 4; ++i) -#pragma unroll - for (int n = 0; n < 2; ++n) -#pragma unroll - for (int q = 0; q < 4; ++q) acc[i][n][q] = 0.0f; - for (int kb = 0; kb < NKB; ++kb) { - cp_wait(); - __syncthreads(); - if (kb + STAGES - 1 < NKB) load(kb + STAGES - 1); - cp_commit(); - if (!on0) continue; - const uint8_t* st = stages + (kb % STAGES) * STAGE_BYTES; - const uint8_t* sa = st + WROWS * 16; - uint2 bq[2][2]; // [n8 tile][half]: the B registers - float4 sc[2][2]; // [n8 tile][column 2 tig + c]: {d0, c0, d1, c1} -#pragma unroll - for (int n = 0; n < 2; ++n) { - if (n == 1 && !on1) break; - const uint8_t* r = sa + (nb0 + 8 * n + g) * AB + 8 * tig; - bq[n][0] = *(const uint2*) r; - bq[n][1] = *(const uint2*) (r + 32); - sc[n][0] = *(const float4*) (sa + (nb0 + 8 * n + 2 * tig) * AB + 64); - sc[n][1] = *(const float4*) (sa + (nb0 + 8 * n + 2 * tig + 1) * AB + 64); - } -#pragma unroll - for (int i = 0; i < 4; ++i) { - const uint4 ca = *(const uint4*) (st + ra[i] * 16), cb = *(const uint4*) (st + rb[i] * 16); - const float da = __half2float(wsc[ra[i] * NKB + kb]), db = __half2float(wsc[rb[i] * NKB + kb]); - const int s = 2 * tig; - const uint32_t a0[4] = {(ca.x >> s) & M2, (cb.x >> s) & M2, (ca.y >> s) & M2, (cb.y >> s) & M2}; - const uint32_t a1[4] = {(ca.z >> s) & M2, (cb.z >> s) & M2, (ca.w >> s) & M2, (cb.w >> s) & M2}; -#pragma unroll - for (int n = 0; n < 2; ++n) { - if (n == 1 && !on1) break; - int d0[4], d1[4]; - mma_s8(d0, a0, bq[n][0].x, bq[n][0].y); - mma_s8(d1, a1, bq[n][1].x, bq[n][1].y); -#pragma unroll - for (int q = 0; q < 4; ++q) { - const float4 z = sc[n][q & 1]; - const float u0 = __int_as_float(MAGIC + d0[q]) + z.y, u1 = __int_as_float(MAGIC + d1[q]) + z.w; - acc[i][n][q] = fmaf(q < 2 ? da : db, fmaf(z.z, u1, z.x * u0), acc[i][n][q]); - } - } - } - } - if (!on0) continue; - if (GU) { - // SwiGLU of feature 32 wf + 8 i + g (lane g of m tile i), tile rows nb0 + 8 n + 2 tig + c; H to int8 per - // row over the warp's 32 features (= one 32-value half-block of the down product's K) - const int blk = 4 * fb + wf; -#pragma unroll - for (int n = 0; n < 2; ++n) { - if (n == 1 && !on1) break; -#pragma unroll - for (int c = 0; c < 2; ++c) { - float h[4], am = 0.0f; -#pragma unroll - for (int i = 0; i < 4; ++i) { - const float gt = acc[i][n][c], up = acc[i][n][2 + c]; - h[i] = gt / (1.0f + __expf(-gt)) * up; - am = fmaxf(am, fabsf(h[i])); - } -#pragma unroll - for (int o = 4; o < 32; o <<= 1) am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, o)); - const float inv = am > 0.0f ? 127.0f / am : 0.0f; - int qv[4], sum = 0; -#pragma unroll - for (int i = 0; i < 4; ++i) { qv[i] = __float2int_rn(h[i] * inv); sum += qv[i]; } -#pragma unroll - for (int o = 4; o < 32; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); - 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; - const int hh = blk & 1; -#pragma unroll - for (int i = 0; i < 4; ++i) o[32 * hh + perm32(8 * i + g)] = (uint8_t) (int8_t) qv[i]; - if (g == 0) *(float2*) (o + 64 + 8 * hh) = make_float2(am / 127.0f, -(MAGICF + (float) sum)); - } - } - } - } else { -#pragma unroll - for (int i = 0; i < 4; ++i) -#pragma unroll - for (int n = 0; n < 2; ++n) { - if (n == 1 && !on1) break; -#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 + (q < 2 ? ra[i] : rb[i])] = acc[i][n][q]; - } - } - } - } -#endif -} - -unsigned blocks(int64_t n, int per) { return (unsigned) ((n + per - 1) / per); } - -struct DevInfo { - bool done = false; - int cc = 0, sms = 0, occ_gu = 0, occ_d = 0; -}; -std::mutex g_mu; -DevInfo g_dev[32]; - -const DevInfo& dev_info() { - int dev = 0; - cudaGetDevice(&dev); - std::lock_guard lk(g_mu); - DevInfo& d = g_dev[dev & 31]; - if (d.done) return d; - d.done = true; -#if defined(STRATA_HIP_GFX906) - // gfx906 reports compute capability 9.0 through HIP, but the mma.sync bodies above are CUDA sm_80+ only and - // empty in a hipcc build: never available here (the prompt path keeps its own expert GEMMs) - return d; -#else - int major = 0, minor = 0; - cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); - cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev); - cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev); - d.cc = 10 * major + minor; - if (d.cc < 80) return d; - // the device code of this card's arch must have the kernels (a build without an sm_80+ target has an empty body) - cudaFuncAttributes fa{}; - if (cudaFuncGetAttributes(&fa, expert_kernel) != cudaSuccess || fa.ptxVersion < 80) { - cudaGetLastError(); - d.cc = 0; - return d; - } - ck(cudaFuncSetAttribute(expert_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem_bytes(true)), - "smem gu"); - ck(cudaFuncSetAttribute(expert_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem_bytes(false)), - "smem down"); - cudaOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_gu, expert_kernel, THREADS, smem_bytes(true)); - cudaOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_d, expert_kernel, THREADS, smem_bytes(false)); - if (d.occ_gu < 1 || d.occ_d < 1) d.cc = 0; // does not fit this card: the MMQ path - cudaGetLastError(); -#endif - return d; -} - -} // namespace - -bool built() { return true; } -bool available() { return dev_info().cc >= 80; } -// 0.1.36: on by default for the Q2_0 pack (+13-23% prompts on an RTX 5070; teacher-forced against the FP16 path as -// close as MMQ at 8K and closer at 32K: phaseA-tests s18-tf); STRATA_PF_FUSED=0 keeps MMQ. The native packs' kernels -// (moe_fused_iq) stay opt-in: STRATA_PF_FUSED=1 (requested()). -bool enabled() { - static const bool env = [] { - const char* v = std::getenv("STRATA_PF_FUSED"); - return v == nullptr || v[0] != '0'; - }(); - return env && available(); -} -bool requested() { - static const bool env = [] { - const char* v = std::getenv("STRATA_PF_FUSED"); - return v != nullptr && v[0] == '1'; - }(); - return env && available(); -} - -size_t act_bytes(int64_t rows, int64_t cols) { return (size_t) rows * (size_t) (cols / 64) * AB; } -size_t group_bytes(int64_t n, int n_expert) { - return tiles_at(n_expert) + ((size_t) (n + kTileRows - 1) / kTileRows + (size_t) n_expert) * sizeof(int2); -} - -void quantize_act(const float* x, int64_t rows, int64_t cols, void* xa, void* stream) { - if (rows <= 0) return; - const int64_t nblk = rows * (cols / 64); - quant_act_kernel<<>>(x, nblk, (uint8_t*) xa); - ck(cudaGetLastError(), "quantize_act"); -} - -void group(const int32_t* ids, int64_t n, int k, int n_expert, void* scratch, int32_t* slot, int32_t* src, - void* stream) { - if (n_expert < 1 || n_expert > 1024) { - std::fprintf(stderr, "prefill fused experts: %d experts (the grouping takes 1 to 1024)\n", n_expert); - std::exit(1); - } - const cudaStream_t s = (cudaStream_t) stream; - const Tables tb = tables(scratch, n_expert); - ck(cudaMemsetAsync(tb.cnt, 0, (size_t) n_expert * 4, s), "group memset"); - if (n > 0) { - const unsigned nb = std::min(blocks(n, 1024), 4u * (unsigned) std::max(dev_info().sms, 1)); - count_kernel<<>>(ids, n, n_expert, tb.cnt); - } - scan_kernel<<<1, (unsigned) ((n_expert + 31) / 32 * 32), 0, s>>>(tb, n_expert); - if (n > 0) place_kernel<<>>(ids, n, k, n_expert, tb, slot, src); - ck(cudaGetLastError(), "group"); -} - -void experts(const Batch& b, int n_expert, int64_t n, const void* scratch, const void* xa, const int32_t* src, - void* ha, float* dm, void* stream) { - if (b.e1 <= b.e0 || n <= 0) return; - const DevInfo& d = dev_info(); - const cudaStream_t s = (cudaStream_t) stream; - const Tables tb = tables(const_cast(scratch), n_expert); - // the most tiles the batch can have: every row in it, plus a partial tile per expert - const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0); - const unsigned g_gu = (unsigned) std::min(tiles * 5, (int64_t) d.sms * d.occ_gu); - const unsigned g_d = (unsigned) std::min(tiles * 10, (int64_t) d.sms * d.occ_d); - expert_kernel<<>>(b, tb, (const uint8_t*) xa, src, (uint8_t*) ha, - nullptr); - expert_kernel<<>>(b, tb, (const uint8_t*) ha, src, nullptr, dm); - ck(cudaGetLastError(), "experts"); -} - -} // namespace strata::prefill::fused diff --git a/src/prefill/moe_fused_iq.cu b/src/prefill/moe_fused_iq.cu deleted file mode 100644 index 1e8227a..0000000 --- a/src/prefill/moe_fused_iq.cu +++ /dev/null @@ -1,646 +0,0 @@ -// src/prefill/moe_fused_iq.cu - see include/strata/prefill/moe_fused_iq.hpp (#136: the native packs' prompt experts on -// the fused int8 kernels of moe_fused.cu). -// -// The arithmetic. An activation block of 32 values is x = d_x * a, a = round(x / d_x) in -127..127, stored in natural -// order (per 64 values: 64 codes, then {d_0, d_1} and 8 unused bytes - 80 bytes, the Q2_0 path's size). A weight -// block of 32 (or 16) values is w = d_w * q with q an int8: the i-quants' codebook entries with their signs applied -// (IQ2_XXS / IQ2_XS / IQ2_S: 0..43, IQ3_XXS: 0..62, IQ3_S: 0..15, IQ4_XS / IQ4_NL: -127..113), Q2_0's code - 1. So -// sum w x = d_w * d_x * sum q a, |sum q a| <= 32 * 127 * 127 < 2^22, -// and the int32 dot becomes a float exactly with one float add: the mma starts from C = 0x4B400000 (the bits of -// 1.5 * 2^23), so as_float(D) - 1.5 * 2^23 is the dot. Per output and 32 values: that add, d_w * d_x, one fma (the -// formats with a scale per 16 values: two dots, each times its d_w, then d_x). d_w is llama.cpp's own: IQ2_XXS -// d (2s + 1) / 8, IQ2_XS / IQ2_S d (2s + 1) / 8 per 16, IQ3_XXS d (2s + 1) / 4, IQ3_S d (2s + 1), IQ4_XS d (s - 32), -// IQ4_NL and Q2_0 d (dequantize_row_* in ggml-quants.c, mmq-load-tiles.cuh). -// -// The load stage. Per 64 values of K (a stage), a thread decodes one 32-value sub-block of one of the work item's -// weight rows: its block bytes are read from the blob with 16-bit loads (the GGUF blocks are 2-byte aligned: 66 / 74 / -// 82 / 98 / 110 / 136 / 18 bytes) one stage ahead into registers (and two 256-value blocks ahead into L2), then turned -// into 32 int8 and the sub-block's scales in shared memory, double-buffered. The codebooks live in shared memory (up -// to 8 KB, IQ2_S). The activations arrive by cp.async, four stages deep, as in moe_fused.cu; the fragments come by -// ldmatrix. The products are mma.sync m16n8k32 (m16n8k16 for the formats with a scale per 16 values); the epilogues -// (SwiGLU, H to int8 per 32 features; down into the per-slot rows) are moe_fused.cu's. -#include "strata/prefill/moe_fused_iq.hpp" - -#include -#include - -#include "ggml.h" - -#define GGML_COMMON_DECL_CUDA -#define GGML_COMMON_IMPL_CUDA -#include "ggml-common.h" - -#include -#include -#include -#include - -namespace strata::prefill::fused { -namespace { - -void ck(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "prefill fused experts (native): %s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -constexpr int AB = 80; // activation bytes per 64 values: 64 codes, {d0, d1}, 8 unused -constexpr int MAGIC = 0x4B400000; // the bits of 1.5 * 2^23 -constexpr float MAGICF = 12582912.0f; -// 16 warps, each 64 weight rows x 16 routed rows; WW of them along the weight rows and 16 / WW along the routed rows: a -// work item is (WR = 64 WW weight rows) x (TR = 256 / WW routed rows of one expert) - 256 x 64 or 128 x 128, chosen -// per launch by the rows per expert (pick_ww) -constexpr int THREADS = 512; -constexpr int WLD = 80; // bytes per decoded weight row of a stage: 64 int8 + 16 (no bank conflicts) -__host__ __device__ constexpr int tile_rows(int ww) { return 256 / ww; } -__host__ __device__ constexpr int weight_rows(int ww) { return 64 * ww; } -constexpr int ASTAGES = 4; // cp.async depth of the activations (64 values of K a stage) -// K of gate/up (n_embd) and of down (n_ff) are the layer's (NativeGeom): 2560 / 640 for Flash-Next, 2048 / 512 for -// Qwen3.6. They set the stage count and the weight-row blocks per tile, loop bounds rather than unrolled constants. - -// 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, - T_IQ3_XXS = GGML_TYPE_IQ3_XXS, T_IQ3_S = GGML_TYPE_IQ3_S, T_IQ4_XS = GGML_TYPE_IQ4_XS, - T_IQ4_NL = GGML_TYPE_IQ4_NL, T_Q2_0 = GGML_TYPE_Q2_0; -static_assert(sizeof(block_iq2_xxs) == 66 && sizeof(block_iq2_xs) == 74 && sizeof(block_iq2_s) == 82 && - sizeof(block_iq3_xxs) == 98 && sizeof(block_iq3_s) == 110 && sizeof(block_iq4_xs) == 136 && - sizeof(block_iq4_nl) == 18 && sizeof(block_q2_0) == 18, "the block layouts this file decodes"); - -// block bytes, scale per 16 values, codebook bytes in shared memory -__host__ __device__ constexpr int block_bytes(int t) { - return t == T_IQ2_XXS ? 66 : t == T_IQ2_XS ? 74 : t == T_IQ2_S ? 82 : t == T_IQ3_XXS ? 98 : t == T_IQ3_S ? 110 - : t == T_IQ4_XS ? 136 : 18; -} -__host__ __device__ constexpr bool per16(int t) { return t == T_IQ2_XS || t == T_IQ2_S; } -__host__ __device__ constexpr int grid_bytes(int t) { - return t == T_IQ2_XXS ? 256 * 8 : t == T_IQ2_XS ? 512 * 8 : t == T_IQ2_S ? 1024 * 8 : t == T_IQ3_XXS ? 256 * 4 - : t == T_IQ3_S ? 512 * 4 : 0; -} -__host__ __device__ constexpr size_t smem_bytes(int t, int ww) { - return (size_t) 2 * weight_rows(ww) * (WLD + 16) + (size_t) ASTAGES * tile_rows(ww) * AB + - (size_t) tile_rows(ww) * 4 + grid_bytes(t); -} - -// moe_fused.cu's grouping tables (the same layout: fused::group writes them) -struct Tables { - int32_t *cnt, *off, *fill, *ts; - int2* tiles; -}; -size_t tiles_at(int n_expert) { return ((size_t) (4 * n_expert + 2) * 4 + 15) / 16 * 16; } -Tables tables(void* scratch, int n_expert) { - int32_t* p = (int32_t*) scratch; - return {p, p + n_expert, p + 2 * n_expert + 1, p + 3 * n_expert + 1, - (int2*) ((uint8_t*) scratch + tiles_at(n_expert))}; -} - -// ---- activations in natural order: one warp per 64 values -__global__ void quant_act_nat_kernel(const float* __restrict__ x, int64_t nblk, uint8_t* __restrict__ xa) { - const int64_t w = (int64_t) blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32; - const int lane = threadIdx.x & 31; - if (w >= nblk) return; - const float v0 = x[w * 64 + lane], v1 = x[w * 64 + 32 + lane]; - float a0 = fabsf(v0), a1 = fabsf(v1); -#pragma unroll - for (int o = 16; o > 0; o >>= 1) { - a0 = fmaxf(a0, __shfl_xor_sync(0xffffffffu, a0, o)); - a1 = fmaxf(a1, __shfl_xor_sync(0xffffffffu, a1, o)); - } - uint8_t* out = xa + w * AB; - out[lane] = (uint8_t) (int8_t) (a0 > 0.0f ? __float2int_rn(v0 * (127.0f / a0)) : 0); - out[32 + lane] = (uint8_t) (int8_t) (a1 > 0.0f ? __float2int_rn(v1 * (127.0f / a1)) : 0); - if (lane == 0) *(float4*) (out + 64) = make_float4(a0 / 127.0f, a1 / 127.0f, 0.0f, 0.0f); -} - -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 -__device__ __forceinline__ void cp16(void* dst, const void* src) { - asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"((unsigned) __cvta_generic_to_shared(dst)), - "l"(src)); -} -__device__ __forceinline__ void cp_commit() { asm volatile("cp.async.commit_group;\n" ::); } -__device__ __forceinline__ void pf_l2(const void* p) { asm volatile("prefetch.global.L2 [%0];\n" ::"l"(p)); } -template __device__ __forceinline__ void cp_wait() { asm volatile("cp.async.wait_group %0;\n" ::"n"(N)); } -// d = MAGIC + A (16 x 32 s8, row) * B (32 x 8 s8, col): the int32 dot with the magic bias already added (the C -// operand), so as_float(d) - 1.5 * 2^23 is the dot as a float -__device__ __forceinline__ void mma32(int (&d)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) { - asm("mma.sync.aligned.m16n8k32.row.col.s32.s8.s8.s32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%10,%10,%10,%10};\n" - : "=r"(d[0]), "=r"(d[1]), "=r"(d[2]), "=r"(d[3]) - : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1), "r"(MAGIC)); -} -// the same at m16n8k16 (A 16 x 16, B 16 x 8) -__device__ __forceinline__ void mma16(int (&d)[4], uint32_t a0, uint32_t a1, uint32_t b0) { - asm("mma.sync.aligned.m16n8k16.row.col.s32.s8.s8.s32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%7,%7,%7,%7};\n" - : "=r"(d[0]), "=r"(d[1]), "=r"(d[2]), "=r"(d[3]) - : "r"(a0), "r"(a1), "r"(b0), "r"(MAGIC)); -} -__device__ __forceinline__ float dotf(int d) { return __int_as_float(d) - MAGICF; } -// four 8 x 16-byte matrices, row addresses from lanes 0-7, 8-15, 16-23, 24-31: lane (g, t) gets bytes 4t..4t+3 of row g -// of each - an mma fragment -__device__ __forceinline__ void ldsm4(uint32_t (&r)[4], const void* p) { - asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n" - : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) - : "r"((unsigned) __cvta_generic_to_shared(p)) - : "memory"); -} - -// ---- the load stage: a 32-value sub-block's bytes into registers, then int8 and scales -__device__ __forceinline__ uint32_t ld16(const uint8_t* p) { return *(const uint16_t*) p; } -__device__ __forceinline__ uint32_t ld32(const uint8_t* p) { return ld16(p) | (ld16(p + 2) << 16); } -__device__ __forceinline__ float half_at(uint32_t w) { return __half2float(__ushort_as_half((unsigned short) w)); } -// llama.cpp's sign unpacking: 7 bits of signs, the 8th their parity (bit 7 of v may be anything) -__device__ __forceinline__ uint32_t unpack_ksigns(uint32_t v) { - v &= 0xFF; - const uint32_t p = __popc(v) & 1; - return (v ^ p << 7) * 0x01010101u; -} -// 8 bytes of a codebook entry with the sign byte `s` (broadcast) applied: bits 0-3 to .x, 4-7 to .y -__device__ __forceinline__ void signed8(uint32_t gx, uint32_t gy, uint32_t s, uint32_t& qx, uint32_t& qy) { - const uint32_t m0 = __vcmpne4(s & 0x08040201u, 0), m1 = __vcmpne4(s & 0x80402010u, 0); - qx = __vsub4(gx ^ m0, m0); - qy = __vsub4(gy ^ m1, m1); -} -// 8 nibbles of q4 through a 16-entry int8 table (4 words): the low nibbles' values in .x, the high ones' in .y -__device__ __forceinline__ void table16(uint32_t q4, const uint32_t (&t)[4], uint32_t& lo, uint32_t& hi) { - uint32_t tmp[2]; - const uint32_t sel = 0x32103210u | ((q4 & 0x88888888u) >> 1); -#pragma unroll - for (int i = 0; i < 2; ++i) { - const uint32_t sh = 16 * i; - const uint32_t l = __byte_perm(t[0], t[1], q4 >> sh), h = __byte_perm(t[2], t[3], q4 >> sh); - tmp[i] = __byte_perm(l, h, sel >> sh); - } - lo = __byte_perm(tmp[0], tmp[1], 0x6420); - hi = __byte_perm(tmp[0], tmp[1], 0x7531); -} - -// Raw bytes of sub-block `ib` of the block at `bp` (IQ: the 256-value super-block, ib 0..7; Q2_0: the 64-value block, -// ib 0..1; IQ4_NL: the 32-value block). -template __device__ __forceinline__ void load_unit(const uint8_t* bp, int ib, uint32_t (&w)[5]) { - if constexpr (T == T_IQ2_XXS) { - w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld16(bp); - } else if constexpr (T == T_IQ2_XS) { - w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld16(bp) | ((uint32_t) bp[66 + ib] << 16); - } else if constexpr (T == T_IQ2_S) { - w[0] = ld32(bp + 2 + 4 * ib); w[1] = ld32(bp + 34 + 4 * ib); - w[2] = ld16(bp) | ((uint32_t) bp[66 + ib] << 16) | ((uint32_t) bp[74 + ib] << 24); - } else if constexpr (T == T_IQ3_XXS) { - w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld32(bp + 66 + 4 * ib); w[3] = ld16(bp); - } else if constexpr (T == T_IQ3_S) { - w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld32(bp + 74 + 4 * ib); - w[3] = ld16(bp) | ((uint32_t) bp[66 + ib] << 16) | ((uint32_t) ((bp[106 + ib / 2] >> (4 * (ib & 1))) & 15) << 24); - } else if constexpr (T == T_IQ4_XS) { -#pragma unroll - for (int k = 0; k < 4; ++k) w[k] = ld32(bp + 8 + 16 * ib + 4 * k); - const uint32_t ls = ((bp[4 + ib / 2] >> (4 * (ib & 1))) & 15) | (((ld16(bp + 2) >> (2 * ib)) & 3) << 4); - w[4] = ld16(bp) | (ls << 16); - } else if constexpr (T == T_IQ4_NL) { -#pragma unroll - for (int k = 0; k < 4; ++k) w[k] = ld32(bp + 2 + 4 * k); - w[4] = ld16(bp); - } else { // Q2_0 - w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld16(bp); - } -} - -// The sub-block as 32 int8 (q[0..7], natural order) and its scales (s0: values 0-15, s1: 16-31). -template -__device__ __forceinline__ void convert(const uint32_t (&w)[5], const uint8_t* grid, const uint32_t (&kv)[4], - uint32_t (&q)[8], float& s0, float& s1) { - if constexpr (T == T_IQ2_XXS) { - const uint2* g = (const uint2*) grid; -#pragma unroll - for (int l = 0; l < 4; ++l) { - const uint2 e = g[(w[0] >> (8 * l)) & 255]; - signed8(e.x, e.y, unpack_ksigns(w[1] >> (7 * l)), q[2 * l], q[2 * l + 1]); - } - s0 = s1 = half_at(w[2]) * (float) ((w[1] >> 27) | 1) * 0.125f; - } else if constexpr (T == T_IQ2_XS) { - const uint2* g = (const uint2*) grid; -#pragma unroll - for (int l = 0; l < 4; ++l) { - const uint32_t c = (w[l >> 1] >> (16 * (l & 1))) & 0xFFFF; - const uint2 e = g[c & 511]; - signed8(e.x, e.y, unpack_ksigns(c >> 9), q[2 * l], q[2 * l + 1]); - } - const float d = half_at(w[2]); - const uint32_t sc = w[2] >> 16; - s0 = d * (float) (2 * (sc & 15) + 1) * 0.125f; - s1 = d * (float) (2 * ((sc >> 4) & 15) + 1) * 0.125f; - } else if constexpr (T == T_IQ2_S) { - const uint2* g = (const uint2*) grid; - const uint32_t qh = (w[2] >> 16) & 255; -#pragma unroll - for (int l = 0; l < 4; ++l) { - const uint2 e = g[((w[0] >> (8 * l)) & 255) | ((qh << (8 - 2 * l)) & 0x300)]; - signed8(e.x, e.y, ((w[1] >> (8 * l)) & 255) * 0x01010101u, q[2 * l], q[2 * l + 1]); - } - const float d = half_at(w[2]); - const uint32_t sc = w[2] >> 24; - s0 = d * (float) (2 * (sc & 15) + 1) * 0.125f; - s1 = d * (float) (2 * (sc >> 4) + 1) * 0.125f; - } else if constexpr (T == T_IQ3_XXS) { - const uint32_t* g = (const uint32_t*) grid; -#pragma unroll - for (int l = 0; l < 4; ++l) { - const uint32_t i0 = (w[l >> 1] >> (16 * (l & 1))) & 255, i1 = (w[l >> 1] >> (16 * (l & 1) + 8)) & 255; - signed8(g[i0], g[i1], unpack_ksigns(w[2] >> (7 * l)), q[2 * l], q[2 * l + 1]); - } - s0 = s1 = half_at(w[3]) * (float) (2 * (w[2] >> 28) + 1) * 0.25f; - } else if constexpr (T == T_IQ3_S) { - const uint32_t* g = (const uint32_t*) grid; - const uint32_t qh = (w[3] >> 16) & 255; -#pragma unroll - for (int l = 0; l < 4; ++l) { - const uint32_t i0 = (w[l >> 1] >> (16 * (l & 1))) & 255, i1 = (w[l >> 1] >> (16 * (l & 1) + 8)) & 255; - signed8(g[i0 | ((qh << (8 - 2 * l)) & 256)], g[i1 | ((qh << (7 - 2 * l)) & 256)], - ((w[2] >> (8 * l)) & 255) * 0x01010101u, q[2 * l], q[2 * l + 1]); - } - s0 = s1 = half_at(w[3]) * (float) (1 + 2 * (w[3] >> 24)); - } else if constexpr (T == T_IQ4_XS || T == T_IQ4_NL) { -#pragma unroll - for (int k = 0; k < 4; ++k) table16(w[k], kv, q[k], q[4 + k]); - s0 = s1 = T == T_IQ4_XS ? half_at(w[4]) * (float) ((int) (w[4] >> 16) - 32) : half_at(w[4]); - } else { // Q2_0: code - 1 via a byte table {-1, 0, 1, 2} -#pragma unroll - for (int h = 0; h < 4; ++h) { - const uint32_t c = (w[h >> 1] >> (16 * (h & 1))) & 0xFFFF; - const uint32_t qe = __byte_perm(0x020100FFu, 0x020100FFu, c & 0x7777); - const uint32_t qo = __byte_perm(0x020100FFu, 0x020100FFu, (c >> 2) & 0x7777); - q[2 * h] = __byte_perm(qe, qo, 0x5140); - q[2 * h + 1] = __byte_perm(qe, qo, 0x7362); - } - s0 = s1 = half_at(w[2]); - } -} - -template __device__ __forceinline__ const void* grid_src() { - if constexpr (T == T_IQ2_XXS) return iq2xxs_grid; - else if constexpr (T == T_IQ2_XS) return iq2xs_grid; - else if constexpr (T == T_IQ2_S) return iq2s_grid; - else if constexpr (T == T_IQ3_XXS) return iq3xxs_grid; - else if constexpr (T == T_IQ3_S) return iq3s_grid; - else return nullptr; -} -#endif - -// One work item = (TR routed rows of expert e - one or two of group()'s 64-row tiles -, a block of WR weight rows); -// a persistent grid walks the batch's items. GU: gate/up rows of WR / 2 features (format WT) against the rows' -// tokens' activations, SwiGLU, H to int8 per 32 features into `out`. !GU: down rows (format WT) against H, FP32 into -// `dm`. Warp (wf, wt): weight rows 64 wf.. as four m16 tiles (GU: a tile = 8 features, gate rows as mma rows 0-7 and -// up rows as 8-15, so a lane holds gate and up of one feature), routed rows 16 wt.. as two n8. -template -__global__ void __launch_bounds__(THREADS, 1) -native_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_t* __restrict__ act, - const int32_t* __restrict__ src, uint8_t* __restrict__ out, float* __restrict__ dm) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 - constexpr int TR = tile_rows(WW), WR = weight_rows(WW); - constexpr int WT_BYTES = WR * WLD, WS_FLOATS = WR * 4, ACT_STAGE = TR * AB; - const int n_embd = (int) geo.n_embd, n_ff = (int) geo.n_ff; - const int NS = (GU ? n_embd : n_ff) / 64; // 64-value stages along K - const int NFB = (GU ? 2 * n_ff : n_embd) / WR; // weight-row blocks per tile - const int ACT_LD = NS * AB; // bytes per activation row: n_embd / 64 * 80 (a token), n_ff / 64 * 80 (a row's H) - const int H_BLOCKS = n_ff / 64; // 64-value blocks of a row's H - constexpr int BS = block_bytes(WT); - constexpr bool K16 = per16(WT); - extern __shared__ __align__(16) uint8_t smem[]; - uint8_t* wt = smem; // [2][WR][WLD] decoded int8 weights - float* ws = (float*) (smem + 2 * WT_BYTES); // [2][WR][4] their scales per 16 values - uint8_t* stages = (uint8_t*) (ws + 2 * WS_FLOATS); // [ASTAGES][TR][AB] activations - int* srow = (int*) (stages + ASTAGES * ACT_STAGE); // [TR] the activation row of each tile row - uint8_t* sgrid = (uint8_t*) (srow + TR); // the codebook - - const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5, g = lane >> 2, tig = lane & 3; - const int wf = warp % WW, nb0 = 16 * (warp / WW); - if constexpr (grid_bytes(WT) > 0) { - const uint32_t* gs = (const uint32_t*) grid_src(); - for (int i = tid; i < grid_bytes(WT) / 4; i += THREADS) ((uint32_t*) sgrid)[i] = gs[i]; - } - uint32_t kv[4] = {0, 0, 0, 0}; - if constexpr (WT == T_IQ4_XS || WT == T_IQ4_NL) { -#pragma unroll - for (int k = 0; k < 16; ++k) kv[k >> 2] |= (uint32_t) (uint8_t) kvalues_iq4nl[k] << (8 * (k & 3)); - } - // Local weight rows: m tile i of warp wf is rows 64 wf + 16 i.. (mma rows g and g + 8: rows +g and +8+g). For - // gate/up a tile is 8 features, its gate rows then its up rows, so a lane holds gate and up of one feature. The - // fragments come by ldmatrix: lane l gives the address of row (l & 7) of matrix l >> 3 - A: {rows 0-7, rows 8-15} - // x {bytes 0-15, 16-31} of a 32-value chunk; B: {tokens nb0 + 0-7, + 8-15} x {bytes 0-15, 16-31}. - const int lm = lane >> 3, l8 = lane & 7; - const int a_off = (64 * wf + 8 * (lm & 1) + l8) * WLD + 16 * (lm >> 1); - const int b_off = (nb0 + 8 * (lm >> 1) + l8) * AB + 16 * (lm & 1); - // this thread's decode unit (the first 2 WR threads): local weight row ur, sub-block uj of each stage - const bool dec = tid < 2 * WR; - const int ur = dec ? tid >> 1 : 0, uj = tid & 1; - const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB; - for (int w = blockIdx.x; w < nwork; w += gridDim.x) { - const int2 tl = tb.tiles[t0 + w / NFB]; - const int fb = w % NFB, e = tl.x, row0 = tl.y; - if ((row0 - tb.off[e]) % TR != 0) continue; // a 64-row tile inside an earlier item's TR rows - const int nrows = min(TR, tb.off[e + 1] - row0); - const uint8_t* blob = b.blob[e - b.e0]; - const int rbase = fb * WR; - // local row ur: gate/up - feature (WR / 2) fb + 8 (ur >> 4) + (ur & 7), its up row when bit 3 is set - const uint8_t* wrow = GU ? blob + ((ur & 8) ? geo.up_off : 0) + - (size_t) (fb * (WR / 2) + 8 * (ur >> 4) + (ur & 7)) * geo.gu_row - : blob + geo.down_off + (size_t) (rbase + ur) * geo.d_row; - auto unit = [&](int s) -> const uint8_t* { // the block of stage s's sub-block - if (GU) return wrow + (s >> 2) * BS; - return WT == T_IQ4_NL ? wrow + (2 * s + uj) * BS : wrow + s * BS; - }; - auto sub = [&](int s) { return GU ? 2 * (s & 3) + uj : uj; }; - // the weight bytes into L2 ahead of the register loads (one stage ahead only - less than a DRAM round trip): - // gate/up PF super-blocks ahead (the row's two threads take a block's first and last line), down the whole row - // slice at once (180 or 360 bytes a row) - constexpr int PF = 2; - auto prefetch_sb = [&](int sb) { - if (dec && sb < n_embd / 256) pf_l2(wrow + sb * BS + (uj ? BS - 1 : 0)); - }; - if (GU) { -#pragma unroll - for (int sb = 0; sb < PF; ++sb) prefetch_sb(sb); - } else if (dec) { - for (size_t o = 128 * (size_t) uj; o < geo.d_row + 127; o += 256) pf_l2(wrow + min(o, geo.d_row - 1)); - } - __syncthreads(); // the previous item is done with the buffers - if (tid < TR) srow[tid] = tid < nrows ? (GU ? src[row0 + tid] : row0 + tid) : -1; - __syncthreads(); // srow - // the rows past the item's end are not loaded: a warp entirely past it skips the products, and the columns - // of a partial one are never written (no reduction mixes columns) - auto load_act = [&](int s) { - uint8_t* st = stages + (s % ASTAGES) * ACT_STAGE; - for (int c = tid; c < TR * 5; c += THREADS) { - const int r = c / 5, q = c % 5; - if (r < nrows) cp16(st + r * AB + q * 16, act + (size_t) srow[r] * ACT_LD + s * AB + q * 16); - } - }; - auto put = [&](const uint32_t (&raw)[5], int buf) { - if (!dec) return; - uint32_t q[8]; - float s0, s1; - convert(raw, sgrid, kv, q, s0, s1); - uint4* d = (uint4*) (wt + buf * WT_BYTES + ur * WLD + 32 * uj); - d[0] = make_uint4(q[0], q[1], q[2], q[3]); - d[1] = make_uint4(q[4], q[5], q[6], q[7]); - *(float2*) (ws + buf * WS_FLOATS + ur * 4 + 2 * uj) = make_float2(s0, s1); - }; -#pragma unroll - for (int s = 0; s < ASTAGES - 1; ++s) { - if (s < NS) load_act(s); - cp_commit(); - } - uint32_t raw[5] = {0, 0, 0, 0, 0}; - if (dec) load_unit(unit(0), sub(0), raw); - put(raw, 0); - if (dec) load_unit(unit(1), sub(1), raw); - // a warp whose rows are all past the tile's end only takes part in the loads - const bool on0 = nb0 < nrows, on1 = nb0 + 8 < nrows; - float acc[4][2][4]; -#pragma unroll - for (int i = 0; i < 4; ++i) -#pragma unroll - for (int n = 0; n < 2; ++n) -#pragma unroll - for (int q = 0; q < 4; ++q) acc[i][n][q] = 0.0f; - for (int s = 0; s < NS; ++s) { - cp_wait(); - __syncthreads(); - if (s + ASTAGES - 1 < NS) load_act(s + ASTAGES - 1); - cp_commit(); - if (GU && (s & 3) == 0) prefetch_sb((s >> 2) + PF); - if (on0) { - const uint8_t* W = wt + (s & 1) * WT_BYTES; - const float* S = ws + (s & 1) * WS_FLOATS; - const uint8_t* sa = stages + (s % ASTAGES) * ACT_STAGE; - // the stage's scales: per weight row 4 (per 16 values), per routed row 2 (per 32) - float2 dx[2][2]; // [n8 tile][column 2 tig + cc] -#pragma unroll - for (int n = 0; n < 2; ++n) -#pragma unroll - for (int cc = 0; cc < 2; ++cc) dx[n][cc] = *(const float2*) (sa + (nb0 + 8 * n + 2 * tig + cc) * AB + 64); -#pragma unroll - for (int h = 0; h < 2; ++h) { // the stage's two 32-value halves - uint32_t bq[4]; // {n0 bytes 0-15, n0 16-31, n1 0-15, n1 16-31} - ldsm4(bq, sa + b_off + 32 * h); -#pragma unroll - for (int i = 0; i < 4; ++i) { - uint32_t a[4]; // {rows g, g + 8} x {bytes 0-15, 16-31} - ldsm4(a, W + a_off + 16 * i * WLD + 32 * h); - const float2 swa = *(const float2*) (S + (64 * wf + 16 * i + g) * 4 + 2 * h); - const float2 swb = *(const float2*) (S + (64 * wf + 16 * i + 8 + g) * 4 + 2 * h); - const float wa0 = swa.x, wa1 = swa.y, wb0 = swb.x, wb1 = swb.y; -#pragma unroll - for (int n = 0; n < 2; ++n) { - if (n == 1 && !on1) break; - if constexpr (K16) { - // a scale per 16 weights: the two halves' dots, each times its scale, then d_x - int d0[4], d1[4]; - mma16(d0, a[0], a[1], bq[2 * n]); - mma16(d1, a[2], a[3], bq[2 * n + 1]); -#pragma unroll - for (int q = 0; q < 4; ++q) { - const float v = fmaf(q < 2 ? wa1 : wb1, dotf(d1[q]), (q < 2 ? wa0 : wb0) * dotf(d0[q])); - acc[i][n][q] = fmaf(h ? dx[n][q & 1].y : dx[n][q & 1].x, v, acc[i][n][q]); - } - } else { - int d[4]; - mma32(d, a, bq[2 * n], bq[2 * n + 1]); -#pragma unroll - for (int q = 0; q < 4; ++q) { - const float p = (q < 2 ? wa0 : wb0) * (h ? dx[n][q & 1].y : dx[n][q & 1].x); - acc[i][n][q] = fmaf(p, dotf(d[q]), acc[i][n][q]); - } - } - } - } - } - } - // the next stage's weights (into the other buffer, read after the next barrier). (Decoding them before - // this stage's products instead was slower on the RTX 5070: a layer of 2048 / 3584 / 8192 tokens, IQ2_S - // 5.2 / 9.5 / 17.5 ms -> 6.0 / 10.2 / 18.3.) - if (s + 1 < NS) { - put(raw, (s + 1) & 1); - if (dec && s + 2 < NS) load_unit(unit(s + 2), sub(s + 2), raw); - } - } - if (!on0) continue; - if (GU) { - // SwiGLU of feature (WR / 2) fb + 32 wf + 8 i + g (lane g of m tile i: rows 64 wf + 16 i + g and + 8), tile - // rows nb0 + 8 n + 2 tig + c; H to int8 per row over the warp's 32 features (one 32-value half-block of the - // down product's K) - const int blk = WW * fb + wf; -#pragma unroll - for (int n = 0; n < 2; ++n) { - if (n == 1 && !on1) break; -#pragma unroll - for (int c = 0; c < 2; ++c) { - float h[4], am = 0.0f; -#pragma unroll - for (int i = 0; i < 4; ++i) { - const float gt = acc[i][n][c], up = acc[i][n][2 + c]; - h[i] = gt / (1.0f + __expf(-gt)) * up; - am = fmaxf(am, fabsf(h[i])); - } -#pragma unroll - for (int o = 4; o < 32; o <<= 1) am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, o)); - const float inv = am > 0.0f ? 127.0f / am : 0.0f; - const int r = nb0 + 8 * n + 2 * tig + c; - if (r < nrows) { - uint8_t* o = out + (size_t) (row0 + r) * (H_BLOCKS * AB) + (blk >> 1) * AB; - 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); - if (g == 0) *(float*) (o + 64 + 4 * hh) = am / 127.0f; - } - } - } - } else { -#pragma unroll - for (int i = 0; i < 4; ++i) -#pragma unroll - for (int n = 0; n < 2; ++n) { - if (n == 1 && !on1) break; -#pragma unroll - for (int q = 0; q < 4; ++q) { - const int r = nb0 + 8 * n + 2 * tig + (q & 1); - if (r < nrows) dm[(size_t) (row0 + r) * n_embd + rbase + 64 * wf + 16 * i + 8 * (q >> 1) + g] = acc[i][n][q]; - } - } - } - } -#endif -} - -unsigned blocks(int64_t n, int per) { return (unsigned) ((n + per - 1) / per); } - -// per device: whether every kernel here runs (sm_80+, device code in this build, fits), and their occupancy -struct DevInfo { - bool done = false, ok = false; - int sms = 0, occ = 1; -}; -std::mutex g_mu; -DevInfo g_dev[32]; - -#if !defined(STRATA_HIP_GFX906) -template bool setup_ww(int& occ) { - cudaFuncAttributes fa{}; - if (cudaFuncGetAttributes(&fa, native_kernel) != cudaSuccess || fa.ptxVersion < 80) return false; - if (cudaFuncSetAttribute(native_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, - (int) smem_bytes(T, WW)) != cudaSuccess) - return false; - int o = 0; - if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&o, native_kernel, THREADS, smem_bytes(T, WW)) != - cudaSuccess || o < 1) - return false; - occ = std::min(occ, o); - return true; -} -template bool setup_one(int& occ) { return setup_ww(occ) && setup_ww(occ); } -#endif - -const DevInfo& dev_info() { - int dev = 0; - cudaGetDevice(&dev); - std::lock_guard lk(g_mu); - DevInfo& d = g_dev[dev & 31]; - if (d.done) return d; - d.done = true; -#if defined(STRATA_HIP_GFX906) - // gfx906 reports compute capability 9.0 through HIP, but the mma.sync bodies above are CUDA sm_80+ only and - // empty in a hipcc build: never available here (the prompt path keeps its own expert GEMMs) - return d; -#else - int major = 0; - cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); - cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev); - if (major < 8) return d; - int occ = 1 << 20; - d.ok = setup_one(occ) && setup_one(occ) && setup_one(occ) && - setup_one(occ) && setup_one(occ) && setup_one(occ) && - setup_one(occ) && setup_one(occ); - d.occ = d.ok ? occ : 1; - cudaGetLastError(); -#endif - return d; -} - -bool gu_covered(int t) { - return t == T_IQ2_XXS || t == T_IQ2_XS || t == T_IQ2_S || t == T_IQ3_XXS || t == T_IQ3_S || t == T_IQ4_XS; -} -bool d_covered(int t) { return t == T_Q2_0 || t == T_IQ4_NL; } - -template -void launch(int ww, unsigned grid, const Batch& b, const NativeGeom& g, const Tables& tb, const void* act, - const int32_t* src, void* out, float* dm, cudaStream_t s) { - const uint8_t* a = (const uint8_t*) act; - uint8_t* o = (uint8_t*) out; - if (ww == 4) native_kernel<<>>(b, g, tb, a, src, o, dm); - else native_kernel<<>>(b, g, tb, a, src, o, dm); -} - -// The work item's shape for a layer of `n` routed rows over `n_expert` experts: 128 routed rows when an expert has -// about one such tile (56 to 112 rows on average), else 64. Measured on the RTX 5070 (tests/cuda/prefill_fused_iq_test, -// a layer of 2048 / 3584 / 8192 tokens, ms, 64 -> 128): IQ2_S 5.2 -> 6.7, 9.5 -> 9.3, 17.5 -> 19.5; IQ2_XXS 4.2 -> -// 5.8, 7.4 -> 7.6, 13.6 -> 16.5; IQ3_S 5.6 -> 6.6, 10.2 -> 8.8, 18.4 -> 19.0; IQ3_XXS 5.1 -> 6.3, 9.1 -> 8.3, 16.5 -> -// 17.5 (256 rows was slower still). STRATA_PF_FUSED_TILE=64|128 forces one. -int pick_ww(int64_t n, int n_expert) { - static const int forced = [] { - const char* v = std::getenv("STRATA_PF_FUSED_TILE"); - const int t = v ? std::atoi(v) : 0; - return t == 64 ? 4 : t == 128 ? 2 : 0; - }(); - if (forced) return forced; - const double avg = (double) n / std::max(n_expert, 1); - return avg > 56.0 && avg <= 112.0 ? 2 : 4; -} - -} // namespace - -bool native_supported(int gu_type, int d_type) { - static const bool off = [] { // STRATA_PF_FUSED_NATIVE=0: the native packs keep MMQ under STRATA_PF_FUSED=1 (A/B) - const char* v = std::getenv("STRATA_PF_FUSED_NATIVE"); - return v != nullptr && v[0] == '0'; - }(); - return !off && requested() && gu_covered(gu_type) && d_covered(d_type) && dev_info().ok; // opt-in (=1) -} - -void quantize_act_native(const float* x, int64_t rows, int64_t cols, void* xa, void* stream) { - if (rows <= 0) return; - const int64_t nblk = rows * (cols / 64); - quant_act_nat_kernel<<>>(x, nblk, (uint8_t*) xa); - ck(cudaGetLastError(), "quantize_act_native"); -} - -void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n, const void* scratch, const void* xa, - const int32_t* src, void* ha, float* dm, void* stream) { - if (b.e1 <= b.e0 || n <= 0) return; - const DevInfo& d = dev_info(); - if (!d.ok || !gu_covered(g.gu_type) || !d_covered(g.d_type)) { - std::fprintf(stderr, "prefill fused experts (native): types %d / %d are not covered here\n", g.gu_type, g.d_type); - std::exit(1); - } - const cudaStream_t s = (cudaStream_t) stream; - const Tables tb = tables(const_cast(scratch), n_expert); - const int ww = pick_ww(n, n_expert); - // the most 64-row tiles the batch can have (every row in it, plus a partial tile per expert) - the items of the - // ones inside a larger item end at once - const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0); - if (g.n_embd % 256 != 0 || g.n_ff % 64 != 0 || (2 * g.n_ff) % weight_rows(ww) != 0 || g.n_embd % weight_rows(ww) != 0) { - std::fprintf(stderr, "prefill fused experts (native): n_embd %lld / n_ff %lld do not tile (n_embd a multiple of 256, " - "2 n_ff and n_embd multiples of %d)\n", (long long) g.n_embd, (long long) g.n_ff, weight_rows(ww)); - std::exit(1); - } - const unsigned g_gu = (unsigned) std::min(tiles * (2 * g.n_ff / weight_rows(ww)), (int64_t) d.sms * d.occ); - const unsigned g_d = (unsigned) std::min(tiles * (g.n_embd / weight_rows(ww)), (int64_t) d.sms * d.occ); - switch (g.gu_type) { - case T_IQ2_XXS: launch(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; - case T_IQ2_XS: launch(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; - case T_IQ2_S: launch(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; - case T_IQ3_XXS: launch(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; - case T_IQ3_S: launch(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; - default: launch(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; - } - if (g.d_type == T_Q2_0) launch(ww, g_d, b, g, tb, ha, src, nullptr, dm, s); - else launch(ww, g_d, b, g, tb, ha, src, nullptr, dm, s); - ck(cudaGetLastError(), "experts_native"); -} - -} // namespace strata::prefill::fused diff --git a/src/prefill/moe_mmq.cu b/src/prefill/moe_mmq.cu deleted file mode 100644 index 00fe653..0000000 --- a/src/prefill/moe_mmq.cu +++ /dev/null @@ -1,268 +0,0 @@ -// src/prefill/moe_mmq.cu - see include/strata/prefill/moe_mmq.hpp. llama.cpp's MMQ (ggml-cuda, MIT) is compiled -// from the pinned llama.cpp checkout the build already takes ggml from; src/prefill/ggml_cuda_host.cu supplies the -// few host symbols of ggml-cuda.cu it references. -#include "strata/prefill/moe_mmq.hpp" - -#include "common.cuh" -#include "mmq.cuh" -#include "quantize.cuh" - -#include -#include - -namespace strata::prefill::mmq { -namespace { - -void ck(cudaError_t e, const char* what) { - if (e != cudaSuccess) { - std::fprintf(stderr, "prefill mmq: %s: %s\n", what, cudaGetErrorString(e)); - std::exit(1); - } -} - -int64_t pad512(int64_t n) { return (n + 511) / 512 * 512; } - -__global__ void copy16_kernel(const uint4* __restrict__ a, int64_t na, const uint4* __restrict__ b, int64_t nb, - uint4* __restrict__ ab_dst, const uint4* __restrict__ c, int64_t nc, uint4* __restrict__ c_dst) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i < na) ab_dst[i] = a[i]; - else if (i < na + nb) ab_dst[i] = b[i - na]; - else if (i < na + nb + nc) c_dst[i - na - nb] = c[i - na - nb]; -} -// copy16_kernel for an MMQ group: blockIdx.y is the expert (first + y) -struct GroupArgs { - const uint8_t* blob[kGatherGroupMax]; - int64_t up_off, down_off, gu_stride, d_stride; // in uint4 -}; -__global__ void copy16_group_kernel(GroupArgs ga, int first, int64_t na, int64_t nc, uint4* __restrict__ gu_dst, - uint4* __restrict__ d_dst) { - const int q = first + (int) blockIdx.y; - const uint4* src = (const uint4*) ga.blob[q]; - uint4* ab = gu_dst + (int64_t) q * ga.gu_stride; - uint4* cd = d_dst + (int64_t) q * ga.d_stride; - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i < na) ab[i] = src[i]; - else if (i < 2 * na) ab[i] = src[ga.up_off + (i - na)]; - else if (i < 2 * na + nc) cd[i - 2 * na] = src[ga.down_off + (i - 2 * na)]; -} -__global__ void copy1_kernel(const uint8_t* __restrict__ a, int64_t na, const uint8_t* __restrict__ b, int64_t nb, - uint8_t* __restrict__ ab_dst, const uint8_t* __restrict__ c, int64_t nc, uint8_t* __restrict__ c_dst) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i < na) ab_dst[i] = a[i]; - else if (i < na + nb) ab_dst[i] = b[i - na]; - else if (i < na + nb + nc) c_dst[i - na - nb] = c[i - na - nb]; -} - -// Strata blob: gate/up codes [1280][640 B], down codes [2560][160 B], gate/up scales [1280][40] f16, down scales -// [2560][10] f16 (the layout of prefill/kernels.cu's blob_dequant_kernel). A GGUF Q2_0 block is {f16 d; 16 code -// bytes} with the same 2-bit codes in the same order, so a block is a scale and a 16-byte run of codes. -__global__ void strata_q2_kernel(const uint8_t* __restrict__ blob, uint16_t* __restrict__ gu, uint16_t* __restrict__ dn) { - constexpr size_t O_D_CODES = (size_t) 1280 * 640, O_GU_SC = O_D_CODES + (size_t) 2560 * 160, - O_D_SC = O_GU_SC + (size_t) 1280 * 40 * 2; - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; // one GGUF block - const int64_t n_gu = 1280LL * 40, n_d = 2560LL * 10; - const uint8_t* codes; - const uint16_t* scale; - uint16_t* out; - if (i < n_gu) { - const int64_t row = i / 40, b = i % 40; - codes = blob + row * 640 + b * 16; - scale = (const uint16_t*) (blob + O_GU_SC) + row * 40 + b; - out = gu + i * 9; - } else if (i < n_gu + n_d) { - const int64_t j = i - n_gu, row = j / 10, b = j % 10; - codes = blob + O_D_CODES + row * 160 + b * 16; - scale = (const uint16_t*) (blob + O_D_SC) + row * 10 + b; - out = dn + j * 9; - } else { - return; - } - const uint4 q = *(const uint4*) codes; - const uint16_t* qh = (const uint16_t*) &q; - out[0] = *scale; -#pragma unroll - for (int k = 0; k < 8; ++k) out[1 + k] = qh[k]; -} - -__global__ void swiglu_kernel(const float* __restrict__ gu, float* __restrict__ h, int64_t rows, int64_t n_ff, - bool interleaved) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= rows * n_ff) return; - const int64_t r = i / n_ff, k = i % n_ff; - const float* row = gu + r * 2 * n_ff; - const float g = interleaved ? row[2 * k] : row[k], u = interleaved ? row[2 * k + 1] : row[n_ff + k]; - h[i] = g / (1.0f + __expf(-g)) * u; -} - -__global__ void iota_kernel(int32_t* dst, int64_t n) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) dst[i] = (int32_t) i; -} - -unsigned blocks(int64_t n) { return (unsigned) ((n + 255) / 256); } - -} // namespace - -bool built() { return true; } - -bool supported(int t) { - switch ((ggml_type) t) { - case GGML_TYPE_Q2_0: -#ifdef STRATA_ORCA_Q4KS_MMQ - case GGML_TYPE_Q5_0: // #296 (Q4_K and Q5_1: STRATA_MMQ_KQUANTS) -#endif - case GGML_TYPE_IQ2_XXS: case GGML_TYPE_IQ2_XS: case GGML_TYPE_IQ2_S: - case GGML_TYPE_IQ3_XXS: case GGML_TYPE_IQ3_S: case GGML_TYPE_IQ4_NL: case GGML_TYPE_IQ4_XS: - 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: - return false; - } -} - -bool fits(int t, int64_t w_rows) { - if (!supported(t)) return false; - // mul_mat_q_case's choice: the "fallback" configs when the rows are not a multiple of 128; then - // mul_mat_q_switch_J's loop - a tile size whose config exists for this card and fits its shared memory - const bool fallback = w_rows % 128 != 0; - const ggml_cuda_device_info& info = ggml_cuda_info(); - for (int id = 0; id < info.device_count; ++id) { - const int cc = info.devices[id].cc; - const size_t smpbo = info.devices[id].smpbo; - bool any = false; - for (int J = 8; J <= 128 && !any; J += 8) { - const ggml_cuda_mmq_config c = ggml_cuda_mmq_get_config((ggml_type) t, J, fallback, cc); - any = c.type != GGML_TYPE_COUNT && mmq_get_nbytes_shared(c, cc) <= smpbo; - } - if (!any) { - static bool said[GGML_TYPE_COUNT] = {}; - if (t >= 0 && t < GGML_TYPE_COUNT && !said[t]) { - said[t] = true; - std::fprintf(stderr, "strata: prompt kernels: llama.cpp's MMQ has no tile for %s (%lld rows) on GPU %d " - "(cc %d, %zu bytes of shared memory per block): that product takes the non-MMQ path " - "(#420)\n", ggml_type_name((ggml_type) t), (long long) w_rows, id, cc, smpbo); - } - return false; - } - } - return true; -} - -size_t matrix_bytes(int t, int64_t rows, int64_t cols) { - return (size_t) rows * (size_t) (cols / ggml_blck_size((ggml_type) t)) * ggml_type_size((ggml_type) t); -} - -size_t q8_bytes(int64_t rows, int64_t cols) { - return (size_t) rows * (size_t) pad512(cols) * sizeof(block_q8_1_mmq) / (4 * QK8_1) + 128 * sizeof(block_q8_1_mmq); -} - -void quantize(const float* x, const int32_t* ids, void* xq, int t, int64_t cols, int64_t ld, int64_t rows, void* stream) { - if (rows <= 0) return; - quantize_mmq_q8_1_cuda(x, ids, xq, (ggml_type) t, cols, ld, rows * ld, rows * ld, pad512(cols), rows, 1, 1, - (cudaStream_t) stream); - ck(cudaGetLastError(), "quantize"); -} - -Context::Context() { - int dev = 0; - cudaGetDevice(&dev); - ctx_ = new ggml_backend_cuda_context(dev); -} -Context::~Context() { delete (ggml_backend_cuda_context*) ctx_; } - -void Context::run(const Product& p, void* stream) { - if (p.n <= 0 || p.max_rows <= 0) return; - const ggml_type t = (ggml_type) p.type; - const int64_t qk = ggml_blck_size(t), bpr = p.w_cols / qk; - const mmq_args a = {(const char*) p.w, t, (const int*) p.xq, p.ids, p.bounds, p.dst, nullptr, - p.w_cols, p.w_rows, p.total_rows, bpr, p.total_rows, p.ld_dst, - p.n, p.n, (int64_t) (p.expert_bytes / ggml_type_size(t)), 0, 0, - 1, 1, 0, 0, 0, - p.max_rows, p.max_rows}; - auto& ctx = *(ggml_backend_cuda_context*) ctx_; - const cudaStream_t s = (cudaStream_t) stream; - switch (t) { -#ifdef STRATA_ORCA_Q4KS_MMQ - case GGML_TYPE_Q5_0: mul_mat_q_case(ctx, a, s); break; -#endif - case GGML_TYPE_Q2_0: mul_mat_q_case(ctx, a, s); break; - case GGML_TYPE_IQ2_XXS: mul_mat_q_case(ctx, a, s); break; - case GGML_TYPE_IQ2_XS: mul_mat_q_case(ctx, a, s); break; - case GGML_TYPE_IQ2_S: mul_mat_q_case(ctx, a, s); break; - case GGML_TYPE_IQ3_XXS: mul_mat_q_case(ctx, a, s); break; - case GGML_TYPE_IQ3_S: mul_mat_q_case(ctx, a, s); break; - case GGML_TYPE_IQ4_NL: mul_mat_q_case(ctx, a, s); break; - case GGML_TYPE_IQ4_XS: mul_mat_q_case(ctx, a, s); break; - case GGML_TYPE_Q8_0: mul_mat_q_case(ctx, a, s); break; -#ifdef STRATA_MMQ_KQUANTS - case GGML_TYPE_Q4_K: mul_mat_q_case(ctx, a, s); break; - case GGML_TYPE_Q5_K: mul_mat_q_case(ctx, a, s); break; - case GGML_TYPE_Q5_1: mul_mat_q_case(ctx, a, s); break; - case GGML_TYPE_Q6_K: mul_mat_q_case(ctx, a, s); break; -#endif - default: - std::fprintf(stderr, "prefill mmq: type %d is not covered\n", (int) t); - std::exit(1); - } - ck(cudaGetLastError(), "mul_mat_q"); -} - -void gather_native(const void* gate, const void* up, size_t gu_half_bytes, const void* down, size_t d_bytes, - void* gu_dst, void* d_dst, void* stream) { - const cudaStream_t s = (cudaStream_t) stream; - const bool a16 = ((uintptr_t) gate | (uintptr_t) up | (uintptr_t) down | (uintptr_t) gu_dst | (uintptr_t) d_dst | - gu_half_bytes | d_bytes) % 16 == 0; - if (a16) { - const int64_t na = (int64_t) gu_half_bytes / 16, nc = (int64_t) d_bytes / 16; - copy16_kernel<<>>((const uint4*) gate, na, (const uint4*) up, na, (uint4*) gu_dst, - (const uint4*) down, nc, (uint4*) d_dst); - } else { - const int64_t na = (int64_t) gu_half_bytes, nc = (int64_t) d_bytes; - copy1_kernel<<>>((const uint8_t*) gate, na, (const uint8_t*) up, na, - (uint8_t*) gu_dst, (const uint8_t*) down, nc, (uint8_t*) d_dst); - } - ck(cudaGetLastError(), "gather_native"); -} - -bool gather_native_group(const GatherGroup& g, size_t up_off, size_t gu_half_bytes, size_t down_off, size_t d_bytes, - void* gu_dst, size_t gu_stride, void* d_dst, size_t d_stride, void* stream) { - if (g.first < 0 || g.n <= g.first || g.n > kGatherGroupMax) return false; - uintptr_t a = (uintptr_t) gu_dst | (uintptr_t) d_dst | up_off | gu_half_bytes | down_off | d_bytes | gu_stride | d_stride; - for (int q = g.first; q < g.n; ++q) a |= (uintptr_t) g.blob[q]; - if (a % 16 != 0) return false; - GroupArgs ga{}; - for (int q = g.first; q < g.n; ++q) ga.blob[q] = g.blob[q]; - ga.up_off = (int64_t) up_off / 16; - ga.down_off = (int64_t) down_off / 16; - ga.gu_stride = (int64_t) gu_stride / 16; - ga.d_stride = (int64_t) d_stride / 16; - const int64_t na = (int64_t) gu_half_bytes / 16, nc = (int64_t) d_bytes / 16; - copy16_group_kernel<<>>( - ga, g.first, na, nc, (uint4*) gu_dst, (uint4*) d_dst); - ck(cudaGetLastError(), "gather_native_group"); - return true; -} - -void gather_strata_q2(const uint8_t* blob, void* gu_dst, void* d_dst, void* stream) { - strata_q2_kernel<<>>(blob, (uint16_t*) gu_dst, - (uint16_t*) d_dst); - ck(cudaGetLastError(), "gather_strata_q2"); -} - -void swiglu(const float* gu, float* h, int64_t rows, int64_t n_ff, bool interleaved, void* stream) { - if (rows <= 0) return; - swiglu_kernel<<>>(gu, h, rows, n_ff, interleaved); - ck(cudaGetLastError(), "swiglu"); -} - -void iota(int32_t* dst, int64_t n, void* stream) { - if (n <= 0) return; - iota_kernel<<>>(dst, n); - ck(cudaGetLastError(), "iota"); -} - -} // namespace strata::prefill::mmq diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp deleted file mode 100644 index 12dc80a..0000000 --- a/src/prefill/prefill.cpp +++ /dev/null @@ -1,3359 +0,0 @@ -// 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" -#include "strata/core/on_device.hpp" - -#include "strata/core/layout.hpp" -#include "strata/kernels/cpu/expert.hpp" -#include "strata/kernels/native_qsa_indexer.hpp" -#include "strata/kernels/ngram.hpp" -#include "strata/kernels/ple.hpp" -#include "strata/kernels/native_ple_postops.hpp" -#include "strata/kernels/iq_kernels.hpp" -#include "strata/kernels/cpu/expert_layout.hpp" -#include "strata/kernels/qsa.hpp" -#include "strata/kernels/kv_stream.hpp" -#include "strata/kernels/cvec.hpp" -#include "strata/kernels/kv_q4.hpp" -#include "strata/core/layer.hpp" -#include "strata/core/native_head.hpp" -#include "strata/kernels/verify_kernels.hpp" -#include "strata/kernels/qsa_decode_attn.hpp" -#include "strata/kernels/qsa_prompt_attn.hpp" -#include "strata/kernels/qsa_select.hpp" -#include "strata/prefill/gemm.hpp" -#include "strata/prefill/moe_fused.hpp" -#include "strata/prefill/moe_fused_iq.hpp" -#include "strata/prefill/moe_mmq.hpp" -#include "strata/core/peer_experts.hpp" -#include "strata/prefill/kernels.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef STRATA_PREFILL_MMQ -// A build without the llama.cpp sources (no STRATA_NATIVE_EXPERTS): no MMQ, the FP16 expert path everywhere. -namespace strata::prefill::mmq { -bool built() { return false; } -bool supported(int) { return false; } -bool fits(int, int64_t) { return false; } -size_t matrix_bytes(int, int64_t, int64_t) { return 0; } -size_t q8_bytes(int64_t, int64_t) { return 0; } -void quantize(const float*, const int32_t*, void*, int, int64_t, int64_t, int64_t, void*) {} -Context::Context() {} -Context::~Context() {} -void Context::run(const Product&, void*) {} -void gather_native(const void*, const void*, size_t, const void*, size_t, void*, void*, void*) {} -bool gather_native_group(const GatherGroup&, size_t, size_t, size_t, size_t, void*, size_t, void*, size_t, void*) { return false; } -void gather_strata_q2(const uint8_t*, void*, void*, void*) {} -void swiglu(const float*, float*, int64_t, int64_t, bool, void*) {} -void iota(int32_t*, int64_t, void*) {} -} // namespace strata::prefill::mmq -#endif -#ifndef STRATA_PREFILL_FUSED -// #136: the fused int8 experts are CUDA-only (HIP and builds without MMQ keep the MMQ / FP16 paths) -namespace strata::prefill::fused { -bool built() { return false; } -bool available() { return false; } -bool enabled() { return false; } -bool requested() { return false; } -size_t act_bytes(int64_t, int64_t) { return 0; } -size_t group_bytes(int64_t, int) { return 0; } -void quantize_act(const float*, int64_t, int64_t, void*, void*) {} -void group(const int32_t*, int64_t, int, int, void*, int32_t*, int32_t*, void*) {} -void experts(const Batch&, int, int64_t, const void*, const void*, const int32_t*, void*, float*, void*) {} -bool native_supported(int, int) { return false; } -void quantize_act_native(const float*, int64_t, int64_t, void*, void*) {} -void experts_native(const Batch&, const NativeGeom&, int, int64_t, const void*, const void*, const int32_t*, void*, - float*, void*) {} -} // namespace strata::prefill::fused -#endif - -namespace strata::prefill { -namespace { - -using Clock = std::chrono::steady_clock; -constexpr float EPS = 1e-6f; -// The model's geometry as this path uses it, from ModelGeometry (Qwen3.6 port, step 3: the file-wide constants N 2560, -// HC 4, LR 320, K 10, NE 512, C 10240, ZV 6144, HV 48 became these members; docs/QWEN36-35B-A3B.md section 3.6). -// Every function below takes it from Impl (or builds it from the ModelGeometry it was given) and names the members -// as the constants were named, so the arithmetic reads as before. -struct Geom { - int64_t n = 2560; ///< n_embd - int64_t hc = 4, d = 10240, lr = 320; ///< hyper-connection streams, hc * n_embd, the bottleneck (hc 1: no GR) - int64_t k = 10, ne = 512, ff = 640; ///< experts per token, experts, expert width - int64_t ff2 = 1280, ffs = 640; ///< 2 * n_ff (gate | up rows), the shared expert's width - int64_t c = 10240, zv = 6144, hv = 48, hk = 16; ///< GDN: conv channels, value dim, value heads, key heads - int64_t nh = 24, nkv = 2, hd = 256; ///< attention heads, KV heads, head dim - int64_t qf = 24 * 512, av = 6144, kvw = 512; ///< attn_q's width (q | gate per head), n_head * 256, n_head_kv * 256 - bool indexer = true; ///< the QSA indexer (Flash-Next); Qwen3.6's attention is dense - strata::kernels::GdnGate gate = strata::kernels::GdnGate::Sigmoid; ///< the GDN output gate (ModelGeometry::gdn_gate) - static Geom of(const core::ModelGeometry& g) { - Geom o; - o.n = g.n_embd; o.hc = g.hc; o.d = g.hc * g.n_embd; o.lr = g.hc_lr; - o.k = g.n_expert_used; o.ne = g.n_expert; o.ff = g.n_ff; o.ff2 = 2 * g.n_ff; o.ffs = g.n_ff_shexp; - o.c = g.ssm_conv_channels; o.zv = g.ssm_value_dim; o.hv = g.ssm_v_heads; o.hk = g.ssm_k_heads; - o.nh = g.n_head; o.nkv = g.n_head_kv; o.hd = g.head_dim; - o.qf = g.n_head * 2 * g.head_dim; o.av = g.n_head * g.head_dim; o.kvw = g.n_head_kv * g.head_dim; - o.indexer = g.has_indexer(); - o.gate = g.gdn_gate(); - return o; - } - GdnGeom gdn() const { return GdnGeom{(int) hv, (int) hk, (int) c, gate}; } -}; -// The largest expert count any pack has (the peer path's event ring and host bounds are sized once from it). -constexpr int64_t NE_MAX = 512; -// 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()) -constexpr int kSplitHelpRing = 48; // layer split help: the helper stage's ring slots it streams through (at most) -// Step 3: from this chunk size on, every non-resident expert of every layer streams in a fixed order through a -// ring_slots()-slot ring (nearly all 512 are routed at such a chunk), so the copy engine keeps working through the -// attention halves instead of waiting for each layer's routing. -constexpr int RING_MAX = 1024; // the arrays; the ring itself is ring_slots(), at most ring_cap() -// The chunk size from which every expert streams: 1024 since 0.1.30 (was 2048). Measured on the 5070, Q2_0 / IQ2_XS, -// fixed cache: 1,500-token prompts 621 -> 785 / 612 -> 735 tok/s, 2,000 727 -> 934 / 712 -> 892, 4,000 (its last -// chunk) 779 -> 912 / 766 -> 844, the same output. Below ~1,000 tokens the output changed on Q2_0 (a smaller chunk -// takes other kernels), so 1024 is the floor. STRATA_PREFILL_STREAM_MIN overrides (A/B). -inline int64_t stream_all_min() { - static const int64_t v = [] { const char* e = std::getenv("STRATA_PREFILL_STREAM_MIN"); return e ? (int64_t) std::atoll(e) : (int64_t) 1024; }(); - return v; -} -double g_pinned_share = 1.0; -// The streamed ring: 384 slots when (nearly) every streamed expert is DMA'd from pinned RAM - measured on Q2_0, -// 8192-token chunks: 96 slots 1153 tok/s, 384 1294 (the next layer's experts arrive during its attention half) - -// and 96 when a large share goes through host copies (IQ3_S on 64 GB, a third unpinned: 96 slots 1216, 256 1070 - -// the host copies are the limit and the bigger ring only takes cache slots). STRATA_PREFILL_RING overrides. -// -// Those are slots on the pack they were measured on, and a slot is one WHOLE expert blob - a Q2_0 blob is -// 1,382,400 B, so 384 slots is 506 MiB. On a pack with bigger blobs the same slot count is a different amount of -// memory: 1,912 MiB on Q8_0 (5,222,400 B), which is more than half of an 8 GB card's expert cache and what held -// that card at a 1,024-token chunk when its own buffers would have fitted 6,144. Measured on the 4-way rig, one -// env var and nothing else: chunk 1,024 -> 6,144, prefill 87 -> 402 tok/s. So the budget is kept in BYTES and the -// slot count is derived from the pack (`ring_budget_slots`); Q2_0 still resolves to exactly 1024 (fused) and 384, -// so the pack all of this was tuned on does not move. -int g_ring_override = 0; // #340: set by a layer split (Prefill::set_ring_override); 0 = the rule below -// #583 (0.1.39b): the auto chunk scan's byte-budget ring (Prefill::set_ring_budget), for requests whose chunk is above -// g_ring_small_max - the chunk 0.1.39's rule would have picked. A prompt that fits that chunk keeps 0.1.39's ring: -// on one chunk the smaller ring only slowed it (RTX 5070, 4K prompts: Coder -15%, IQ3_S -5%, IQ3_XXS -2%). -int g_ring_budget = 0; -int64_t g_ring_small_max = 0; -// #136: the fused experts (STRATA_PF_FUSED=1) launch on a batch of a layer's streamed experts at once, so the ring -// should hold a whole layer's (~460 of 512 on Q2_0): with 384 slots a layer's last batch waits for slots its own -// first batch frees. Measured on the 5070, Q2_0, the 4K / 32K code-agent prompts (one run each): fused at 384 slots -// +5% / +3% over MMQ, at 512 +19-22% / +11-12% (MMQ itself at 512: -2% / -1%). P3: with the fused path's smaller -// buffers (moe_bufs) 1024 slots - two layers' experts - fit too; 2 pairs each, prompt tok/s at 512 / 1024 slots: 4K -// 1,512 / 1,605, 32K 2,485 / 2,660 (both chunk 8192), 128K with KV streaming 2,346 / 2,392 (the chunk falls from -// 8192 to 6144, but more experts stay resident). A native pack likewise when the native kernels (moe_fused_iq.hpp) -// take any of its layers: IQ2_XS, 4K / 32K, their first version at 384 slots -3% / -6% against MMQ, at 512 +8% / 0%. -inline bool fused_ring() { - if (!fused::enabled()) return false; - if (core::peer_portable()) return false; // multi-GPU: --peer-device keeps the MMQ path and its buffer sizes - const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout(); - if (!lay.native) return true; - // EVERY layer: fused_layout() shrinks the MoE buffers to the fused path's needs, so a layer the native kernels do - // not cover (Unsloth UD-IQ4_XS's Q8_0 down projections) would run MMQ in them at the full chunk and overflow them - // (garbage, an illegal memory access or a hung prompt on gfx1151). A pack with such a layer keeps MMQ's buffers; - // its covered layers still take the fused kernels. - static const bool all = [&lay] { - for (const auto& f : lay.fmt) - if (!fused::native_supported(f.gu_type, f.d_type)) return false; - return !lay.fmt.empty(); - }(); - return all; -} -// the largest ring: 512 slots; 1024 with the Q2_0 pack's fused experts (P3's smaller buffers, measured there) - the -// native packs' fused layers were measured at 512 -inline int ring_cap() { return fused_ring() && !strata::kernels::cpu::expert_layout().native ? RING_MAX : 512; } -// The ring's budget in bytes: the measured slot counts above, at the blob size they were measured with. It is -// bytes and not slots because a slot is one whole blob and the blob is the pack's - see the note above. -inline constexpr uint64_t Q2_0_BLOB = 1382400ull; // the blob of the pack the ring was tuned on -inline uint64_t ring_bytes() { - const uint64_t slots = fused_ring() ? 1024ull : 384ull; // #136: a fused ring holds two layers' experts - return (g_pinned_share >= 0.9 ? slots : slots / 4) * Q2_0_BLOB; -} -// ...and what that buys on THIS pack, never past ring_cap(): the slot count `init` lays out, and what the auto -// chunk scan treats as a full ring. A pack whose blobs are larger than Q2_0's gets fewer slots for the same -// bytes, which is the point - the ring competes with the expert cache for the same VRAM. -// 0.1.39b: on by default (#583); STRATA_RING_BYTES=0 restores 0.1.39's ring, loan and auto chunk list. It moves the -// prompt path's loan on a native pack (fewer ring slots, the rest kept as cache slots, a larger auto chunk), so a long -// prompt's experts are read through a different mix of resident and streamed groups and its bits differ from 0.1.39's -// (RTX 5070, IQ3_XXS, 32K prompt: +14% to +26%; teacher-forced against the FP16 prompt path in the same band). -inline bool ring_bytes_on() { - static const bool on = [] { const char* v = std::getenv("STRATA_RING_BYTES"); return v == nullptr || v[0] != '0'; }(); - return on; -} -inline int ring_budget_slots() { - const int64_t per = MAXBLOB(); - const int64_t n = per > 0 ? (int64_t) (ring_bytes() / (uint64_t) per) : 0; - const int cap = ring_cap(); - return (int) (n <= 0 ? 0 : (n > cap ? cap : n)); -} -inline int ring_slots(size_t T) { - const char* v = std::getenv("STRATA_PREFILL_RING"); -#if defined(STRATA_USE_HIP) - // S6: with the opt-in RDNA4 matrix-core attention (STRATA_HIP_WMMA=1) a 96-slot ring: measured with it, 9070 XT - // 4K prompts 718 -> 1,211 tok/s (16K 1,949 -> 2,032), R9700 4K 2,426 -> 2,483 (16K the same) - static const bool wmma = [] { - const char* e = std::getenv("STRATA_HIP_WMMA"); - return e != nullptr && e[0] == '1'; - }(); - if (!v && g_ring_override <= 0 && wmma) return (int64_t) T >= stream_all_min() ? 96 : STAGE; -#endif - // the byte budget as this pack's slots: 1024 fused / 384 not on Q2_0, fewer on a pack with bigger blobs. The - // unpinned arm stays a slot count (96): it was measured where the host copies are the limit, and there the ring - // is not what is competing for VRAM. - // 0.1.39's ring (1024 fused / 384 pinned, 96 when a large share goes through host copies), and the #583 byte - // budget the auto scan chose for chunks past the size 0.1.39's rule would have picked (set_ring_budget) - const int pinned_ring = g_pinned_share >= 0.9 ? (fused_ring() ? 1024 : 384) : 96; - const bool budget = ring_bytes_on() && g_ring_budget > 0 && (int64_t) T > g_ring_small_max; - const int r = v ? std::atoi(v) : g_ring_override > 0 ? g_ring_override : budget ? g_ring_budget : pinned_ring; - if (v && r == STAGE) return STAGE; // Explicit opt-in to routed-only staging, including large chunks. - const int big = r < 16 ? 16 : r > ring_cap() ? ring_cap() : r; - return (int64_t) T >= stream_all_min() ? big : STAGE; -} -constexpr int DQ = 2; // dequantized-expert ring (FP16 gate/up + down) -// The BF16-weight projections (hyper-connection, SSM alpha/beta, indexer, router, shared gate, PLE key/value) take -// BF16 activations here and FP32 ones in decode. STRATA_PREFILL_BF16X2=1 adds each activation's BF16 remainder as a -// second GEMM (Y = W.hi + W.lo, ~16 mantissa bits): a router that picks its top 10 from the same x decode would. -// 2 = all but the hyper-connection's; 1 = the hyper-connection's too (its activations are 10240 wide and its up -// projection writes as much: slower); 0 (the default: opt-in, it changes the prompt path's numbers) = off. -inline int bf16x2_mode() { - static const int v = [] { - const char* e = std::getenv("STRATA_PREFILL_BF16X2"); - return e != nullptr ? std::atoi(e) : 0; - }(); - return v; -} -inline bool bf16x2() { return bf16x2_mode() != 0; } -inline bool bf16x2_hc() { return bf16x2_mode() == 1; } - -// F-1: STRATA_GR_UNFUSED=1 keeps the FP32 copy of the normalized rows (gr_norm + gr_mix), the A/B arm -inline bool gr_unfused() { - static const bool v = [] { const char* e = std::getenv("STRATA_GR_UNFUSED"); return e && e[0] == '1'; }(); - return v; -} - -double ms_since(Clock::time_point t) { return std::chrono::duration(Clock::now() - t).count(); } - -// Either cudaMalloc (owned, freed with the object) or a bump allocation from a borrowed region; with no base and -// no region it only counts, which is how `bytes_needed` sizes the region. -struct Alloc { - uint8_t* base = nullptr; - uint64_t cap = 0, used = 0; - bool count_only = false; - std::vector* owned = nullptr; - template T* take(size_t n, bool& ok) { - const uint64_t bytes = ((uint64_t) n * sizeof(T) + 256 + 255) & ~255ull; - if (count_only) { used += bytes; return nullptr; } - if (base != nullptr) { - if (used + bytes > cap) { - if (std::getenv("STRATA_PREFILL_ALLOC_TRACE")) // which take overflowed its region (a count/carve mismatch) - std::fprintf(stderr, "prefill alloc: %llu bytes do not fit (%llu of %llu used)\n", (unsigned long long) bytes, - (unsigned long long) used, (unsigned long long) cap); - ok = false; - return nullptr; - } - T* p = (T*) (base + used); - used += bytes; - return p; - } - void* p = nullptr; - if (const cudaError_t e = cudaMalloc(&p, bytes); e != cudaSuccess) { - if (std::getenv("STRATA_PREFILL_ALLOC_TRACE")) - std::fprintf(stderr, "prefill alloc: cudaMalloc of %llu bytes: %s\n", (unsigned long long) bytes, cudaGetErrorString(e)); - cudaGetLastError(); - ok = false; - return nullptr; - } - owned->push_back(p); - used += bytes; - return (T*) p; - } -}; - -} // namespace - -// Step 4 of the prompt-speed plan: the experts the arena could not pin (a third of the streamed ones on IQ3_S) are -// copied into pinned buffers by these threads, ahead of the launches. Copied in line by the launching thread they -// left the GPU without queued work while each ~2 MB memcpy ran (~15 s of a 32K prompt on IQ3_S). Job j - a layer's -// j-th unpinned expert, in launch order - lands in host buffer j % kRing, which is free again once the DMA of job -// j - kRing (recorded by the launching thread, `issued`) is done. -struct Stager { - // D-5: the pinned ring's depth (STRATA_STAGER_RING, default 16) - how far the host copies can run ahead of the - // DMAs of the unpinned experts' blobs - int kRing = 16; - // `from` set: the blob is copied by the source itself (CS-T: a GGUF read in place assembles it from its three - // role slices; a pointer to it would not live as long as the queue) - struct Job { const uint8_t* src; size_t bytes; core::ExpertSource* from = nullptr; int32_t l = 0, e = 0; }; - std::vector buf; - std::vector pinned; - std::vector> pageable; // the fallback when no more RAM can be pinned - std::vector dma_done; - std::vector jobs; - std::unique_ptr[]> ready; - size_t ready_cap = 0; - // gen << 32 | n << 16 | next index: a claim is a CAS on the generation it woke for (a thread late from the - // previous layer can never take a job of this one - the expert pool's issue #29 lesson) - std::atomic head{0}; - std::atomic issued{0}, active{0}; - uint32_t gen = 0; - bool quit = false; - std::mutex mu; - std::condition_variable cv; - std::vector threads; - int device = 0; - - bool init(size_t blob_bytes, int nthreads) { - if (const char* v = std::getenv("STRATA_STAGER_RING")) kRing = std::clamp(std::atoi(v), 2, 256); - buf.assign((size_t) kRing, nullptr); - pinned.assign((size_t) kRing, 0); - dma_done.assign((size_t) kRing, nullptr); - pageable.resize(kRing); - for (int i = 0; i < kRing; ++i) { - pinned[i] = cudaHostAlloc((void**) &buf[i], blob_bytes, cudaHostAllocDefault) == cudaSuccess; - if (!pinned[i]) { - cudaGetLastError(); - pageable[(size_t) i].resize(blob_bytes); - buf[i] = pageable[(size_t) i].data(); - } - if (cudaEventCreateWithFlags(&dma_done[i], cudaEventDisableTiming) != cudaSuccess) return false; - } - cudaGetDevice(&device); - for (int t = 0; t < nthreads; ++t) threads.emplace_back([this] { work(); }); - return true; - } - ~Stager() { - finish(); - { std::lock_guard lk(mu); quit = true; } - cv.notify_all(); - for (auto& t : threads) t.join(); - for (int i = 0; i < kRing; ++i) { - if (dma_done[i]) cudaEventDestroy(dma_done[i]); - if (buf[i] && pinned[i]) cudaFreeHost(buf[i]); - } - } - void work() { - cudaSetDevice(device); - uint32_t seen = 0; - for (;;) { - { - std::unique_lock lk(mu); - cv.wait(lk, [&] { return quit || gen != seen; }); - if (quit) return; - seen = gen; - } - for (;;) { - active.fetch_add(1, std::memory_order_acq_rel); - const int j = claim(seen); - if (j < 0) { active.fetch_sub(1, std::memory_order_acq_rel); break; } - const int b = j % kRing; - if (j >= kRing) // job j - kRing's DMA from this buffer is queued - while (issued.load(std::memory_order_acquire) <= j - kRing) std::this_thread::yield(); - // and done - for a generation's first kRing jobs that is the previous generation's last DMA from - // the buffer, which nothing else waits for when a chunk ends without a sync (no MTP) or the DMA - // was a ring entry the routing skipped (an event never recorded returns at once) - cudaEventSynchronize(dma_done[b]); - const Job& jb = jobs[(size_t) j]; - if (jb.from == nullptr) std::memcpy(buf[b], jb.src, jb.bytes); - else if (!jb.from->copy_blob(jb.l, jb.e, buf[b])) { - std::fprintf(stderr, "prefill: the expert source could not copy expert %d of layer %d\n", jb.e, jb.l); - std::abort(); - } - ready[(size_t) j].store(1, std::memory_order_release); - active.fetch_sub(1, std::memory_order_acq_rel); - } - } - } - int claim(uint32_t g) { - uint64_t cur = head.load(std::memory_order_acquire); - for (;;) { - if ((uint32_t) (cur >> 32) != g) return -1; - const int n = (int) ((cur >> 16) & 0xffff), j = (int) (cur & 0xffff); - if (j >= n) return -1; - if (head.compare_exchange_weak(cur, cur + 1, std::memory_order_acq_rel, std::memory_order_acquire)) return j; - } - } - /// A layer's jobs; the previous layer's are finished (finish()). - void start(std::vector&& js) { - if (js.empty()) return; - std::lock_guard lk(mu); - jobs = std::move(js); - if (ready_cap < jobs.size()) { - ready_cap = jobs.size() * 2; - ready.reset(new std::atomic[ready_cap]); - } - for (size_t i = 0; i < jobs.size(); ++i) ready[i].store(0, std::memory_order_relaxed); - issued.store(0); - ++gen; - head.store((uint64_t) gen << 32 | (uint64_t) jobs.size() << 16, std::memory_order_release); - cv.notify_all(); - } - /// Job j's bytes, in a pinned buffer (waits for the copy). - const uint8_t* wait(int j) { - while (!ready[(size_t) j].load(std::memory_order_acquire)) std::this_thread::yield(); - return buf[j % kRing]; - } - /// The launching thread queued job j's DMA on `copy`: its buffer is free once that is done. - void issued_one(int j, cudaStream_t copy) { - cudaEventRecord(dma_done[j % kRing], copy); - issued.store(j + 1, std::memory_order_release); - } - /// No job is running after this (the end of a layer, or an early return in the middle of one). - void finish() { - head.store((uint64_t) gen << 32, std::memory_order_release); // n = 0: nothing more to claim - issued.store(1 << 30, std::memory_order_release); - while (active.load(std::memory_order_acquire) != 0) std::this_thread::yield(); - } -}; - -// multi-GPU: the peer GPU's share of a prompt chunk's experts. Per MoE layer the primary copies its normed -// activations over P2P, the peer quantizes the rows routed to the experts it holds, runs the same MMQ products the -// primary would (gathered from its own slots), and copies the result rows back into the primary's Dm rows - the rows -// are laid out local-first, so the peer's are one contiguous block at the end. -struct PeerPrefill { - core::PeerExperts* peer = nullptr; - int dev = -1; - int64_t cap_rows = 0, T_max = 0; - cudaStream_t s = nullptr; - cudaEvent_t ev_in = nullptr; // on the primary: the activations and the row tables are ready - cudaEvent_t ev_done = nullptr; // on the peer: its rows have landed in the primary's Dm - // multi-GPU: the result rows go back group by group on a second stream while the next group computes - cudaStream_t s_out = nullptr; - static constexpr int kGrpEv = NE_MAX / 16 + 2; // sized for the largest pack; a smaller one uses fewer - 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; - // multi-GPU COMPACT: the peer's per-row buffers hold one GROUP's rows instead of the layer's (a group - // = up to 16 experts and at most G rows), the result rows double-buffered: ~0.9 GB -> ~0.26 GB on the helper - // card at 8192-token chunks, and no row cap (every peer-held expert's rows go to the peer). - // STRATA_PF_PEER_COMPACT=0: the layer-sized buffers (the A/B). - bool compact = true; - int64_t G = 0; - void *Xq_g = nullptr, *Hq_g = nullptr; - float *GU_g = nullptr, *H_g = nullptr, *Dm_b[2] = {}; - cudaEvent_t ev_dm[2] = {}; - bool dm_live[2] = {}; - std::vector> groups; - // multi-GPU PEER STREAMING: a share of the experts the primary would stream over ITS PCIe link in a - // big chunk is streamed by the peer over its own link instead (into its own ring) and computed there - it halves - // the primary's copy load and moves expert work to the card that idles through most of the MoE half. - // STRATA_PF_PEER_STREAM = the share (0 = off), STRATA_PF_PEER_RING = its ring slots. - double ps_frac = 0.0; - int RP = 0; - std::vector pstage; - std::vector pcopied, pused; - std::vector plive; - cudaStream_t s_cp = nullptr; - struct PsEntry { int32_t l, e; const uint8_t* blob; }; - std::vector pseq; // this chunk's peer-streamed experts, layer by layer in id order - std::vector pseq_start; - std::vector ps_flag; // [layer * NE + e]: streamed by the peer in this chunk - size_t p_issued = 0, pk = 0; - int64_t ps_experts = 0; - float *mixed = nullptr, *GU = nullptr, *H = nullptr, *Dm = nullptr; - void *Xq = nullptr, *Hq = nullptr; - int32_t *src = nullptr, *bounds = nullptr, *ident = nullptr; - uint8_t *grp_gu = nullptr, *grp_d = nullptr; - std::unique_ptr ctx; - mmq::Context* run_ctx = nullptr; // the context its products run in: ctx, or a layer split helper stage's - // Without P2P (a layer split's helper) the activations and the result rows go through MAPPED pinned host buffers: the device that needs them reads them with a copy kernel. A copy-engine - // upload would queue behind the expert blobs that device's streams already hold (up to a ring of them, ~70 us - // each - the grouping tables' reason for mapped memory too), and cudaMemcpyPeerAsync would be staged by the - // driver. `back_at` / `back_rows`: the rows this layer sends back. - bool p2p = true; - // The row table and the group bounds go the same way: the primary's are pinned for its own device only (or - // pageable), and a copy from them on the peer's stream would hold up the host until that stream is idle. - float* host_x = nullptr; // T x N activations (mapped, portable) - float* host_rows = nullptr; // the peer's result rows (mapped, portable) - int32_t* host_src = nullptr; // the peer's rows' tokens (mapped, portable) - int32_t* host_bounds = nullptr; // its group bounds (mapped, portable) - size_t host_x_cap = 0, host_rows_cap = 0, host_src_cap = 0; // elements - static constexpr size_t kHostBounds = 2 * (NE_MAX + NE_MAX / 16 + 2) + 64; - int64_t back_at = 0, back_rows = 0; - std::vector bounds_host; - std::vector owned; - int64_t layers = 0, experts = 0, rows = 0, over_cap = 0; // stats - ~PeerPrefill() { - if (dev < 0) return; - int prev = 0; - cudaGetDevice(&prev); - cudaSetDevice(dev); - if (s) cudaStreamSynchronize(s); - ctx.reset(); - for (void* p : owned) cudaFree(p); - if (ev_done) cudaEventDestroy(ev_done); - if (s_out) cudaStreamSynchronize(s_out); - for (cudaEvent_t e : ev_grp) if (e) cudaEventDestroy(e); - for (cudaEvent_t e : ev_dm) if (e) cudaEventDestroy(e); - if (s_cp) cudaStreamSynchronize(s_cp); - for (cudaEvent_t e : pcopied) if (e) cudaEventDestroy(e); - for (cudaEvent_t e : pused) if (e) cudaEventDestroy(e); - if (s_cp) cudaStreamDestroy(s_cp); - if (s_out) cudaStreamDestroy(s_out); - if (s) cudaStreamDestroy(s); - cudaSetDevice(prev); - if (ev_in) cudaEventDestroy(ev_in); - if (host_x) cudaFreeHost(host_x); - if (host_rows) cudaFreeHost(host_rows); - if (host_src) cudaFreeHost(host_src); - if (host_bounds) cudaFreeHost(host_bounds); - } -}; - -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; - const int32_t* host_res = nullptr; - int64_t T = 0, T_max = 0; - bool borrowed = false; - cudaStream_t cs = nullptr, copy = nullptr; - Gemm gemm; - std::vector owned; - // chunk buffers - float *emb = nullptr, *R = nullptr, *xn = nullptr, *lo = nullptr, *gated = nullptr, *inj = nullptr; - float* grs = nullptr; // F-1: the hyper-connection read's row scales (T x 4) - uint16_t *xn16 = nullptr, *lo16 = nullptr; - float* mixed = nullptr; - uint16_t *mixed_bf = nullptr, *mixed_h = nullptr; - uint16_t *xn16_lo = nullptr, *lo16_lo = nullptr, *mixed_bf_lo = nullptr; // bf16x2(): the BF16 GEMMs' low parts - float* bo = nullptr; - // GDN - float *qkv = nullptr, *z = nullptr, *ab = nullptr, *gate = nullptr, *beta = nullptr, *hbuf = nullptr, *y = nullptr; - uint16_t* y_h = nullptr; - // QSA - float *Kc = nullptr, *Vc = nullptr, *Qf = nullptr, *q = nullptr, *idx_raw = nullptr, *q_idx = nullptr, *attn = nullptr; - uint16_t* attn_h = nullptr; - int32_t* steps_dev = nullptr; - std::vector steps_host; - int32_t* sel_ids = nullptr; - float* sel_scores = nullptr; // [sel_batch, max_blocks] - int64_t sel_batch = 256, max_blocks = 0; - float* attn_scratch = nullptr; - int64_t attn_batch = 32, cap = 0; - // MoE - float *logits = nullptr, *w = nullptr, *GU = nullptr, *Dm = nullptr, *sgate = nullptr, *sup = nullptr, - *shared = nullptr, *sg = nullptr; - int32_t *ids = nullptr, *slot_dev = nullptr, *src_dev = nullptr; - uint16_t *Xs = nullptr, *Hh = nullptr, *sh_h = nullptr; - // step 2b (MMQ): the activations quantized per layer, H in FP32 and its group's quantized rows, the identity - // row map, the group bounds, the group buffers of gathered experts - void *Xq = nullptr, *Hq = nullptr; - float* H = nullptr; - int32_t *ids_identity = nullptr, *bounds_dev = nullptr; - uint8_t *grp_gu = nullptr, *grp_d = nullptr; - std::vector bounds_host; - std::unique_ptr mmq_ctx; - std::vector ids_host, slot_host, src_host, cnt, off; - // The grouping tables in mapped pinned memory, [ids | slot | src] of T_max * K each, then the MMQ bounds: kernels - // read and write them in place. A cudaMemcpyAsync of them queues behind the expert blobs the copy stream already - // holds (up to `ring` of them, ~70 us each), and the GPU idles meanwhile - measured 4.2 s of a 128K prompt's - // 70 s at the default ring, 0.7 s with a 16-slot one. STRATA_GROUP_COPY=1: the copies (the A/B arm). - int32_t* grp_host = nullptr; - int32_t* grp_dev = nullptr; // its device alias - size_t grp_n = 0, grp_tk = 0; // int32s allocated; T_max * K (the offset of slot, and of src past it) - uint16_t* dq_gu[DQ] = {}; - uint16_t* dq_d[DQ] = {}; - uint8_t* stage_dev[RING_MAX] = {}; - int ring = STAGE; // the slots of this layout's ring (ring_slots) - std::unique_ptr stager; // the unpinned experts' host copies (step 4) - cudaEvent_t copied[RING_MAX] = {}, used[RING_MAX] = {}; - bool stage_live[RING_MAX] = {}; - // the event that releases each ring slot: its own `used`, or - when an MMQ group is gathered in one launch - the - // `used` of the last slot gathered with it, recorded once for all of them (a later record only waits longer) - int used_of[RING_MAX] = {}; - // PLE - float* ple_emb = nullptr; - std::vector ple_pageable[2]; // the fallback when no more RAM can be pinned - float* ple_emb_host[2] = {}; // pinned, double-buffered: the next chunk's rows are read while this - cudaEvent_t ple_copied[2] = {}; // one runs; the event marks that buffer's upload done - std::vector ple_rows[2]; - float* ple_norm = nullptr; - uint8_t* region = nullptr; // the attention/MoE scratch region (idle while the PLE block runs) - uint64_t region_bytes = 0; - PrefillStats* stats = nullptr; - // KV streaming: one layer's whole K/V, staged from the host copy per layer and chunk (identity layout) - strata::kernels::KvHostPools stage; - int32_t* ident_table = nullptr; - // layer split: the device, and the hand-off to the next stage (two pinned chunk buffers, used in turn) - int device = -1; - float* hand[2] = {}; - // C-4: the chunk's token ids on the device, for one batched embedding gather - int32_t* tok_dev = nullptr; - std::vector tok_host; - std::unique_ptr pp; // multi-GPU: the peer GPU's expert share (set_peer) - // layer split: the next stage's GPU as a stream-only peer (set_stage_helper); its buffers are that stage's own - // prompt buffers, bound per prompt, and it takes the place of `pp` for a run it helps - std::unique_ptr help_pp; -}; - -namespace { -// the staging pool of a streamed session: every page of one layer (same sequence in init and bytes_needed) -// STRATA_KV_STAGE_OWN (A/B only): the staging pool gets its own allocation instead of borrowed expert slots, so a -// streamed run lends the prompt path exactly the slots a resident one does (a lent expert runs on the CPU, which -// rounds differently: without this an A/B compares two expert placements as well as two KV placements) -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; - Alloc own; - own.owned = o_borrowed.owned; - Alloc& o = stage_own() ? own : o_borrowed; - const size_t rows = (size_t) q0.n_pages * s.n_head_kv * s.page_size; - if (q0.kv_q4) { - st.k_q4 = o.take(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok); - st.v_q4 = o.take(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok); - } else if (q0.kv_int8) { - st.k_q = o.take(rows * s.head_dim, ok); - st.v_q = o.take(rows * s.head_dim, ok); - st.k_scale = o.take(rows * (s.head_dim / 64), ok); - st.v_scale = o.take(rows * (s.head_dim / 64), ok); - } else { - st.k_pool = o.take(rows * s.head_dim, ok); - st.v_pool = o.take(rows * s.head_dim, ok); - } -} -strata::kernels::QsaAttnPools pools_of(const strata::kernels::KvHostPools& h, const int32_t* table) { - strata::kernels::QsaAttnPools p; - p.k_pool = h.k_pool; p.v_pool = h.v_pool; p.k_q = h.k_q; p.v_q = h.v_q; p.k_scale = h.k_scale; p.v_scale = h.v_scale; - p.k_q4 = h.k_q4; p.v_q4 = h.v_q4; - p.page_table = table; - return p; -} -} // namespace - -Prefill::Prefill() : impl_(new Impl) {} -Prefill::~Prefill() { release(); } - -void Prefill::reset() { - release(); - impl_.reset(new Impl); - stats_ = PrefillStats{}; -} - -void Prefill::release() { - if (!impl_) return; - if (impl_->cs) cudaStreamSynchronize(impl_->cs); - if (impl_->copy) cudaStreamSynchronize(impl_->copy); - for (int i = 0; i < RING_MAX; ++i) { - if (impl_->copied[i]) cudaEventDestroy(impl_->copied[i]); - if (impl_->used[i]) cudaEventDestroy(impl_->used[i]); - } - for (int b = 0; b < 2; ++b) { - if (impl_->hand[b]) cudaFreeHost(impl_->hand[b]); - if (impl_->ple_copied[b]) cudaEventDestroy(impl_->ple_copied[b]); - if (impl_->ple_emb_host[b] && impl_->ple_pageable[b].empty()) cudaFreeHost(impl_->ple_emb_host[b]); - } - if (impl_->copy) cudaStreamDestroy(impl_->copy); - if (impl_->grp_host) cudaFreeHost(impl_->grp_host); - for (void* p : impl_->owned) cudaFree(p); -} - -namespace { -constexpr int64_t GEMM_SCRATCH = 32ll << 20; // FP16 elements for the largest dequantized dense weight -constexpr size_t GEMM_WS = 32u << 20; // cuBLAS workspace - -// THE ATTENTION HALF AND THE MoE HALF SHARE THEIR BUFFERS. A layer runs its attention (GDN or QSA), writes it back -// into the residual, and only then its MoE, so the three sets of scratch are never live at once: one region the size -// of the largest holds them all. That is ~260 KB of the ~680 KB a prompt token cost - which is what lets a chunk -// grow (every expert is streamed once per chunk, so a bigger chunk streams fewer bytes per token). The sizes are -// counted with the same `take` sequence `init` uses; a mismatch makes `init` fail with "do not fit", never overlap. -uint64_t gdn_set_bytes(size_t T, const Geom& G) { - const int64_t C = G.c, ZV = G.zv, HV = G.hv; - Alloc a; a.count_only = true; bool ok = true; - a.take(T * C, ok); a.take(T * ZV, ok); a.take(T * 2 * HV, ok); a.take(T * HV, ok); - a.take(T * HV, ok); a.take(T * C, ok); a.take(T * ZV, ok); a.take(T * ZV, ok); - return a.used; -} -// the indexer's two buffers (the raw key, the query) only with an indexer; the dense model carves none -uint64_t qsa_set_bytes(size_t T, int64_t cap, int64_t max_blocks, int64_t sel_batch, int64_t attn_batch, - const strata::kernels::QsaShapes& s, const Geom& G) { - Alloc a; a.count_only = true; bool ok = true; - a.take(T * G.kvw, ok); a.take(T * G.kvw, ok); a.take(T * G.qf, ok); a.take(T * G.av, ok); - if (G.indexer) { a.take(T * s.idx_dim, ok); a.take(T * s.idx_n_head * s.idx_dim, ok); } - a.take(T * G.av, ok); a.take(T * G.av, ok); - if (G.indexer) a.take(T * (size_t) cap, ok); // dense attention carries no ids (a null is the identity) - if (G.indexer) a.take((size_t) sel_batch * (size_t) max_blocks, ok); - a.take((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(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). -constexpr int MMQ_GROUP = 16; // experts per MMQ launch (the gather is per expert, as blobs arrive) -// MMQ reads up to one 256-value tile past a matrix's last row when the row length is not a multiple of it (the down -// product: 640 values). Those bytes meet zero activations, which is harmless only if they decode to finite numbers - -// llama.cpp zero-pads after every tensor, and so does a group buffer: this many zeroed bytes follow its last expert. -constexpr size_t MMQ_TAIL = 4096; -struct MmqPlan { - bool any = false, fallback = true; - std::vector layer; // per layer: MMQ - size_t gu_max = 0, d_max = 0; -}; -const MmqPlan& mmq_plan() { - static const MmqPlan plan = [] { - MmqPlan p; - const auto& lay = strata::kernels::cpu::expert_layout(); - const char* env = std::getenv("STRATA_PREFILL_MMQ"); - const bool on = mmq::built() && (env == nullptr || std::atoi(env) != 0); - const int64_t layers = lay.native ? (int64_t) lay.fmt.size() : lay.n_layers; - p.layer.assign((size_t) std::max(layers, 0), 0); - p.fallback = !on || layers <= 0; - for (int64_t l = 0; on && l < layers; ++l) { - const int gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42, dt = lay.native ? lay.fmt[(size_t) l].d_type : 42; - // the layer's widths: the native pack's own (2048 / 512 for Qwen3.6), the canonical Q2_0 pack's 2560 / 640 - const int64_t n_embd = lay.native ? lay.fmt[(size_t) l].n_embd : 2560; - const int64_t n_ff = lay.native ? lay.fmt[(size_t) l].n_ff : 640; - // #420: a tile on every GPU for these shapes (gate+up: 2 n_ff rows, down: n_embd rows), else the FP16 path - if (!mmq::fits(gt, 2 * n_ff) || !mmq::fits(dt, n_embd)) { p.fallback = true; continue; } - p.layer[(size_t) l] = 1; - p.any = true; - p.gu_max = std::max(p.gu_max, mmq::matrix_bytes(gt, 2 * n_ff, n_embd)); - p.d_max = std::max(p.d_max, mmq::matrix_bytes(dt, n_embd, n_ff)); - } - return p; - }(); - return plan; -} -// #136 P3: a layout whose chunks run the fused experts (STRATA_PF_FUSED=1, the Q2_0 pack, a streamed chunk of -// stream_all_min() tokens or more). Its GU, H and Xq hold only the fused path's grouping tables, int8 H and per-token -// int8 activations, and Hq nothing: ~100 KB a token less than MMQ's FP32 GU / H and per-slot q8_1 rows, which is what -// lets a bigger chunk or ring fit in the slots the prompt path borrows. A last chunk below stream_all_min() still runs -// MMQ in the same buffers, so each keeps MMQ's size for stream_all_min() - 1 tokens. `src`: the layout streams experts -// (Prefill::init got an ExpertSource; without one no chunk takes the streamed walk, so no chunk is fused). -bool fused_layout(size_t T, bool src) { - return src && fused_ring() && mmq_plan().any && ring_slots(T) > STAGE && (int64_t) T >= stream_all_min(); -} -// The MoE buffers MMQ and the fused path share: GU and H in floats, Xq and Hq in bytes. Without `fused` (the -// default): MMQ's, for T tokens. -struct MoeBufs { size_t gu, h, xq, hq; }; -MoeBufs moe_bufs(size_t T, const Geom& G, bool fused) { - const int64_t K = G.k, N = G.n, FF = G.ff, FF2 = G.ff2; - if (!fused) return {T * K * FF2, T * K * FF, mmq::q8_bytes((int64_t) (T * K), N), mmq::q8_bytes((int64_t) (T * K), FF)}; - const size_t ts = (size_t) std::min((int64_t) T, stream_all_min() - 1); // MMQ's last small chunk - return {std::max(ts * K * FF2, (fused::group_bytes((int64_t) (T * K), (int) G.ne) + 3) / 4), - std::max(ts * K * FF, (fused::act_bytes((int64_t) (T * K), FF) + 3) / 4), - std::max(mmq::q8_bytes((int64_t) (ts * K), N), fused::act_bytes((int64_t) T, N)), - mmq::q8_bytes((int64_t) (ts * K), FF)}; -} -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, G, fused); - Alloc a; a.count_only = true; bool ok = true; - a.take(T * G.ne, ok); a.take(T * K, ok); a.take(T * K, ok); a.take(T * K, ok); - a.take(T * K, ok); - if (mp.fallback) a.take(T * K * N, ok); - a.take(mb.gu, ok); - if (mp.fallback) a.take(T * K * FF, ok); - a.take(T * K * N, ok); a.take(T * FFS, ok); - a.take(T * FFS, ok); a.take(T * FFS, ok); a.take(T * N, ok); a.take(T, ok); - if (mp.any) { - a.take(mb.xq, ok); - a.take(mb.h, ok); - a.take(mb.hq, ok); - } - return a.used; -} -} - -bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, core::SessionState& ss, - core::ExpertSource* src, const core::ExpertCache* cache, const int32_t* host_res, int64_t chunk, - void* stream, std::string& err, void* borrow, uint64_t borrow_bytes) { - Impl& m = *impl_; - m.wt = &wt; m.g = &g; m.ss = &ss; m.src = src; m.cache = cache; m.host_res = host_res; - m.T = chunk; m.cs = (cudaStream_t) stream; m.stats = &stats_; - m.geo = Geom::of(g); - const Geom& G = m.geo; - const int64_t D = G.d, K = G.k, N = G.n; - // The geometries this path is built for: Flash-Next's (the hyper-connection kernels at 2560 / 4 / 320, top-10) and - // Qwen3.6's (the plain block, hc 1, the GDN kernels forked at 32 / 16 / 8192, top-8 of 256). Everything else in - // the layer loop is runtime; what is not (the GDN head geometry, the head size, the KV layout) is refused here by - // name rather than mis-indexed below. - if (g.arch == core::ModelArch::Qwen4Exp) { - if (g.n_embd != 2560 || g.hc != 4 || g.hc_lr != 320 || ss.k != 10 || g.n_expert_used != 10) { - err = "prefill: geometry differs from the artifact's (Flash-Next: n_embd 2560, hc 4, hc_lr 320, top-10)"; - return false; - } - } else if (g.hc != 1) { - err = "prefill: qwen35moe with hc " + std::to_string(g.hc) + " (the plain block has one residual stream)"; - return false; - } - if (g.n_expert < 1 || ss.k != g.n_expert_used || ss.k < 1 || ss.k > 32 || ss.k > g.n_expert) { - err = "prefill: top-" + std::to_string(ss.k) + " routing over " + std::to_string(g.n_expert) + - " experts (the file says top-" + std::to_string(g.n_expert_used) + "; k must be 1..32 and at most n_expert)"; - return false; - } - if (!gdn_geometry_supported((int) g.ssm_v_heads, (int) g.ssm_k_heads, (int) g.ssm_conv_channels) || g.ssm_state_size != 128 || - g.ssm_d_conv != 4) { - err = "prefill: no GDN kernels for " + std::to_string(g.ssm_v_heads) + " value heads / " + std::to_string(g.ssm_k_heads) + - " key heads / " + std::to_string(g.ssm_conv_channels) + " conv channels (built for 48/16/10240 and 32/16/8192, " - "state 128, conv 4)"; - return false; - } - if (g.head_dim != 256 || g.n_head_kv != 2 || g.n_rot != 64 || g.n_embd % 256 != 0 || g.n_ff % 64 != 0) { - err = "prefill: the attention and expert kernels take head_dim 256, 2 KV heads, n_rot 64, n_embd a multiple of 256 " - "and n_ff a multiple of 64"; - return false; - } - cudaGetDevice(&m.device); - if (stage_le_ < 0) stage_le_ = g.n_layers; - if (stage_lb_ < 0 || stage_lb_ >= stage_le_ || stage_le_ > g.n_layers || (stage_le_ < g.n_layers) != (next_ != nullptr)) { - err = "prefill: the stage's layer range is wrong"; - return false; - } - for (int b = 0; next_ != nullptr && b < 2; ++b) - if (!m.hand[b] && cudaHostAlloc((void**) &m.hand[b], (size_t) chunk * D * 4, cudaHostAllocPortable) != cudaSuccess) { - err = "prefill: the layer split's hand-off buffers"; - return false; - } - if (m.tok_dev == nullptr) { - if (const cudaError_t e = cudaMalloc((void**) &m.tok_dev, (size_t) chunk * sizeof(int32_t)); e != cudaSuccess) { - err = std::string("prefill: the token id buffer (") + cudaGetErrorString(e) + ")"; - return false; - } - m.owned.push_back(m.tok_dev); - m.tok_host.resize((size_t) chunk); - } - if (cudaStreamCreateWithFlags(&m.copy, cudaStreamNonBlocking) != cudaSuccess) { err = "prefill: copy stream"; return false; } - const size_t T = (size_t) chunk; - m.T_max = chunk; - m.borrowed = borrow != nullptr; - bool ok = true; - // one-time: events, the stager, the host buffers (for the largest chunk), the identity page table - for (int i = 0; i < ring_cap(); ++i) { - if (cudaEventCreateWithFlags(&m.copied[i], cudaEventDisableTiming) != cudaSuccess) ok = false; - if (cudaEventCreateWithFlags(&m.used[i], cudaEventDisableTiming) != cudaSuccess) ok = false; - } - if (!m.stager) { - m.stager = std::make_unique(); - const int hw = (int) std::thread::hardware_concurrency(); - const char* stv = std::getenv("STRATA_STAGER_THREADS"); // D-5: the host copy threads of unpinned blobs - // A GGUF read in place (UD-Q4_K_XL beyond its RAM budget): most of a chunk's blobs are page faults on the - // SSD, so the copies need many reads in flight - 32 threads and a 128-deep ring read a 4K chunk in 29 s - // instead of 71 s on an RTX 5070 / NVMe PC (4 threads, 16 deep: the defaults, kept for every other source) - bool files = false; - for (int64_t l = 0; src != nullptr && !files && l < g.n_layers; ++l) - for (int64_t e = 0; !files && e < g.n_expert; ++e) files = src->transient(l, e); - const int threads = stv ? std::clamp(std::atoi(stv), 1, 32) : files ? 32 : std::max(2, std::min(4, hw / 4)); - if (files && std::getenv("STRATA_STAGER_RING") == nullptr) m.stager->kRing = 4 * threads; - if (!m.stager->init((size_t) MAXBLOB(), threads)) ok = false; - } - m.steps_host.resize(T * strata::kernels::kStepCount); - m.ids_host.resize(T * K); m.slot_host.resize(T * K); m.src_host.resize(T * K); m.cnt.resize(m.g->n_expert); m.off.resize(m.g->n_expert + 1); - { - const size_t need = 3 * T * K + (size_t) (2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2)); - const char* gc = std::getenv("STRATA_GROUP_COPY"); - if (m.grp_n < need && !(gc && gc[0] == '1')) { - if (m.grp_host) cudaFreeHost(m.grp_host); - m.grp_host = m.grp_dev = nullptr; - m.grp_n = m.grp_tk = 0; - void *h = nullptr, *d = nullptr; - if (cudaHostAlloc(&h, need * 4, cudaHostAllocMapped | (core::peer_portable() ? cudaHostAllocPortable : 0)) == cudaSuccess && - cudaHostGetDevicePointer(&d, h, 0) == cudaSuccess) { - m.grp_host = (int32_t*) h; - m.grp_dev = (int32_t*) d; - m.grp_n = need; - m.grp_tk = T * K; - } else { // the copies, as before - if (h) cudaFreeHost(h); - cudaGetLastError(); - } - } - } - for (int b = 0; b < 2; ++b) { - if (!m.ple_emb_host[b] && - cudaHostAlloc((void**) &m.ple_emb_host[b], (size_t) T * N * 4, cudaHostAllocDefault) != cudaSuccess) { - cudaGetLastError(); - m.ple_pageable[b].resize(T * N); // pageable: the upload is staged before it returns - m.ple_emb_host[b] = m.ple_pageable[b].data(); - } - if (!m.ple_copied[b] && cudaEventCreateWithFlags(&m.ple_copied[b], cudaEventDisableTiming) != cudaSuccess) - ok = false; - m.ple_rows[b].resize(T * strata::kernels::PLE_N_HEADS); - } - if (ss.qsa_alloc > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1) { // KV streaming: the staging pool's identity page table - const int64_t pages = ss.qsa_states[ss.qsa_primary()].n_pages; - std::vector ident((size_t) pages); - for (int64_t i = 0; i < pages; ++i) ident[(size_t) i] = (int32_t) i; - if (cudaMalloc((void**) &m.ident_table, ident.size() * 4) != cudaSuccess || - cudaMemcpy(m.ident_table, ident.data(), ident.size() * 4, cudaMemcpyHostToDevice) != cudaSuccess) - ok = false; - else - m.owned.push_back(m.ident_table); - } - if (!ok) { err = "prefill: host buffers or events for a chunk of " + std::to_string(chunk) + " tokens"; return false; } - Alloc o; - o.base = (uint8_t*) borrow; - o.cap = borrow_bytes; - o.owned = &m.owned; - { - uint16_t* gs = o.take((size_t) GEMM_SCRATCH, ok); - void* ws = o.take(GEMM_WS, ok); - if (!ok) { err = "prefill: GEMM scratch does not fit"; return false; } - if (!m.gemm.init_external(stream, gs, GEMM_SCRATCH, ws, GEMM_WS, err)) return false; - } - if (!carve(T, &o)) { - err = "prefill: device buffers for a chunk of " + std::to_string(chunk) + " tokens do not fit"; - return false; - } - return true; -} - -// Every device buffer of a chunk of T tokens, from the Alloc `alloc` (after the GEMM scratch and workspace): `init` -// once, and `relayout` for a request's own chunk. The order is `bytes_needed`'s. -bool Prefill::carve(size_t T, void* alloc) { - Impl& m = *impl_; - Alloc& o = *static_cast(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(T * N, ok); m.R = o.take(T * D, ok); - m.xn = gr && gr_unfused() ? o.take(T * D, ok) : nullptr; // F-1: not needed (gr_mix_r reads R) - m.grs = gr ? o.take(T * HC, ok) : nullptr; - m.xn16 = gr ? o.take(T * D, ok) : nullptr; - m.lo = gr ? o.take(T * LR, ok) : nullptr; m.lo16 = gr ? o.take(T * LR, ok) : nullptr; - m.gated = gr ? o.take(T * D, ok) : nullptr; m.inj = gr ? o.take(T * HC, ok) : nullptr; - m.mixed = o.take(T * N, ok); m.mixed_bf = o.take(T * N, ok); - m.mixed_h = o.take(T * N, ok); m.bo = o.take(T * N, ok); - if (gr && bf16x2_hc()) { m.xn16_lo = o.take(T * D, ok); m.lo16_lo = o.take(T * LR, ok); } - if (bf16x2()) m.mixed_bf_lo = o.take(T * N, ok); - m.steps_dev = o.take(T * strata::kernels::kStepCount, ok); - const strata::kernels::QsaShapes s = shapes_of(g); - m.cap = selection_cap(ss, s); - m.max_blocks = primary_cells(ss) / s.idx_block + 2; - { - // one region for the attention half's and the MoE half's scratch (see gdn_set_bytes) - const bool fz = fused_layout(T, m.src != nullptr); - const MoeBufs mb = moe_bufs(T, G, fz); - const uint64_t region = std::max({gdn_set_bytes(T, G), qsa_set_bytes(T, m.cap, m.max_blocks, m.sel_batch, - m.attn_batch, s, G), moe_set_bytes(T, G, fz)}); - uint8_t* base = o.take((size_t) region, ok); - m.region = base; - m.region_bytes = region; - Alloc a; - a.base = base; a.cap = region; a.owned = &m.owned; - m.qkv = a.take(T * C, ok); m.z = a.take(T * ZV, ok); m.ab = a.take(T * 2 * HV, ok); - m.gate = a.take(T * HV, ok); m.beta = a.take(T * HV, ok); m.hbuf = a.take(T * C, ok); - m.y = a.take(T * ZV, ok); m.y_h = a.take(T * ZV, ok); - Alloc b; - b.base = base; b.cap = region; b.owned = &m.owned; - m.Kc = b.take(T * G.kvw, ok); m.Vc = b.take(T * G.kvw, ok); m.Qf = b.take(T * G.qf, ok); - m.q = b.take(T * G.av, ok); - m.idx_raw = G.indexer ? b.take(T * s.idx_dim, ok) : nullptr; - m.q_idx = G.indexer ? b.take(T * s.idx_n_head * s.idx_dim, ok) : nullptr; - m.attn = b.take(T * G.av, ok); m.attn_h = b.take(T * G.av, ok); - m.sel_ids = G.indexer ? b.take(T * (size_t) m.cap, ok) : nullptr; - m.sel_scores = G.indexer ? b.take((size_t) m.sel_batch * (size_t) m.max_blocks, ok) : nullptr; - m.attn_scratch = b.take((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(T * G.ne, ok); m.w = c.take(T * K, ok); m.ids = c.take(T * K, ok); - m.slot_dev = c.take(T * K, ok); m.src_dev = c.take(T * K, ok); - const MmqPlan& mp = mmq_plan(); - m.Xs = mp.fallback ? c.take(T * K * N, ok) : nullptr; - m.GU = c.take(mb.gu, ok); - m.Hh = mp.fallback ? c.take(T * K * G.ff, ok) : nullptr; - m.Dm = c.take(T * K * N, ok); - m.sgate = c.take(T * G.ffs, ok); m.sup = c.take(T * G.ffs, ok); m.sh_h = c.take(T * G.ffs, ok); - m.shared = c.take(T * N, ok); m.sg = c.take(T, ok); - if (mp.any) { - m.Xq = c.take(mb.xq, ok); - m.H = c.take(mb.h, ok); - m.Hq = c.take(mb.hq, ok); - } - if (base == nullptr) ok = false; - } - for (int i = 0; i < DQ; ++i) { m.dq_gu[i] = o.take((size_t) (G.ff2 * N), ok); m.dq_d[i] = o.take((size_t) (N * G.ff), ok); } - if (mmq_plan().any) { - const MmqPlan& mp = mmq_plan(); - m.ids_identity = o.take(T * K, ok); - m.bounds_dev = o.take((size_t) (2 * (G.ne + G.ne / MMQ_GROUP + 2)), ok); - m.grp_gu = o.take(MMQ_GROUP * mp.gu_max + MMQ_TAIL, ok); - m.grp_d = o.take(MMQ_GROUP * mp.d_max + MMQ_TAIL, ok); - // (written at every run's start, not here: when serving, these are live expert-cache slots until a request - // lends them - a write now would corrupt a resident expert) - if (!m.mmq_ctx) m.mmq_ctx = std::make_unique(); - } - m.ring = ring_slots(T); - for (int i = 0; i < m.ring; ++i) { - m.stage_dev[i] = o.take((size_t) MAXBLOB(), ok); - m.stage_live[i] = false; // a new buffer: nothing of an earlier layout to wait for - m.used_of[i] = i; - } - m.ple_emb = g.has_ple ? o.take(T * N, ok) : nullptr; - m.ple_norm = g.has_ple ? o.take((size_t) strata::kernels::NG_HC_DIM, ok) : nullptr; - take_stage(o, ss, s, m.stage, ok); - m.T = (int64_t) T; - return ok; -} - -bool Prefill::relayout(int64_t chunk, void* borrow, uint64_t borrow_bytes, std::string& err) { - Impl& m = *impl_; - if (!m.borrowed || borrow == nullptr || chunk <= 0 || chunk > m.T_max) { - err = "prefill: relayout needs borrowed buffers and a chunk of at most " + std::to_string(m.T_max); - return false; - } - if (cudaStreamSynchronize(m.cs) != cudaSuccess || cudaStreamSynchronize(m.copy) != cudaSuccess) { - err = "prefill: relayout: the stream failed"; - return false; - } - bool ok = true; - Alloc o; - o.base = (uint8_t*) borrow; - o.cap = borrow_bytes; - o.owned = &m.owned; - uint16_t* gs = o.take((size_t) GEMM_SCRATCH, ok); - void* ws = o.take(GEMM_WS, ok); - if (ok) m.gemm.rebind(gs, GEMM_SCRATCH, ws, GEMM_WS); - if (!ok || !carve((size_t) chunk, &o)) { - err = "prefill: device buffers for a chunk of " + std::to_string(chunk) + " tokens do not fit"; - return false; - } - return true; -} - -int64_t Prefill::chunk() const { return impl_->T; } - -bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, - std::string& err) { - Impl& m = *impl_; - static const bool off = [] { const char* v = std::getenv("STRATA_MTP_BATCH"); return v != nullptr && v[0] == '0'; }(); - // A ring (KV streaming: the drafter's window, page p in slot p % n_slots over a host copy) takes the same appends - // with its own page table and host copy, as a streamed main layer does; the cells written are those the window can - // still reach (r0 below), which the ring holds, so no two of them share a slot. STRATA_MTP_BATCH_RING=0: the - // 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) - return false; - const auto t0 = Clock::now(); - const core::ModelGeometry& g = *m.g; - const int64_t Nn = g.n_embd, HCN = g.hc * g.n_embd, KV = g.n_head_kv * g.head_dim, HC = m.geo.hc, LR = m.geo.lr; - 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(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(n - r0, (int64_t) (m.region_bytes / per_row) & ~(int64_t) 63); - if (st.kv_mode == 2) - B = std::min(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 tk((size_t) B); - if (q8) { - if (!m.mmq_ctx) m.mmq_ctx = std::make_unique(); - 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"); - const void* w_fh = mtp.tensor_q8("fc_hidden.weight"); - const float* w_hn = mtp.tensor_f32("attn_hyper_connection.hc_norm.weight"); - const uint16_t* w_dn = mtp.tensor_bf16("attn_hyper_connection.input_mix_weight_down.weight"); - const uint16_t* w_up = mtp.tensor_bf16("attn_hyper_connection.input_mix_weight_up.weight"); - const void* w_k = mtp.tensor_q8("self_attn.k_proj.weight"); - const void* w_v = mtp.tensor_q8("self_attn.v_proj.weight"); - const float* w_kn = mtp.tensor_f32("self_attn.k_norm.weight"); - if (!w_ne || !w_fe || !w_nh || !w_fh || !w_hn || !w_dn || !w_up || !w_k || !w_v || !w_kn) return false; - const core::NativeEmbed* nemb = core::native_embed(); - const core::WeightRef* wemb = nemb ? nullptr : m.wt->find("token_embd.weight"); - if (!nemb && (wemb == nullptr || wemb->codebook_iq4nl || wemb->ne0 != g.n_embd || wemb->group_elems <= 0 || - (wemb->code_bits != 2 && wemb->code_bits != 4 && wemb->code_bits != 8))) - return false; - // the cells the drafter's window can still reach - const int64_t r0 = std::max(0, mtp.first_needed() - cell0); - 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 - 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); - int64_t B = std::min(n - r0, (int64_t) (m.region_bytes / per_row) & ~(int64_t) 63); - if (st.kv_mode == 2) // a ring: one batch's cells must not share a slot (a batch can straddle one page more) - B = std::min(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); - float* e2 = (float*) carve((size_t) B * Nn * 4); - uint16_t* en16 = (uint16_t*) carve((size_t) B * Nn * 2); - float* hn = (float*) carve((size_t) B * HCN * 4); - float* h2 = (float*) carve((size_t) B * HCN * 4); - float* Rm = (float*) carve((size_t) B * HCN * 4); - float* gated = (float*) carve((size_t) B * HCN * 4); - uint16_t* hn16 = (uint16_t*) carve((size_t) B * HCN * 2); - uint16_t* xn16 = (uint16_t*) carve((size_t) B * HCN * 2); - float* lo = (float*) carve((size_t) B * LR * 4); - uint16_t* lo16 = (uint16_t*) carve((size_t) B * LR * 2); - float* grs = (float*) carve((size_t) B * HC * 4); - float* mixed = (float*) carve((size_t) B * Nn * 4); - uint16_t* mixed_h = (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 * g.hc, Nn)) : nullptr; - 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; - 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 tk((size_t) B); - if (q8) { - if (!m.mmq_ctx) m.mmq_ctx = std::make_unique(); - mmq::iota(ident, B * g.hc, m.cs); - } - // y[rows, n_out] = x[rows, k] . w^T for a Q8_0 matrix: MMQ from the FP32 rows (bounds slot 0: rows, 1: rows*hc) - auto proj = [&](const float* x, const uint16_t* x16, const void* w, float* y, int64_t rows, int64_t n_out, - int64_t k, int slot) { - if (!q8) { m.gemm.native(x16, kQ8_0, w, y, rows, n_out, k); return; } - mmq::quantize(x, nullptr, xq, kQ8_0, k, k, rows, m.cs); - mmq::Product p; - p.w = w; p.type = kQ8_0; p.w_rows = n_out; p.w_cols = k; p.expert_bytes = mmq::matrix_bytes(kQ8_0, n_out, k); - p.n = 1; p.xq = xq; p.bounds = bnd + 2 * slot; 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 * g.hc)}; - if (q8 && cudaMemcpyAsync(bnd, bh, sizeof bh, cudaMemcpyHostToDevice, m.cs) != cudaSuccess) { - err = "prefill: the draft bounds' upload failed"; - return false; - } - if (cudaMemcpyAsync(tok, tk.data(), (size_t) nb * 4, cudaMemcpyHostToDevice, m.cs) != cudaSuccess) { - err = "prefill: the draft tokens' upload failed"; - return false; - } - // the input branches: the next token's embedding, and this cell's final residual rows - if (nemb) { - nemb->gather_dev(tok, nb, emb, m.cs); - } else { - const auto* codes = (const uint8_t*) wemb->data; - const auto* scales = (const float*) (codes + wemb->codes_bytes); - const auto* offsets = wemb->has_offset ? (const float*) (codes + wemb->codes_bytes + wemb->scales_bytes) - : nullptr; - strata::kernels::embedding_gather_dev(codes, scales, offsets, tok, (int) nb, wemb->ne0, wemb->code_bits, - wemb->code_bias, wemb->group_elems, - (uint64_t) (wemb->ne0 / (8 / wemb->code_bits)), - (uint64_t) (wemb->ne0 / wemb->group_elems), emb, m.cs); - } - rms_rows(emb, w_ne, nb, Nn, Nn, EPS, m.cs); - if (!q8) to_f16(emb, en16, nb * Nn, m.cs); - proj(emb, en16, w_fe, e2, nb, Nn, Nn, 0); - cudaMemcpyAsync(hn, R_rows + (size_t) b0 * HCN, (size_t) nb * HCN * 4, cudaMemcpyDeviceToDevice, m.cs); - rms_rows(hn, w_nh, nb, HCN, HCN, EPS, m.cs); - if (!q8) to_f16(hn, hn16, nb * HCN, m.cs); - proj(hn, hn16, w_fh, h2, nb * g.hc, Nn, Nn, 1); // every stream through fc_hidden - strata::kernels::add_streams_broadcast(h2, e2, Rm, Nn, (int) g.hc, (int) nb, m.cs); - // the attention hyper-connection's read (its mixed input only: this pass writes nothing back) - gr_norm_rs(Rm, w_hn, EPS, grs, xn16, nb, m.cs); - m.gemm.bf16(xn16, w_dn, lo, nb, LR, HCN); - gr_silu(lo, lo16, nb, m.cs); - m.gemm.bf16(lo16, w_up, gated, nb, HCN, LR); - gr_mix_r(Rm, grs, w_hn, gated, mixed, nullptr, nb, m.cs, mixed_h); - // K and V into the drafter's cache, as the prompt path's QSA layers append theirs - proj(mixed, mixed_h, w_k, Kc, nb, KV, Nn, 0); - proj(mixed, mixed_h, w_v, Vc, nb, KV, Nn, 0); - 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) { // rotated as the drafter's own decode stores them (mtp.cpp) - 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: %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; -} -namespace { -// Layer split: STRATA_PREFILL_HELP=1 lends the idle stage's GPU (opt-in: the helped rows are computed in another MMQ -// grouping and round differently from the default, like STRATA_SPLIT_OWN). Unset or 0: every stage's prompt experts on -// its own GPU, as before. -bool split_help_env() { - static const bool v = [] { const char* e = std::getenv("STRATA_PREFILL_HELP"); return e != nullptr && std::atoi(e) != 0; }(); - return v; -} -// The share of a stage's streamed experts the idle stage's GPU takes for a one-chunk prompt of T tokens (0: none). -// The streamed bytes are the same at any T; the hand-over (the activations there, the rows back) grows with T and is -// paid per layer whatever the share. Measured on 2x RTX 3090 (UD-Q4_K_XL, PCIe 4.0 x16 each, no P2P), fixed shares -// 0.2 / 0.3 / 0.4 against none: 1.5K tokens 749 / 820 / 908 (none 675), 3K 1335 / 1437 / 1328 (1262), 4K 1622 / 1620 / -// 1440 (1609), 6K 1811 / 1660 / 1471 (2038), 8K 1895 / 1804 / 1663 (2230) - the best share falls with T and from ~4K -// none pays, which this rule follows (0.41 at 1.5K, 0.32 at 3K, off from ~3.3K). -// STRATA_PREFILL_HELP_FRAC sets the share for every T. -double split_help_frac(int64_t T) { - static const double fixed = [] { - const char* e = std::getenv("STRATA_PREFILL_HELP_FRAC"); - return e ? std::clamp(std::atof(e), 0.0, 1.0) : -1.0; - }(); - if (fixed >= 0.0) return fixed; - const double f = std::min(0.45, 0.5 - (double) T / 16384.0); - return f >= 0.3 ? f : 0.0; -} -} // namespace - -bool Prefill::set_stage_helper(Prefill* helper, std::string& err) { - Impl& m = *impl_; - m.help_pp.reset(); - if (helper == nullptr || helper == this || !split_help_env()) return true; - const Impl& h = *helper->impl_; - if (m.device < 0 || h.device < 0 || h.device == m.device || !mmq_plan().any) return true; - auto pp = std::make_unique(); - pp->peer = nullptr; // stream-only: it holds no experts, it streams a share of this stage's - pp->compact = true; - pp->p2p = false; // the mapped host route, whether or not the cards could reach each other (measured there) - pp->out_pipe = true; - bool ok; - { - const core::OnDevice on(m.device); - ok = cudaEventCreateWithFlags(&pp->ev_in, cudaEventDisableTiming) == cudaSuccess; - } - int prev = 0; - cudaGetDevice(&prev); - pp->dev = h.device; - cudaSetDevice(pp->dev); - ok = ok && cudaStreamCreateWithFlags(&pp->s, cudaStreamNonBlocking) == cudaSuccess && - cudaStreamCreateWithFlags(&pp->s_out, cudaStreamNonBlocking) == cudaSuccess && - cudaStreamCreateWithFlags(&pp->s_cp, cudaStreamNonBlocking) == cudaSuccess && - cudaEventCreateWithFlags(&pp->ev_done, cudaEventDisableTiming) == cudaSuccess; - for (int i = 0; ok && i < PeerPrefill::kGrpEv; ++i) - ok = cudaEventCreateWithFlags(&pp->ev_grp[i], cudaEventDisableTiming) == cudaSuccess; - for (int b = 0; ok && b < 2; ++b) ok = cudaEventCreateWithFlags(&pp->ev_dm[b], cudaEventDisableTiming) == cudaSuccess; - // the ring's events; its slots are the helper stage's own ring, bound per prompt (bind_stage_helper) - pp->pcopied.assign((size_t) kSplitHelpRing, nullptr); - pp->pused.assign((size_t) kSplitHelpRing, nullptr); - for (int i = 0; ok && i < kSplitHelpRing; ++i) - ok = cudaEventCreateWithFlags(&pp->pcopied[(size_t) i], cudaEventDisableTiming) == cudaSuccess && - cudaEventCreateWithFlags(&pp->pused[(size_t) i], cudaEventDisableTiming) == cudaSuccess; - cudaSetDevice(prev); - if (!ok) { err = "prefill: the layer split's prompt help (streams and events)"; return false; } - helper_ = helper; - m.help_pp = std::move(pp); - return true; -} - -// A one-chunk prompt of T tokens on a layer split: binds the stream-only peer to the helper stage's prompt buffers -// (that stage idles until this one hands its rows over). False when it cannot help this prompt. -bool Prefill::bind_stage_helper(int64_t T) { - Impl& m = *impl_; - if (!m.help_pp || helper_ == nullptr || m.pp) return false; - const double frac = split_help_frac(T); - if (frac <= 0.0 || T < stream_all_min() || m.src == nullptr || m.ring <= STAGE || fused_ring()) return false; - const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout(); - for (int64_t l = stage_lb_; l < stage_le_; ++l) { - if (!(mmq_plan().any && mmq_plan().layer[(size_t) l])) return false; // the peer computes on MMQ only - if (lay.native && fused::native_supported(lay.fmt[(size_t) l].gu_type, lay.fmt[(size_t) l].d_type)) return false; - } - Impl& h = *helper_->impl_; - // the helper's buffers must be laid out for this chunk (the serve path lends every stage's at once) - if (h.T < T || h.mixed == nullptr || h.Xq == nullptr || h.Hq == nullptr || h.GU == nullptr || h.H == nullptr || - h.Dm == nullptr || h.src_dev == nullptr || h.ids_identity == nullptr || h.bounds_dev == nullptr || - 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 - P.mixed = h.mixed; - P.Xq_g = h.Xq; // the helper's per-layer buffers hold T * K rows: a group's T fit - P.Hq_g = h.Hq; - P.GU_g = h.GU; - P.H_g = h.H; - P.Dm_b[0] = h.Dm; - P.Dm_b[1] = h.Dm + (size_t) T * N; - P.src = h.src_dev; - P.ident = h.ids_identity; - P.bounds = h.bounds_dev; - P.grp_gu = h.grp_gu; - P.grp_d = h.grp_d; - P.run_ctx = h.mmq_ctx.get(); - P.RP = std::min(h.ring, kSplitHelpRing); - P.pstage.assign(h.stage_dev, h.stage_dev + P.RP); - P.plive.assign((size_t) P.RP, 0); - P.dm_live[0] = P.dm_live[1] = false; - P.out_pending = false; - P.ps_frac = frac; - if (!P.p2p) { // grown once to the largest chunk it helped - auto grow = [](auto*& p, size_t& cap, size_t n) { - if (cap >= n) return true; - if (p) cudaFreeHost(p); - p = nullptr; - cap = 0; - if (cudaHostAlloc((void**) &p, n * sizeof(*p), cudaHostAllocPortable | cudaHostAllocMapped) != cudaSuccess) { - cudaGetLastError(); - p = nullptr; - return false; - } - cap = n; - return true; - }; - size_t bounds_cap = P.host_bounds ? PeerPrefill::kHostBounds : 0; - if (!grow(P.host_x, P.host_x_cap, (size_t) T * N) || !grow(P.host_rows, P.host_rows_cap, (size_t) T * K * N) || - !grow(P.host_src, P.host_src_cap, (size_t) T * K) || !grow(P.host_bounds, bounds_cap, PeerPrefill::kHostBounds)) - return false; - } - const core::OnDevice on(P.dev); - mmq::iota(P.ident, T * K, P.s); // the helper's row table: a refill may have overwritten its slots - return true; -} - -bool Prefill::set_peer(core::PeerExperts* peer, int64_t cap_rows, std::string& err) { - Impl& m = *impl_; - if (peer == nullptr || !peer->valid()) { m.pp.reset(); return true; } - 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(); - 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(1, std::min(cap_rows, m.T_max * K)); - const int64_t R = pp->cap_rows; - const MmqPlan& mp = mmq_plan(); - if (cudaEventCreateWithFlags(&pp->ev_in, cudaEventDisableTiming) != cudaSuccess) { err = "prefill peer: event"; return false; } - int prev = 0; - cudaGetDevice(&prev); - pp->dev = peer->device(); - cudaSetDevice(pp->dev); - bool ok = cudaStreamCreateWithFlags(&pp->s, cudaStreamNonBlocking) == cudaSuccess && - cudaEventCreateWithFlags(&pp->ev_done, cudaEventDisableTiming) == cudaSuccess; - { - const char* v = std::getenv("STRATA_PF_PEER_OUT_PIPE"); // =0: one copy after the last group (the A/B) - pp->out_pipe = (v == nullptr || std::atoi(v) != 0) || pp->compact; // compact always pipes - } - if (ok && pp->out_pipe) { - ok = cudaStreamCreateWithFlags(&pp->s_out, cudaStreamNonBlocking) == cudaSuccess; - for (int i = 0; ok && i < PeerPrefill::kGrpEv; ++i) - ok = cudaEventCreateWithFlags(&pp->ev_grp[i], cudaEventDisableTiming) == cudaSuccess; - } - auto take = [&](size_t bytes) -> void* { - void* p = nullptr; - if (!ok || cudaMalloc(&p, bytes) != cudaSuccess) { ok = false; return nullptr; } - pp->owned.push_back(p); - return p; - }; - pp->mixed = (float*) take((size_t) m.T_max * N * 4); - { - const char* v = std::getenv("STRATA_PF_PEER_COMPACT"); - pp->compact = v == nullptr || std::atoi(v) != 0; - } - if (pp->compact) { - pp->cap_rows = m.T_max * K; // no row cap: only the row tables grow with it - pp->G = m.T_max; // one expert never has more rows than the chunk has tokens - const int64_t Gr = pp->G; - pp->Xq_g = take(mmq::q8_bytes(Gr, N)); - pp->Hq_g = take(mmq::q8_bytes(Gr, FF)); - pp->GU_g = (float*) take((size_t) Gr * FF2 * 4); - pp->H_g = (float*) take((size_t) Gr * FF * 4); - pp->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; - const char* fs = std::getenv("STRATA_PF_PEER_STREAM"); - pp->ps_frac = fs ? std::atof(fs) : 0.35; // measured: 0.25-0.5 all ~1950-1970 at 32K, 0.35 best - if (pp->ps_frac > 0.0 && !mp.fallback && m.T_max >= stream_all_min()) { - pp->RP = 48; - if (const char* pr = std::getenv("STRATA_PF_PEER_RING"); pr != nullptr) pp->RP = std::atoi(pr); - pp->pstage.assign((size_t) pp->RP, nullptr); - pp->pcopied.assign((size_t) pp->RP, nullptr); - pp->pused.assign((size_t) pp->RP, nullptr); - pp->plive.assign((size_t) pp->RP, 0); - ok = ok && cudaStreamCreateWithFlags(&pp->s_cp, cudaStreamNonBlocking) == cudaSuccess; - for (int i = 0; ok && i < pp->RP; ++i) { - pp->pstage[(size_t) i] = (uint8_t*) take((size_t) MAXBLOB()); - ok = ok && cudaEventCreateWithFlags(&pp->pcopied[(size_t) i], cudaEventDisableTiming) == cudaSuccess && - cudaEventCreateWithFlags(&pp->pused[(size_t) i], cudaEventDisableTiming) == cudaSuccess; - } - } else { - pp->ps_frac = 0.0; - } - } else { - pp->Xq = take(mmq::q8_bytes(R, N)); - pp->Hq = take(mmq::q8_bytes(R, FF)); - pp->GU = (float*) take((size_t) R * FF2 * 4); - pp->H = (float*) take((size_t) R * FF * 4); - pp->Dm = (float*) take((size_t) R * N * 4); - } - const int64_t Rt = pp->cap_rows; - pp->src = (int32_t*) take((size_t) Rt * 4); - pp->ident = (int32_t*) take((size_t) Rt * 4); - pp->bounds = (int32_t*) take((size_t) (2 * (NE + NE / MMQ_GROUP + 2)) * 4); - pp->grp_gu = (uint8_t*) take(MMQ_GROUP * mp.gu_max + MMQ_TAIL); - pp->grp_d = (uint8_t*) take(MMQ_GROUP * mp.d_max + MMQ_TAIL); - if (ok) { - pp->ctx = std::make_unique(); - pp->run_ctx = pp->ctx.get(); - mmq::iota(pp->ident, pp->cap_rows, pp->s); - ok = cudaStreamSynchronize(pp->s) == cudaSuccess; - } - size_t fb = 0, tb = 0; - cudaMemGetInfo(&fb, &tb); - cudaSetDevice(prev); - if (!ok) { err = "prefill peer: the peer's buffers do not fit (raise --peer-reserve-mib or lower --peer-prefill-rows)"; return false; } - std::fprintf(stderr, "strata prefill: peer GPU %d computes its experts' rows of each prompt chunk (up to %lld rows per " - "layer%s); %zu MiB left free on it\n", pp->dev, (long long) pp->cap_rows, - pp->compact ? (pp->ps_frac > 0.0 ? (", compact group buffers, streams " + std::to_string((int) (pp->ps_frac * 100 + 0.5)) + - "% of the primary's streamed experts through a " + std::to_string(pp->RP) + "-slot ring").c_str() - : ", compact group buffers") : "", fb >> 20); - m.pp = std::move(pp); - return true; -} - -void Prefill::set_pinned_share(double share) { g_pinned_share = share; } -void Prefill::set_ring_override(int slots) { g_ring_override = slots > 0 ? slots : 0; } -void Prefill::set_ring_budget(int slots, int64_t small_max) { - g_ring_budget = slots > 0 ? slots : 0; - g_ring_small_max = small_max > 0 ? small_max : 0; -} -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; - o.take((size_t) GEMM_SCRATCH, ok); - o.take(GEMM_WS, ok); - auto f = [&](size_t n) { o.take(n, ok); }; - // `carve`'s order, buffer for buffer: emb, R, xn, grs, xn16, lo, lo16, gated, inj, mixed, mixed_bf, mixed_h, - // bo. This counted `xn` unconditionally (carve takes it only under STRATA_GR_UNFUSED) and never counted - // `grs`. Net over-count T*(D-HC)*4 bytes: 42 MB at a 1024-token chunk, 252 MB (48 Q8_0 slots) at 6144 - the - // prompt path was told it had less room than it did. Safe - the direction is over-estimating, and `take` - // still bounds-checks - but it under-sizes every loan, so every chunk the scan picks is one step smaller. - // The plain block (hc 1) has none of the hyper-connection's buffers. - if (ring_bytes_on() || !gr) { - f(T * N); f(T * D); - 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); - } - if (gr) { o.take(T * D, ok); f(T * LR); o.take(T * LR, ok); f(T * D); f(T * HC); } - f(T * N); o.take(T * N, ok); o.take(T * N, ok); f(T * N); - if (gr && bf16x2_hc()) { o.take(T * D, ok); o.take(T * LR, ok); } - if (bf16x2()) o.take(T * N, ok); - o.take(T * strata::kernels::kStepCount, ok); - const strata::kernels::QsaShapes s = shapes_of(g); - const int64_t cap = selection_cap(ss, s); - const int64_t max_blocks = primary_cells(ss) / s.idx_block + 2; - o.take((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((size_t) (G.ff2 * N), ok); o.take((size_t) (N * G.ff), ok); } - if (mmq_plan().any) { - const MmqPlan& mp = mmq_plan(); - o.take(T * K, ok); - o.take((size_t) (2 * (g.n_expert + g.n_expert / MMQ_GROUP + 2)), ok); - o.take(MMQ_GROUP * mp.gu_max + MMQ_TAIL, ok); - o.take(MMQ_GROUP * mp.d_max + MMQ_TAIL, ok); - } - for (int i = 0; i < ring_slots(T); ++i) o.take((size_t) MAXBLOB(), ok); - 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 -} - -uint64_t Prefill::bytes_needed_no_ring(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk) { - return bytes_needed(g, ss, chunk) - (uint64_t) ring_slots((size_t) chunk) * (uint64_t) MAXBLOB(); -} - -int64_t Prefill::ring_default_slots() { - const int r = g_pinned_share >= 0.9 ? (fused_ring() ? 1024 : 384) : 96; - return (int64_t) std::min(r, ring_cap()); -} - -int64_t Prefill::ring_cap_for(int64_t old_chunk) { - // 0.1.39b (#583, measured on the RTX 5070): giving up ring slots for a bigger chunk paid where 0.1.39's ring held - // the chunk at 4096 or less (IQ3_XXS 32K prompts +14% to +26%: 4096/384 -> 6656/56) and lost where 0.1.39 already - // read 6144-token chunks (the Coder: 6144/384 -> 7936/199, 32K -12%). From kKeepRingChunk on the ring keeps its - // 0.1.39 size and the scan only looks for a bigger chunk next to it (IQ3_XXS unpinned 6144/96 -> 6912/96: +9%). - constexpr int64_t kKeepRingChunk = 6144; - return old_chunk >= kKeepRingChunk ? ring_default_slots() : ring_max_slots(); -} - -// the unpinned arm keeps its measured 96 (the PR's rule; the byte budget would have been ~49 slots on IQ3_S) -int64_t Prefill::ring_max_slots() { - return g_pinned_share >= 0.9 ? (int64_t) ring_budget_slots() : (int64_t) std::min(96, ring_cap()); -} - -int64_t Prefill::ring_slots_for(int64_t chunk) { return ring_slots((size_t) chunk); } - -bool Prefill::ring_bytes_enabled() { return ring_bytes_on(); } - -namespace { - -const core::WeightRef* need(const core::LayerView& v, const char* suffix, std::string& err) { - const core::WeightRef* r = v.get(suffix); - if (!r) err = v.name(suffix) + " is missing"; - return r; -} -bool native_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name, - std::string& err, int64_t ldy = 0) { - if (!w->native_data) { err = "prefill: " + name + " has no native GGUF blocks (run with --native)"; return false; } - gm.native(X, w->native_type, w->native_data, Y, T, w->ne1, w->ne0, ldy); - return true; -} -bool bf16_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name, - std::string& err, int64_t ldy = 0, const uint16_t* X_lo = nullptr) { - if (w->kind != core::WeightKind::Bf16InF32 || !w->data) { err = "prefill: " + name + " is not a resident BF16 tensor"; return false; } - gm.bf16(X, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy); - if (X_lo) gm.bf16(X_lo, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 1.0f); - return true; -} - -} // namespace - -namespace { -// STRATA_PREFILL_TIMING=1: the prompt path's GPU time by phase. Events are recorded on the compute stream in order; -// the time between two consecutive marks is charged to the phase of the first, so a gap where the GPU waits (for the -// host's expert grouping, or for an expert's copy) lands on the phase that was waiting. Events are reused: the marks -// are folded at every MoE layer's host sync, after which all of them have completed. -enum PfPhase { kPfStart, kPfHc, kPfGdn, kPfQsa, kPfQsaIdx, kPfQsaSel, kPfQsaAttn, kPfRouter, kPfHostGroup, kPfGather, - kPfWaitCopy, kPfDequant, kPfGemmGU, kPfGemmD, kPfCombine, kPfPle, kPfKvStage, kPfGdnConv, kPfGdnRec, kPfGdnOut, - kPfCount }; -const char* const kPfNames[kPfCount] = {"embed+steps", "hc read", "gdn", "qsa proj", "qsa indexer", "qsa select", - "qsa attn", "router+shared", "host grouping", "gather", "wait copy", "dequant", - "gemm gate/up", "gemm down", "combine", "ple", "kv stage", "gdn conv+gates", - "gdn recurrence", "gdn out proj"}; -struct PfTimer { - bool on = std::getenv("STRATA_PREFILL_TIMING") != nullptr; - std::vector ev; - std::vector ph; - size_t used = 0; - double ms[kPfCount] = {}; - void mark(int phase, cudaStream_t s) { - if (!on) return; - if (used == ev.size()) { - cudaEvent_t e = nullptr; - cudaEventCreate(&e); - ev.push_back(e); - ph.push_back(0); - } - ph[used] = phase; - cudaEventRecord(ev[used], s); - ++used; - } - // every recorded mark has completed (the stream was synchronized): charge the gaps, keep the last mark - void fold() { - if (!on || used < 2) return; - for (size_t i = 0; i + 1 < used; ++i) { - float t = 0.0f; - if (cudaEventElapsedTime(&t, ev[i], ev[i + 1]) == cudaSuccess) ms[ph[i]] += t; - } - std::swap(ev[0], ev[used - 1]); - std::swap(ph[0], ph[used - 1]); - used = 1; - } - ~PfTimer() { - for (cudaEvent_t e : ev) cudaEventDestroy(e); - } -}; -// multi-GPU: the peer's own timeline (STRATA_PREFILL_TIMING): marks on the peer stream, folded with the primary's -enum PePhase { kPeIdle, kPeMoeIn, kPeMoeGemm, kPeMoeOut, kPeCount }; -const char* const kPeNames[kPeCount] = {"idle", "moe in", "moe gemm", "moe out"}; -struct PeTimer { - bool on = std::getenv("STRATA_PREFILL_TIMING") != nullptr; - int dev = -1; - std::vector ev; - std::vector ph; - size_t used = 0; - double ms[kPeCount] = {}; - void mark(int phase, cudaStream_t s) { // the peer device is current - if (!on) return; - if (used == ev.size()) { - cudaEvent_t e = nullptr; - cudaEventCreate(&e); - ev.push_back(e); - ph.push_back(0); - } - ph[used] = phase; - cudaEventRecord(ev[used], s); - ++used; - } - void fold() { // every mark has completed - if (!on || used < 2) return; - for (size_t i = 0; i + 1 < used; ++i) { - float t = 0.0f; - if (cudaEventElapsedTime(&t, ev[i], ev[i + 1]) == cudaSuccess) ms[ph[i]] += t; - } - std::swap(ev[0], ev[used - 1]); - std::swap(ph[0], ph[used - 1]); - used = 1; - } - ~PeTimer() { - if (dev < 0) return; - int prev = 0; - cudaGetDevice(&prev); - cudaSetDevice(dev); - for (cudaEvent_t e : ev) cudaEventDestroy(e); - cudaSetDevice(prev); - } -}; -} // namespace - -bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err) { - err.clear(); - Impl& m = *impl_; - const core::OnDevice on_device(m.device); - const core::ModelGeometry& g = *m.g; - core::SessionState& ss = *m.ss; - const Geom& G = m.geo; - const int64_t N = G.n, HC = G.hc, D = G.d, K = G.k, HV = G.hv; - const bool plain = HC == 1; // the plain residual block (Qwen3.6): no hyper-connection read or write - const GdnGeom gdn_geom = G.gdn(); - const auto t_start = Clock::now(); - const int64_t LB = stage_lb_, LE = stage_le_; - // The direct successor's future lives on the Prefill object. Intermediate - // stages therefore do not drain the complete remaining GPU chain here. - double host_sync_ms = 0, host_chunk_ms = 0, host_setup_ms = 0; // STRATA_PREFILL_TIMING: the host's share - const strata::kernels::QsaShapes s = shapes_of(g); - 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]}; - // layer split: a prompt of one chunk runs the stages one after the other, so the next stage's GPU idles while - // this one reads; it streams and computes a share of this stage's experts then (set_stage_helper), in the - // place of a --peer-device peer, and gives the stage back its own buffers when the run ends - const bool single_chunk = hand_in_ == nullptr ? n <= m.T : single_chunk_; - const bool helped = single_chunk && bind_stage_helper(n); - if (helped) std::swap(m.pp, m.help_pp); - struct HelpScope { - Impl& m; - bool on; - ~HelpScope() { - if (!on) return; - const core::OnDevice d(m.pp->dev); // its work is done before the stage hands over; settle its streams - cudaStreamSynchronize(m.pp->s_cp); - cudaStreamSynchronize(m.pp->s_out); - cudaStreamSynchronize(m.pp->s); - std::swap(m.pp, m.help_pp); - } - } help_scope{m, helped}; - PfTimer pt; - PeTimer pe; - if (m.pp) pe.dev = m.pp->dev; else pe.on = false; - const cudaStream_t cs = (cudaStream_t) m.cs; - // the MMQ row table lives in the borrowed cache slots, which the refill after a prompt overwrites with experts: - // write it again for every prompt (a layout is reused as long as the chunk and the slots are the same) - if (m.ids_identity != nullptr) mmq::iota(m.ids_identity, m.T * K, m.cs); - // The PLE rows of a chunk are read from the model file on the host (an SSD read per missed row): the chunk - // after this one is read on a thread while the GPU runs this one, into the other of two buffers. The rows - // depend only on the tokens (the two before a position name its n-grams), so this is the same data. - const bool ple_on = ss.ple.ready() && LB <= 1 && 1 < LE; - // the PLE block batched over the chunk: the pinned postops and a BF16 or GGUF-native key (else token by token); - // STRATA_PLE_BATCH=0 keeps the per-token block (the A/B) - static const bool ple_batch_env = [] { - const char* v = std::getenv("STRATA_PLE_BATCH"); - return v == nullptr || std::atoi(v) != 0; - }(); - const bool ple_batch = ple_on && ple_batch_env && strata::kernels::ple_native_postops_enabled() && - (ss.ple.w.key_bf16 != nullptr || ss.ple.w.key_native_data != nullptr) && - m.region_bytes / ((uint64_t) (3 * strata::kernels::NG_HC_DIM + N + 4) * 4 + (uint64_t) N * 2 + 4096) >= 64; - const int32_t prev0[2] = {prev[0], prev[1]}; - auto ple_gather = [&m, &ss, tokens, n, prev0](int64_t c0, int buf, std::string& e) -> bool { - const int64_t T = std::min(m.T, n - c0); - auto at = [&](int64_t i) { return i < 2 ? prev0[i] : (int32_t) tokens[i - 2]; }; // prev0, then the tokens - int32_t pv[2] = {at(c0), at(c0 + 1)}; - for (int64_t t = 0; t < T; ++t) { - const int32_t tok = (int32_t) tokens[c0 + t]; - strata::kernels::ngram_rows(&tok, pv, 1, ss.ple.consts, - m.ple_rows[buf].data() + t * strata::kernels::PLE_N_HEADS); - pv[0] = pv[1]; - pv[1] = tok; - } - return ss.ple.table->gather_batch(m.ple_rows[buf].data(), (size_t) T, m.ple_emb_host[buf], e); - }; - std::string ple_next_err; - std::future ple_next; // declared after everything it reads: an early return waits for it - int ple_buf = 0; - - for (int64_t c0 = 0; c0 < n; c0 += m.T) { - if (should_stop && should_stop()) { err = "cancelled"; return false; } - if (std::getenv("STRATA_TRACE")) { std::fprintf(stderr, "strata trace: prompt chunk %lld of %lld\n", (long long) c0, (long long) n); std::fflush(stderr); } - const int64_t T = std::min(m.T, n - c0), p0 = pos0 + c0; - core::progress_at("reading the prompt (batched): preparing the chunk from token", p0); // #251 - ++stats_.chunks; - pt.mark(kPfStart, cs); - const auto tsetup = Clock::now(); - // ---- embeddings, broadcast to the four streams - or, in a later stage of a layer split, the rows the - // previous stage handed on - if (hand_in_ != nullptr) { - if (cudaMemcpyAsync(m.R, hand_in_ + (size_t) c0 * D, (size_t) T * D * 4, cudaMemcpyHostToDevice, m.cs) != - cudaSuccess) { - err = "prefill: the layer split's hand-off upload failed"; - return false; - } - } - // C-4: the whole chunk's rows in one gather (the same per-element arithmetic as the per-token path, so the - // same bits); a chunk with picture rows, or a token outside the table, takes the per-token path - bool batched = hand_in_ == nullptr && m.tok_dev != nullptr; - const core::NativeEmbed* nemb = core::native_embed(); - const core::WeightRef* wemb = nemb ? nullptr : m.wt->find("token_embd.weight"); - if (batched && nemb == nullptr && - (wemb == nullptr || wemb->codebook_iq4nl || wemb->ne0 != g.n_embd || wemb->group_elems <= 0 || - (wemb->code_bits != 2 && wemb->code_bits != 4 && wemb->code_bits != 8))) - batched = false; - for (int64_t t = 0; batched && t < T; ++t) { - const int64_t tok = tokens[c0 + t]; - if ((embd_rows && embd_rows[p0 + t]) || tok < 0 || (wemb && tok >= wemb->ne1)) batched = false; - else m.tok_host[(size_t) t] = (int32_t) tok; - } - if (batched) { - if (cudaMemcpyAsync(m.tok_dev, m.tok_host.data(), (size_t) T * sizeof(int32_t), cudaMemcpyHostToDevice, - m.cs) != cudaSuccess) { - err = "prefill: the token id upload failed"; - return false; - } - if (nemb) { - nemb->gather_dev(m.tok_dev, T, m.emb, m.cs); - } else { - const auto* codes = (const uint8_t*) wemb->data; - const auto* scales = (const float*) (codes + wemb->codes_bytes); - const auto* offsets = wemb->has_offset ? (const float*) (codes + wemb->codes_bytes + wemb->scales_bytes) - : nullptr; - strata::kernels::embedding_gather_dev(codes, scales, offsets, m.tok_dev, (int) T, wemb->ne0, - wemb->code_bits, wemb->code_bias, wemb->group_elems, - (uint64_t) (wemb->ne0 / (8 / wemb->code_bits)), - (uint64_t) (wemb->ne0 / wemb->group_elems), m.emb, m.cs); - } - } - for (int64_t t = 0; hand_in_ == nullptr && !batched && t < T; ++t) { - const float* row = embd_rows ? embd_rows[p0 + t] : nullptr; - if (row) { - if (cudaMemcpyAsync(m.emb + t * N, row, (size_t) N * 4, cudaMemcpyHostToDevice, m.cs) != cudaSuccess) { - err = "prefill: the image embedding upload failed"; - return false; - } - } else if (!core::embed_row(*m.wt, g, tokens[c0 + t], m.emb + t * N, m.cs, err)) { - return false; - } - } - if (hand_in_ == nullptr) { - if (plain) cudaMemcpyAsync(m.R, m.emb, (size_t) T * N * 4, cudaMemcpyDeviceToDevice, m.cs); // R = emb - else gr_broadcast(m.emb, m.R, T, m.cs); - } - // ---- 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) - if (ple_on && !ple_next.valid()) - ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c0, b = ple_buf] { - return ple_gather(c0, b, ple_next_err); - }); - bool ple_pending = ple_on; - // the chunk's rows onto the device just before layer 1 reads them, and the next chunk's gather started - auto ple_land = [&]() -> bool { - if (!ple_pending) return true; - ple_pending = false; - const auto tp = Clock::now(); - if (!ple_next.get()) { - err = ple_next_err; - return false; - } - if (cudaMemcpyAsync(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, cudaMemcpyHostToDevice, m.cs) != - cudaSuccess || - cudaEventRecord(m.ple_copied[ple_buf], m.cs) != cudaSuccess) { - err = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError()); - return false; - } - if (c0 + m.T < n) { - // the other buffer's upload (a chunk ago) is done before the SSD thread refills it - if (cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]) != cudaSuccess) { - err = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError()); - return false; - } - ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + m.T, b = ple_buf ^ 1] { - return ple_gather(c1, b, ple_next_err); - }); - } - ple_buf ^= 1; - stats_.ms_ple += ms_since(tp); - return true; - }; - 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); - - int64_t qsa_index = 0, gdn_index = 0; - for (int64_t l = 0; l < LB; ++l) (core::is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1; - // step 3: this chunk's stream - every non-resident expert of every layer, layer by layer in id order (entry - // k lands in ring slot k % ring); a copy is issued once the entry `ring` before it is consumed (its slot's - // `used` event recorded), so the copy stream never waits on an event that is not queued yet - const strata::kernels::cpu::ExpertLayout& lay0 = strata::kernels::cpu::expert_layout(); - const bool stream_all = m.ring > STAGE && T >= stream_all_min() && m.src != nullptr; - const bool ps_on = stream_all && m.pp && m.pp->ps_frac > 0.0; - if (m.pp && !ps_on) m.pp->ps_flag.clear(); - // multi-GPU: the peer's ring - issue its copies up to `limit` / give entries back (the peer device is current) - auto p_issue_until = [&](size_t limit) { - PeerPrefill& P = *m.pp; - limit = std::min(limit, P.pseq.size()); - while (P.p_issued < limit) { - const PeerPrefill::PsEntry& en = P.pseq[P.p_issued]; - const size_t sl = P.p_issued % (size_t) P.RP; - if (P.plive[sl]) cudaStreamWaitEvent(P.s_cp, P.pused[sl], 0); - cudaMemcpyAsync(P.pstage[sl], en.blob, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(en.l), - cudaMemcpyHostToDevice, P.s_cp); - cudaEventRecord(P.pcopied[sl], P.s_cp); - P.plive[sl] = 1; - ++P.p_issued; - } - }; - auto p_release_to = [&](int64_t l, int32_t e_stop, cudaStream_t ps) { - PeerPrefill& P = *m.pp; - while (P.pk < P.pseq_start[(size_t) l + 1] && P.pseq[P.pk].e < e_stop) { - cudaEventRecord(P.pused[P.pk % (size_t) P.RP], ps); - ++P.pk; - p_issue_until(P.pk + (size_t) P.RP); - } - }; - struct StreamEntry { int32_t l, e; const uint8_t* blob; int job; }; - std::vector seq; - std::vector seq_start; - size_t issued = 0, consumed = 0; - if (stream_all) { - seq_start.assign((size_t) g.n_layers + 1, 0); - std::vector js; - if (ps_on) { - m.pp->pseq.clear(); - m.pp->pseq_start.assign((size_t) g.n_layers + 1, 0); - m.pp->ps_flag.assign((size_t) g.n_layers * m.g->n_expert, 0); - m.pp->p_issued = m.pp->pk = 0; - } - double ps_acc = 0.0; - for (int64_t l = LB; l < LE; ++l) { - seq_start[(size_t) l] = seq.size(); - if (ps_on) m.pp->pseq_start[(size_t) l] = m.pp->pseq.size(); - for (int32_t e = 0; e < m.g->n_expert; ++e) { - if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue; - if (m.pp && m.pp->peer && m.pp->peer->has(l, e)) continue; // multi-GPU: computed on (or read from) the peer - int job = -1; - const uint8_t* b = nullptr; - if (m.src->transient(l, e)) { // CS-T: copied by the source into the stager's buffer - job = (int) js.size(); - js.push_back({nullptr, (size_t) lay0.blob_bytes(l), m.src, (int32_t) l, e}); - } else { - b = m.src->blob(l, e); - if (!b) { err = "prefill: expert source has no blob"; return false; } - if (ps_on && m.src->pinned(l, e)) { // multi-GPU: every ps_frac-th one goes to the peer's ring - ps_acc += m.pp->ps_frac; - if (ps_acc >= 1.0) { - ps_acc -= 1.0; - m.pp->pseq.push_back({(int32_t) l, e, b}); - m.pp->ps_flag[(size_t) l * m.g->n_expert + e] = 1; - continue; - } - } - if (!m.src->pinned(l, e)) { - job = (int) js.size(); - js.push_back({b, (size_t) lay0.blob_bytes(l)}); - } - } - seq.push_back({(int32_t) l, e, b, job}); - } - } - for (int64_t l = LE; l <= g.n_layers; ++l) { - seq_start[(size_t) l] = seq.size(); - if (ps_on) m.pp->pseq_start[(size_t) l] = m.pp->pseq.size(); - } - m.stager->start(std::move(js)); - } - struct StagerDone { - Stager* st; - ~StagerDone() { if (st) st->finish(); } - } chunk_stager_done{stream_all ? m.stager.get() : nullptr}; - auto issue_until = [&](size_t limit) { - limit = std::min(limit, seq.size()); - while (issued < limit) { - const StreamEntry& en = seq[issued]; - const int sl = (int) (issued % (size_t) m.ring); - const auto th = Clock::now(); - const size_t bytes = (size_t) lay0.blob_bytes(en.l); - if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[m.used_of[sl]], 0); - if (en.job < 0) { - cudaMemcpyAsync(m.stage_dev[sl], en.blob, bytes, cudaMemcpyHostToDevice, m.copy); - ++stats_.experts_dma; - } else { - const uint8_t* hb = m.stager->wait(en.job); - cudaMemcpyAsync(m.stage_dev[sl], hb, bytes, cudaMemcpyHostToDevice, m.copy); - m.stager->issued_one(en.job, m.copy); - } - cudaEventRecord(m.copied[sl], m.copy); - m.stage_live[sl] = true; - stats_.ms_experts_host += ms_since(th); - ++stats_.experts_streamed; - ++issued; - } - }; - // D-5: the stream is issued by its own host thread, so the thread launching the layers' kernels never waits - // behind a host copy of an unpinned blob (that wait left the GPU idle: the 'wait copy' / 'dequant' time of the - // i-quant prompts). The same copies in the same order into the same slots, and a slot is refilled only once - // the compute stream has recorded that it is done with it: the same results. STRATA_PREFILL_ISSUER=0: inline. - static const bool issuer_on = [] { - const char* v = std::getenv("STRATA_PREFILL_ISSUER"); - return v == nullptr || std::atoi(v) != 0; - }(); - std::atomic a_issued{0}, a_consumed{0}; - std::atomic a_stop{false}; - double iss_ms = 0; - int64_t iss_streamed = 0, iss_dma = 0; - std::thread issuer; - struct IssuerJoin { - std::atomic* stop; - std::thread* t; - ~IssuerJoin() { if (t->joinable()) { stop->store(true); t->join(); } } - } issuer_join{&a_stop, &issuer}; - const bool threaded_issue = stream_all && issuer_on; - if (threaded_issue) { - issuer = std::thread([&] { - const core::OnDevice od(m.device); - for (size_t idx = 0; idx < seq.size(); ++idx) { - while (idx >= a_consumed.load(std::memory_order_acquire) + (size_t) m.ring) { - if (a_stop.load(std::memory_order_acquire)) return; - std::this_thread::yield(); - } - const StreamEntry& en = seq[idx]; - const int sl = (int) (idx % (size_t) m.ring); - const auto th = Clock::now(); - const size_t bytes = (size_t) lay0.blob_bytes(en.l); - if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[m.used_of[sl]], 0); - if (en.job < 0) { - cudaMemcpyAsync(m.stage_dev[sl], en.blob, bytes, cudaMemcpyHostToDevice, m.copy); - ++iss_dma; - } else { - const uint8_t* hb = m.stager->wait(en.job); - cudaMemcpyAsync(m.stage_dev[sl], hb, bytes, cudaMemcpyHostToDevice, m.copy); - m.stager->issued_one(en.job, m.copy); - } - cudaEventRecord(m.copied[sl], m.copy); - m.stage_live[sl] = true; - iss_ms += ms_since(th); - ++iss_streamed; - a_issued.store(idx + 1, std::memory_order_release); - } - }); - } else if (stream_all) { - issue_until((size_t) m.ring); // layer 0's first experts, behind the embedding and the PLE - } - // the consumer's side: entry k's copy is on the copy stream (the thread issued it), then k is given back - auto wait_issued = [&](size_t k) { - if (!threaded_issue) return; - while (a_issued.load(std::memory_order_acquire) <= k) std::this_thread::yield(); - }; - auto give_back = [&](size_t upto) { - if (threaded_issue) a_consumed.store(upto, std::memory_order_release); - else issue_until(upto + (size_t) m.ring); - }; - if (ps_on) { - int pd = 0; - cudaGetDevice(&pd); - cudaSetDevice(m.pp->dev); - p_issue_until((size_t) m.pp->RP); - cudaSetDevice(pd); - } - host_setup_ms += ms_since(tsetup); - bool normed = false; // F-2: the previous half's write already normed R for this half (grs, xn16) - // #579 #613 (opt-in diagnosis, STRATA_PF_STEP_SYNC=1): the compute and copy streams are waited for after each - // step named below, a step that took over 250 ms is logged, and a stall's report names the step it is in. - // Slower (a sync per step); the bytes are the same. - static const bool step_sync = [] { const char* e = std::getenv("STRATA_PF_STEP_SYNC"); return e && e[0] == '1'; }(); - auto pf_step = [&](const char* what, int64_t layer) { - if (!step_sync) return; - core::progress_at(what, layer, p0); - const auto ts = Clock::now(); - const cudaError_t a = cudaStreamSynchronize(m.cs), b = cudaStreamSynchronize(m.copy); - const double ms = ms_since(ts); - if (ms > 250.0 || a != cudaSuccess || b != cudaSuccess) - std::fprintf(stderr, "strata pf-step: chunk from token %lld, layer %lld: %s took %.0f ms (%s / %s)\n", - (long long) p0, (long long) layer, what, ms, cudaGetErrorString(a), cudaGetErrorString(b)); - }; - for (int64_t l = LB; l < LE; ++l) { - core::progress_beat(); // the serve watchdog: a prompt chunk of 8192 tokens is still moving - if (l > LB) pf_step("reading the prompt (batched, step sync): the experts and the rest of layer", l - 1); - core::progress_at("reading the prompt (batched): layer", l, p0); // #251: a stall names layer and chunk - const core::LayerView v(*m.wt, l); - if (l == std::max(LB, 1) && !ple_land()) return false; // the PLE rows, read from layer 1 on - // ---- the PLE block at layer 1, token by token (its conv reads the previous tokens' rows) - if (l == 1 && ple_on && ple_batch) { - // the whole chunk at once, in sub-batches carved from the idle scratch region: the key and value - // projections as GEMMs (a token at a time they re-read ~52 MB of BF16 key per token on the IQ - // files), the rest with the per-token kernels' arithmetic (native_ple_postops_batch) - pt.mark(kPfPle, cs); - const auto tp = Clock::now(); - const strata::kernels::PleWeights& pw = ss.ple.w; - constexpr int64_t HD = strata::kernels::NG_HC_DIM; - const uint64_t per_token = (uint64_t) (3 * HD + N + 4) * 4 + (uint64_t) N * (bf16x2() ? 4 : 2) + 4096; - const int64_t SB = std::min(T, (int64_t) (m.region_bytes / per_token)); - for (int64_t s0 = 0; s0 < T; s0 += SB) { - const int64_t nb = std::min(SB, T - s0); - uint8_t* q = m.region; - auto carve_f = [&](size_t n) { float* p = (float*) q; q += (n * 4 + 255) & ~(size_t) 255; return p; }; - float* key = carve_f((size_t) nb * HD); - float* qn = carve_f((size_t) nb * HD); - float* gated = carve_f((size_t) nb * HD); - float* val = carve_f((size_t) nb * N); - float* gate = carve_f((size_t) nb * 4); - uint16_t* e16 = (uint16_t*) carve_f((size_t) nb * N / 2); - uint16_t* e16_lo = bf16x2() ? (uint16_t*) carve_f((size_t) nb * N / 2) : nullptr; - const float* emb = m.ple_emb + s0 * N; - if (pw.key_bf16 != nullptr) { - to_bf16(emb, e16, nb * N, m.cs, e16_lo); - m.gemm.bf16(e16, pw.key_bf16, key, nb, HD, N); - if (e16_lo) m.gemm.bf16(e16_lo, pw.key_bf16, key, nb, HD, N, 0, 1.0f); - } else { - to_f16(emb, e16, nb * N, m.cs); - m.gemm.native(e16, pw.key_native_type, pw.key_native_data, key, nb, HD, N); - to_bf16(emb, e16, nb * N, m.cs, e16_lo); - } - m.gemm.bf16(e16, pw.value_bf16, val, nb, N, N); - if (e16_lo) m.gemm.bf16(e16_lo, pw.value_bf16, val, nb, N, N, 0, 1.0f); - try { - strata::kernels::native_ple_postops_batch(key, m.R + s0 * D, val, ss.ple.hist, pw, qn, gated, - gate, (int) nb, m.cs); - } catch (const std::exception& e) { err = std::string("prefill PLE: ") + e.what(); return false; } - } - stats_.ms_ple += ms_since(tp); - } else if (l == 1 && ple_on) { - pt.mark(kPfPle, cs); - const auto tp = Clock::now(); - for (int64_t t = 0; t < T; ++t) { - strata::kernels::PleOut po; - po.normalized = m.ple_norm; - po.result = m.R + t * D; - try { - strata::kernels::ple_block(m.ple_emb + t * N, m.R + t * D, ss.ple.hist, ss.ple.w, po, - ss.ple.scratch, m.cs); - } catch (const std::exception& e) { err = std::string("prefill PLE: ") + e.what(); return false; } - strata::kernels::ple_history_advance(ss.ple.hist, m.ple_norm, m.cs); - } - 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", - su = std::string(pre) + "up.weight", si = std::string(pre) + "inject.weight"; - const core::WeightRef *wn = need(v, sn.c_str(), err), *wd = need(v, sd.c_str(), err), - *wu = need(v, su.c_str(), err), *wi = need(v, si.c_str(), err); - if (!wn || !wd || !wu || !wi) return false; - pt.mark(kPfHc, cs); - if (gr_unfused()) gr_norm(m.R, (const float*) wn->data, EPS, m.xn, m.xn16, T, m.cs, m.xn16_lo); - else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs, m.xn16_lo); - normed = false; - if (!bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo)) return false; - gr_silu(m.lo, m.lo16, T, m.cs, m.lo16_lo); - if (!bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo)) return false; - if (!bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo)) return false; - 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 ======================= - const core::WeightRef *wqkv = need(v, "attn_qkv.weight", err), *wg = need(v, "attn_gate.weight", err), - *wo = need(v, "ssm_out.weight", err), *wa = need(v, "ssm_alpha.weight", err), - *wb = need(v, "ssm_beta.weight", err), *wc = need(v, "ssm_conv1d.weight", err), - *wnm = need(v, "ssm_norm.weight", err), *wdt = need(v, "ssm_dt.bias", err), - *wsa = need(v, "ssm_a", err); - if (!wqkv || !wg || !wo || !wa || !wb || !wc || !wnm || !wdt || !wsa) return false; - pt.mark(kPfGdn, cs); - float* state = ss.gdn_state + (size_t) (gdn_index - ss.gdn_ord0) * gdn_floats; - float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; - if (!native_proj(m.gemm, wqkv, m.mixed_h, m.qkv, T, v.name("attn_qkv.weight"), err)) return false; - if (!native_proj(m.gemm, wg, m.mixed_h, m.z, T, v.name("attn_gate.weight"), err)) return false; - if (!bf16_proj(m.gemm, wa, m.mixed_bf, m.ab, T, v.name("ssm_alpha.weight"), err, 2 * HV, m.mixed_bf_lo)) return false; - if (!bf16_proj(m.gemm, wb, m.mixed_bf, m.ab + HV, T, v.name("ssm_beta.weight"), err, 2 * HV, m.mixed_bf_lo)) return false; - pt.mark(kPfGdnConv, cs); // "gdn" is the projections in; the rest on their own lines - gdn_gates(m.ab, (const float*) wdt->data, (const float*) wsa->data, m.gate, m.beta, T, gdn_geom, m.cs); - gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, gdn_geom, m.cs); - pt.mark(kPfGdnRec, cs); - gdn_recurrence(state, m.hbuf, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, m.y, m.y_h, T, gdn_geom, m.cs); - pt.mark(kPfGdnOut, cs); - if (!native_proj(m.gemm, wo, m.y_h, m.bo, T, v.name("ssm_out.weight"), err)) return false; - ++gdn_index; - } else if (half == 0) { - // ======================= QSA ======================= - const core::QsaState& st = ss.qsa_states[qsa_index]; - // the indexer's four tensors exist on Flash-Next only; Qwen3.6's attention is dense (no indexer) - const core::WeightRef *wq = need(v, "attn_q.weight", err), *wk = need(v, "attn_k.weight", err), - *wv = need(v, "attn_v.weight", err), *wo = need(v, "attn_output.weight", err), - *wqn = need(v, "attn_q_norm.weight", err), *wkn = need(v, "attn_k_norm.weight", err); - if (!wq || !wk || !wv || !wo || !wqn || !wkn) return false; - const core::WeightRef *wik = nullptr, *wiq = nullptr, *wiqn = nullptr, *wikn = nullptr; - if (G.indexer) { - wik = need(v, "indexer.k_proj.weight", err); - wiq = need(v, "indexer.q_proj.weight", err); - wiqn = need(v, "indexer.q_norm.weight", err); - wikn = need(v, "indexer.k_norm.weight", err); - if (!wik || !wiq || !wiqn || !wikn) return false; - } - pt.mark(kPfQsa, cs); - if (!native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false; - if (!native_proj(m.gemm, wv, m.mixed_h, m.Vc, T, v.name("attn_v.weight"), err)) return false; - if (!native_proj(m.gemm, wq, m.mixed_h, m.Qf, T, v.name("attn_q.weight"), err)) return false; - if (G.indexer) { - if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err, 0, m.mixed_bf_lo)) return false; - if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err, 0, m.mixed_bf_lo)) return false; - } - rms_rows(m.Kc, (const float*) wkn->data, T * G.nkv, 256, 256, EPS, m.cs); - rope(m.Kc, T, G.nkv, 256, G.kvw, p0, strata::kernels::rope_scaling(), m.cs); - // 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; - if (staged) { - pt.mark(kPfKvStage, cs); - strata::kernels::kv_stage_from_host(pools_of(m.stage, m.ident_table), st.host, - core::qsa_kv_format(st), - (p0 + s.page_size - 1) / s.page_size, s, m.cs); - pt.mark(kPfQsa, cs); - pf_step("reading the prompt (batched, step sync): the K/V staged from RAM at layer", l); - } - // #579 #613 (HIP, opt-in A/B, STRATA_KV_HOST_DMA=1): the append writes the staging pool and the - // resident slots only, and one DMA copies the chunk's blocks from the staging pool to the host copy - // - no kernel writes host memory over PCIe. The bytes every reader sees are the same (the staged - // first block is complete; past the chunk's last cell nothing is read until a later append writes - // it). CUDA: never. -#if defined(STRATA_USE_HIP) - static const bool kv_host_dma = [] { const char* e = std::getenv("STRATA_KV_HOST_DMA"); return e && e[0] == '1'; }(); -#else - constexpr bool kv_host_dma = false; -#endif - const bool host_by_dma = staged && kv_host_dma; - const strata::kernels::KvHostPools* host_w = host_by_dma ? nullptr : &st.host; - if (st.kv_hybrid) { // K8V4: K INT8 unrotated, V rotated Q4_0 (only V and the output rotate) - strata::kernels::fwht256_inplace_cuda(m.Vc, T * 2, m.cs); - kv_append(m.Kc, m.Kc, T, p0, st.page_table, s.page_size, nullptr, nullptr, - st.k_q, st.k_q, st.k_scale, st.k_scale, m.cs, nullptr, // mode 0: no host mirror - staged ? &m.stage : nullptr); - strata::kernels::kv_append_q4(st.v_q4, st.v_q4, st.page_table, p0, T, m.Vc, m.Vc, s, m.cs, - nullptr, staged ? &m.stage : nullptr); - } else { - if (st.kv_rot) { // rotated K and V (kv_q4.hpp), the queries below too, the output back - strata::kernels::fwht256_inplace_cuda(m.Kc, T * 2, m.cs); - strata::kernels::fwht256_inplace_cuda(m.Vc, T * 2, m.cs); - } - if (st.kv_q4) - strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, p0, T, m.Kc, m.Vc, s, m.cs, - host_w, staged ? &m.stage : nullptr); - else - kv_append(m.Kc, m.Vc, T, p0, 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, - host_w, staged ? &m.stage : nullptr); - if (host_by_dma) - strata::kernels::kv_unstage_to_host(pools_of(m.stage, m.ident_table), st.host, - core::qsa_kv_format(st), p0 / s.page_size, - (p0 + T + s.page_size - 1) / s.page_size, s, m.cs); - } - if (staged) pf_step("reading the prompt (batched, step sync): the K/V append at layer", l); - split_q(m.Qf, m.q, T, G.nh, m.cs); - rms_rows(m.q, (const float*) wqn->data, T * G.nh, 256, 256, EPS, m.cs); - rope(m.q, T, G.nh, 256, G.av, p0, strata::kernels::rope_scaling(), m.cs); - if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(m.q, T * G.nh, m.cs); - // dense attention (no indexer): every cell up to the query's own - the width in the step records, - // a null ids as the identity selection (the attention branch's kernels, G templated at 2 / 8 / 12 - // query heads per KV head; any other ratio is refused by name before a launch) - if (!G.indexer) { - char why[256] = {0}; - if (strata::kernels::qsa_attn_group(s, why, sizeof why) == 0) { err = std::string("prefill: ") + why; return false; } - } - if (G.indexer) { - 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: - // a query reads completed blocks (final once completed) and `dead` for its own tail block - const strata::kernels::QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; - pt.mark(kPfQsaIdx, cs); - // C-2: the chunk's appends in three launches instead of one per token (the same end state: - // the queries below read it only after the whole chunk is appended). STRATA_INDEXER_PER_TOKEN=1: the old - try { - static const bool per_token = std::getenv("STRATA_INDEXER_PER_TOKEN") != nullptr; - if (!per_token) { - strata::kernels::native_qsa_indexer_append_batch(m.idx_raw, T, p0, 0, (const float*) wikn->data, - EPS, ib, s, st.max_cells, - strata::kernels::rope_scaling(), m.cs); - } - for (int64_t t = 0; per_token && t < T; ++t) { - const int32_t* step_t = m.steps_dev + t * strata::kernels::kStepCount; - strata::kernels::native_qsa_indexer_append(m.idx_raw + t * 128, step_t + strata::kernels::kStepPos, 0, - (const float*) wikn->data, EPS, ib, s, st.max_cells, - strata::kernels::rope_scaling(), m.cs); - } - } catch (const std::exception& e) { err = std::string("prefill indexer: ") + e.what(); return false; } - pt.mark(kPfQsaSel, cs); - for (int64_t t0 = 0; t0 < T; t0 += m.sel_batch) { - const int64_t nb = std::min(m.sel_batch, T - t0); - const int32_t* steps0 = m.steps_dev + t0 * strata::kernels::kStepCount; - // C-1: the grid reaches the batch's last query's n_bid (they rise with the position) - const int64_t active = (int64_t) m.steps_host[(size_t) ((t0 + nb - 1) * strata::kernels::kStepCount + - strata::kernels::kStepNBid)] + 1; - // the scores on tensor cores (3xTF32: FP32-level, not bitwise); STRATA_SELECT_OLD=1: the warp kernel - static const bool old_sel = std::getenv("STRATA_SELECT_OLD") != nullptr; - if (old_sel || !strata::kernels::qsa_block_scores_tc(st.idx_pooled, st.idx_dead, m.q_idx + t0 * 512, - steps0, nb, m.max_blocks, s, m.sel_scores, - m.cs, active)) - strata::kernels::qsa_block_scores(st.idx_pooled, st.idx_dead, m.q_idx + t0 * 512, steps0, nb, - m.max_blocks, s, m.sel_scores, m.cs, active); - strata::kernels::qsa_block_topk(m.sel_scores, steps0, nb, m.max_blocks, m.cap, s, - m.sel_ids + t0 * m.cap, m.cs, active); - } - // STRATA_SEL_OVERLAP (debug, D-1's question): how much do neighbouring queries' selections share? - // Per tile of 16 queries: the union of their selected cells against the sum of their widths. - if (static const bool ovl = std::getenv("STRATA_SEL_OVERLAP") != nullptr; ovl && qsa_index == 0) { - std::vector ids((size_t) (T * m.cap)); - cudaMemcpyAsync(ids.data(), m.sel_ids, ids.size() * 4, cudaMemcpyDeviceToHost, m.cs); - cudaStreamSynchronize(m.cs); - double sum_w = 0, sum_u = 0; - for (int64_t t0 = 0; t0 + 16 <= T; t0 += 16) { - std::vector u; - for (int64_t t = t0; t < t0 + 16; ++t) { - const int64_t w = m.steps_host[(size_t) (t * strata::kernels::kStepCount + strata::kernels::kStepWidth)]; - sum_w += (double) w; - u.insert(u.end(), ids.begin() + t * m.cap, ids.begin() + t * m.cap + w); - } - std::sort(u.begin(), u.end()); - sum_u += (double) (std::unique(u.begin(), u.end()) - u.begin()); - } - std::fprintf(stderr, "strata prefill: selection overlap at %lld: 16-query tiles read %.1f%% of the " - "cells one query at a time does\n", (long long) p0, sum_w > 0 ? 100.0 * sum_u / sum_w : 0.0); - } - // STRATA_IDX_FP16_CHECK: would FP16 pooled indexer keys select the same cells? (the KV-streaming - // design's last question). Every query is selected again from the pooled keys and `dead` rounded - // to fp16 (exactly what an fp16 store reads back); the agreement with the fp32 selection is - // printed cumulatively after each chunk's last QSA layer. Debug: syncs per layer. - if (static const bool f16chk = std::getenv("STRATA_IDX_FP16_CHECK") != nullptr; f16chk) { - static float *pooled16 = nullptr, *dead16 = nullptr; - static int32_t* ids16 = nullptr; - static double shared = 0, cells = 0; - static long long queries = 0, same = 0, sel_queries = 0; - const int64_t rows = st.idx_pooled_rows; - if (pooled16 == nullptr && - (cudaMalloc((void**) &pooled16, (size_t) rows * s.idx_dim * 4) != cudaSuccess || - cudaMalloc((void**) &dead16, (size_t) s.idx_dim * 4) != cudaSuccess || - cudaMalloc((void**) &ids16, (size_t) (m.T * m.cap) * 4) != cudaSuccess)) { - err = "STRATA_IDX_FP16_CHECK: no room for its buffers"; - return false; - } - round_f16(st.idx_pooled, pooled16, rows * s.idx_dim, m.cs); - round_f16(st.idx_dead, dead16, s.idx_dim, m.cs); - for (int64_t t0 = 0; t0 < T; t0 += m.sel_batch) { - const int64_t nb = std::min(m.sel_batch, T - t0); - const int32_t* steps0 = m.steps_dev + t0 * strata::kernels::kStepCount; - strata::kernels::qsa_block_scores(pooled16, dead16, m.q_idx + t0 * 512, steps0, nb, - m.max_blocks, s, m.sel_scores, m.cs); - strata::kernels::qsa_block_topk(m.sel_scores, steps0, nb, m.max_blocks, m.cap, s, - ids16 + t0 * m.cap, m.cs); - } - std::vector a((size_t) (T * m.cap)), b((size_t) (T * m.cap)); - cudaMemcpyAsync(a.data(), m.sel_ids, a.size() * 4, cudaMemcpyDeviceToHost, m.cs); - cudaMemcpyAsync(b.data(), ids16, b.size() * 4, cudaMemcpyDeviceToHost, m.cs); - cudaStreamSynchronize(m.cs); - for (int64_t t = 0; t < T; ++t) { - const int64_t w = m.steps_host[(size_t) (t * strata::kernels::kStepCount + strata::kernels::kStepWidth)]; - const int32_t *x = a.data() + t * m.cap, *y = b.data() + t * m.cap; - int64_t i = 0, j = 0, c = 0; - while (i < w && j < w) { - if (x[i] == y[j]) { ++c; ++i; ++j; } else if (x[i] < y[j]) ++i; else ++j; - } - ++queries; - same += c == w; - if (p0 + t + 1 > m.cap) { ++sel_queries; shared += (double) c; cells += (double) w; } - } - if (qsa_index + 1 == g.n_qsa_layers()) - std::fprintf(stderr, "strata prefill: FP16 indexer keys: %lld of %lld selections identical; " - "where the selection is sparse, %.4f%% of cells shared (%lld queries)\n", - same, queries, cells > 0 ? 100.0 * shared / cells : 100.0, sel_queries); - } - // STRATA_QSA_DUMP=: append every QSA layer's selected cells for the prompt's last - // STRATA_QSA_DUMP_LAST (4096) positions - records of int32 {qsa layer, pos0, T, cap} + T*cap cells, - // for tools/qsa_locality.py (how local the sparse attention's reads are: the KV-streaming question) - if (static const char* dump = std::getenv("STRATA_QSA_DUMP"); dump != nullptr) { - static const long long last = std::getenv("STRATA_QSA_DUMP_LAST") - ? std::atoll(std::getenv("STRATA_QSA_DUMP_LAST")) : 4096; - if (p0 + T > pos0 + n - last) { - std::vector h((size_t) (T * m.cap)); - cudaMemcpyAsync(h.data(), m.sel_ids, h.size() * 4, cudaMemcpyDeviceToHost, m.cs); - cudaStreamSynchronize(m.cs); - if (std::FILE* f = std::fopen(dump, "ab")) { - const int32_t hdr[4] = {(int32_t) qsa_index, (int32_t) p0, (int32_t) T, (int32_t) m.cap}; - std::fwrite(hdr, 4, 4, f); - std::fwrite(h.data(), 4, h.size(), f); - std::fclose(f); - } - } - } - } // G.indexer - const strata::kernels::QsaAttnPools pools = staged ? pools_of(m.stage, m.ident_table) - : core::qsa_attn_pools(st); - pt.mark(kPfQsaAttn, cs); - // perf-review D-1: the whole chunk on tensor cores, one block per (query, KV head), FP32-level - // accuracy but not bitwise (qsa_prompt_attn.hpp). Q4_0 KV, or STRATA_PROMPT_ATTN_OLD=1: the - // decode kernel, 32 queries at a time (K8V4 runs the tensor kernel's mode 3: INT8 K, - // V dequantized from its q4_0 blocks to fp16 at gather) - static const bool old_attn = std::getenv("STRATA_PROMPT_ATTN_OLD") != nullptr; - if (old_attn || !strata::kernels::qsa_prompt_attn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s, - m.attn, T, m.cs)) - for (int64_t t0 = 0; t0 < T; t0 += m.attn_batch) { - const int64_t nb = std::min(m.attn_batch, T - t0); - strata::kernels::qsa_decode_attn_batch(m.q + t0 * G.av, pools, m.sel_ids ? m.sel_ids + t0 * m.cap : nullptr, - m.steps_dev + t0 * strata::kernels::kStepCount, m.cap, - 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 * G.nh, m.cs); - pt.mark(kPfQsa, 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 { - // ======================= MoE ======================= - const core::WeightRef *wr = need(v, "ffn_gate_inp.weight", err), - *wgi = need(v, "ffn_gate_inp_shexp.weight", err), - *wsg = need(v, "ffn_gate_shexp.weight", err), - *wsu = need(v, "ffn_up_shexp.weight", err), - *wsd = need(v, "ffn_down_shexp.weight", err); - if (!wr || !wgi || !wsg || !wsu || !wsd) return false; - pt.mark(kPfRouter, cs); - if (!bf16_proj(m.gemm, wr, m.mixed_bf, m.logits, T, v.name("ffn_gate_inp.weight"), err, 0, m.mixed_bf_lo)) return false; - route(m.logits, m.ids, m.w, T, m.g->n_expert, K, m.cs); - if (on_seam && !on_seam("ffn_moe_topk", l, (float*) m.ids, T, K, p0, err)) return false; // int32 ids as floats - // the shared expert and its scalar gate - if (!native_proj(m.gemm, wsg, m.mixed_h, m.sgate, T, v.name("ffn_gate_shexp.weight"), err)) return false; - if (!native_proj(m.gemm, wsu, m.mixed_h, m.sup, T, v.name("ffn_up_shexp.weight"), err)) return false; - swiglu_pair(m.sgate, m.sup, m.sh_h, T, G.ffs, m.cs); - 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); - if (m.mixed_bf_lo) m.gemm.bf16(m.mixed_bf_lo, (const uint16_t*) wgi->data, m.sg, T, 1, N, 0, 1.0f); - // #136: STRATA_PF_FUSED=1 - the Q2_0 pack's experts on the fused int8 kernels (moe_fused.hpp), - // grouped on the GPU: no host sync. Only where every expert's place is known before the routing - - // the streamed walk, in which every non-resident expert of the layer comes through the ring in id - // order - and where the MMQ buffers exist: they hold the fused path's own (the per-token int8 - // activations in Xq, the int8 H in H, the grouping tables in GU). Chunks below stream_all_min() - // keep MMQ; without the variable nothing here runs. A native pack's layer takes the native kernels - // (moe_fused_iq.hpp) where they cover its two formats, else MMQ (or the FP16 path: IQ1_M). - const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout(); - const bool use_mmq = mmq_plan().any && mmq_plan().layer[(size_t) l]; - const int mmq_gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42; - const int mmq_dt = lay.native ? lay.fmt[(size_t) l].d_type : 42; - // --peer-device: MMQ only, whether or not the peer took the prompt path (set_peer can decline), as - // fused_ring() sized the ring and the buffers for it - const bool no_peer = !core::peer_portable(); - const bool fused_nat = use_mmq && stream_all && no_peer && lay.native && fused::native_supported(mmq_gt, mmq_dt); - const bool fused_l = (use_mmq && stream_all && no_peer && !lay.native && fused::enabled()) || fused_nat; - size_t n_order = 0; // the routed experts (the debug report; unknown when fused) - bool peer_now = false; // multi-GPU: the peer computed rows of this layer (MMQ path only) - if (fused_l) { - if (static bool said = false; !said) { - said = true; - std::fprintf(stderr, "strata: prompt experts on the fused int8 kernels (STRATA_PF_FUSED=1, " - "#136)\n"); - } - pt.mark(kPfGather, cs); - // the layer's input to int8 once per token; the rows of each expert from the router's ids - if (fused_nat) fused::quantize_act_native(m.mixed, T, N, m.Xq, m.cs); - else fused::quantize_act(m.mixed, T, N, m.Xq, m.cs); - fused::group(m.ids, T * K, (int) K, (int) m.g->n_expert, m.GU, m.slot_dev, m.src_dev, m.cs); - // launches over the experts in id order, each at most kMaxBatch experts of which at most a - // third of the ring streamed: the next batch's blobs arrive while one computes. An expert - // the routing did not pick has no tiles; its ring slot is given back with its batch. - const size_t per = (size_t) std::max(1, m.ring / 3); - size_t k = seq_start[(size_t) l]; - const size_t kend = seq_start[(size_t) l + 1]; - for (int32_t e = 0; e < m.g->n_expert;) { - fused::Batch b; - b.e0 = e; - const size_t k0 = k; - for (; e < m.g->n_expert && e - b.e0 < fused::kMaxBatch; ++e) { - if (k < kend && seq[k].e == e) { - if (k - k0 == per) break; - b.blob[e - b.e0] = m.stage_dev[k % (size_t) m.ring]; - ++k; - } else { // not streamed: resident (the walk streams all others) - b.blob[e - b.e0] = m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]); - // counted whether routed or not (the routing stays on the GPU): at a streamed - // chunk's size (>= 1024 tokens x 10 of 512) nearly every expert is routed - ++stats_.experts_resident; - } - } - b.e1 = e; - if (k > k0) { - // one copy stream, in order: the batch's last blob covers the others - pt.mark(kPfWaitCopy, cs); - wait_issued(k - 1); - cudaStreamWaitEvent(m.cs, m.copied[(k - 1) % (size_t) m.ring], 0); - } - pt.mark(kPfGemmGU, cs); - if (fused_nat) { - const auto& f = lay.fmt[(size_t) l]; - const fused::NativeGeom ng{f.gu_type, f.d_type, f.gu_row, f.d_row, f.up_off, f.down_off, - f.n_embd, f.n_ff}; - 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 { - fused::experts(b, (int) m.g->n_expert, T * K, m.GU, m.Xq, m.src_dev, m.H, m.Dm, m.cs); - } - for (size_t kk = k0; kk < k; ++kk) { - cudaEventRecord(m.used[kk % (size_t) m.ring], m.cs); - m.used_of[kk % (size_t) m.ring] = (int) (kk % (size_t) m.ring); - } - if (k > k0) { - consumed = k; - give_back(consumed); - } - } - } else { - // group the (token, k) pairs by expert on the host - pt.mark(kPfHostGroup, cs); - // (the sync below also orders this layer's writes of slot/src/bounds after the previous - // layer's kernels that read them) - const bool grp_mapped = m.grp_host != nullptr; - int32_t* ids_h = grp_mapped ? m.grp_host : m.ids_host.data(); - int32_t* slot_h = grp_mapped ? m.grp_host + m.grp_tk : m.slot_host.data(); - int32_t* src_h = grp_mapped ? m.grp_host + 2 * m.grp_tk : m.src_host.data(); - if (grp_mapped) copy_i32(m.grp_dev, m.ids, T * K, m.cs); - else cudaMemcpyAsync(m.ids_host.data(), m.ids, (size_t) T * K * 4, cudaMemcpyDeviceToHost, m.cs); - // #579: a stall here is the GPU (this layer's attention and router, or the previous layer's - // work), not the host: the watchdog's report says so (only its text changes) - core::progress_at("reading the prompt (batched): waiting for the GPU (attention, router) at layer", - l, p0); - cudaStreamSynchronize(m.cs); - core::progress_at("reading the prompt (batched): layer", l, p0); - pt.fold(); - if (pe.on) { // the peer's marks so far are done: the primary waited for its last rows - int pd = 0; cudaGetDevice(&pd); cudaSetDevice(pe.dev); cudaStreamSynchronize(m.pp->s); pe.fold(); cudaSetDevice(pd); - } - std::fill(m.cnt.begin(), m.cnt.end(), 0); - for (int64_t i = 0; i < T * K; ++i) { - const int32_t e = ids_h[(size_t) i]; - if (e < 0 || e >= m.g->n_expert) { err = "prefill: routed id out of range"; return false; } - ++m.cnt[(size_t) e]; - } - // multi-GPU: the rows of the experts the peer computes go last, as one block [rows_local, T*K) - const bool pre_mmq = mmq_plan().any && mmq_plan().layer[(size_t) l]; - std::vector on_peer; - int64_t rows_local = T * K, rows_peer = 0; - if (m.pp && pre_mmq) { - on_peer.assign((size_t) m.g->n_expert, 0); - for (int32_t e = 0; e < m.g->n_expert; ++e) { - const int32_t c = m.cnt[(size_t) e]; - if (c > 0 && !m.pp->ps_flag.empty() && m.pp->ps_flag[(size_t) l * m.g->n_expert + e]) { // peer-streamed - on_peer[(size_t) e] = 2; - rows_peer += c; - continue; - } - if (c == 0 || (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) || - !m.pp->peer || !m.pp->peer->has(l, e)) - continue; - if (rows_peer + c > m.pp->cap_rows) { ++m.pp->over_cap; continue; } - on_peer[(size_t) e] = 1; - rows_peer += c; - } - rows_local = T * K - rows_peer; - } - { - int32_t r = 0; - for (int32_t e = 0; e < m.g->n_expert; ++e) - if (on_peer.empty() || !on_peer[(size_t) e]) { m.off[(size_t) e] = r; r += m.cnt[(size_t) e]; } - // the peer's rows in order_peer's order (peer-held, then peer-streamed): its groups need them contiguous - for (int kind = 1; kind <= 2 && !on_peer.empty(); ++kind) - for (int32_t e = 0; e < m.g->n_expert; ++e) - if (on_peer[(size_t) e] == kind) { m.off[(size_t) e] = r; r += m.cnt[(size_t) e]; } - m.off[(size_t) m.g->n_expert] = r; - } - std::vector fill(m.off.begin(), m.off.end() - 1); - for (int64_t i = 0; i < T * K; ++i) { - const int32_t e = ids_h[(size_t) i]; - const int32_t p = fill[(size_t) e]++; - slot_h[(size_t) i] = p; - src_h[(size_t) p] = (int32_t) (i / K); - } - if (grp_mapped) { - copy_i32(m.slot_dev, m.grp_dev + m.grp_tk, T * K, m.cs); - copy_i32(m.src_dev, m.grp_dev + 2 * m.grp_tk, T * K, m.cs); - } else { - cudaMemcpyAsync(m.slot_dev, m.slot_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs); - cudaMemcpyAsync(m.src_dev, m.src_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs); - } - // the experts, in id order: resident ones from VRAM, the others through the staging ring - std::vector order, order_peer; - for (int32_t e = 0; e < m.g->n_expert; ++e) - if (m.cnt[(size_t) e] > 0 && (on_peer.empty() || on_peer[(size_t) e] != 2)) - (!on_peer.empty() && on_peer[(size_t) e] ? order_peer : order).push_back(e); - for (int32_t e = 0; e < m.g->n_expert && !on_peer.empty(); ++e) // the peer-streamed ones last: - if (on_peer[(size_t) e] == 2) order_peer.push_back(e); // their copies get the most time - n_order = order.size(); - const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, G.ff2, N) : 0; - const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, G.ff) : 0; - pt.mark(kPfGather, cs); - if (use_mmq) { - // step 2b: the layer's activations as q8_1 rows in expert order, straight from `mixed` - mmq::quantize(m.mixed, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs); - // each group's rows: absolute bounds (gate/up reads the layer's rows), relative ones (down - // reads the group's own quantized H) - const size_t n = order.size(), ng = (n + MMQ_GROUP - 1) / MMQ_GROUP; - m.bounds_host.resize(n + 1 + ng * (MMQ_GROUP + 1)); - for (size_t j = 0; j < n; ++j) m.bounds_host[j] = m.off[(size_t) order[j]]; - m.bounds_host[n] = (int32_t) rows_local; - for (size_t g = 0; g < ng; ++g) - for (size_t i = 0; i <= MMQ_GROUP; ++i) - m.bounds_host[n + 1 + g * (MMQ_GROUP + 1) + i] = - m.bounds_host[std::min(n, g * MMQ_GROUP + i)] - m.bounds_host[g * MMQ_GROUP]; - if (grp_mapped) { - int32_t* bh = m.grp_host + 3 * m.grp_tk; - std::memcpy(bh, m.bounds_host.data(), m.bounds_host.size() * 4); - copy_i32(m.bounds_dev, m.grp_dev + 3 * m.grp_tk, (int64_t) m.bounds_host.size(), m.cs); - } else { - cudaMemcpyAsync(m.bounds_dev, m.bounds_host.data(), m.bounds_host.size() * 4, - cudaMemcpyHostToDevice, m.cs); - } - } else { - gather_rows16(m.mixed_h, m.src_dev, m.Xs, T * K, N, m.cs); - } - // multi-GPU: the peer's share, enqueued before the primary's own experts so both cards work at once - peer_now = use_mmq && !order_peer.empty(); - if (peer_now) { - PeerPrefill& P = *m.pp; - if (!P.p2p) cudaMemcpyAsync(P.host_x, m.mixed, (size_t) T * N * 4, cudaMemcpyDeviceToHost, m.cs); - cudaEventRecord(P.ev_in, m.cs); - int prevd = 0; - cudaGetDevice(&prevd); - cudaSetDevice(P.dev); - const cudaStream_t ps = P.s; - cudaStreamWaitEvent(ps, P.ev_in, 0); - if (P.out_pending) { cudaStreamWaitEvent(ps, P.ev_done, 0); P.out_pending = false; } - pe.mark(kPeMoeIn, ps); - if (P.p2p) cudaMemcpyPeerAsync(P.mixed, P.dev, m.mixed, prevd, (size_t) T * N * 4, ps); - else copy_f32_wide(P.mixed, P.host_x, T * N, ps); - P.back_at = rows_local; - P.back_rows = rows_peer; - if (P.p2p) { - cudaMemcpyAsync(P.src, src_h + rows_local, // multi-GPU: the mapped table when on - (size_t) rows_peer * 4, cudaMemcpyHostToDevice, ps); - } else { - std::memcpy(P.host_src, src_h + rows_local, (size_t) rows_peer * 4); - copy_i32(P.src, P.host_src, rows_peer, ps); - } - const size_t n = order_peer.size(); - if (P.compact) { - // groups of up to MMQ_GROUP experts and at most G rows, each computed from its own rows - P.groups.clear(); - { - size_t g0 = 0; - int64_t gr = 0; - for (size_t j = 0; j < n; ++j) { - const int64_t c = m.cnt[(size_t) order_peer[j]]; - if (j > g0 && (j - g0 == (size_t) MMQ_GROUP || gr + c > P.G)) { P.groups.push_back({g0, j}); g0 = j; gr = 0; } - gr += c; - } - if (n > g0) P.groups.push_back({g0, n}); - } - const size_t ng = P.groups.size(); - P.bounds_host.resize(n + 1 + ng * (MMQ_GROUP + 1)); - for (size_t j = 0; j < n; ++j) P.bounds_host[j] = m.off[(size_t) order_peer[j]] - (int32_t) rows_local; - P.bounds_host[n] = (int32_t) rows_peer; - for (size_t g2 = 0; g2 < ng; ++g2) - for (size_t i = 0; i <= MMQ_GROUP; ++i) - P.bounds_host[n + 1 + g2 * (MMQ_GROUP + 1) + i] = - P.bounds_host[std::min(P.groups[g2].second, P.groups[g2].first + i)] - - P.bounds_host[P.groups[g2].first]; - if (P.p2p || P.bounds_host.size() > PeerPrefill::kHostBounds) { - cudaMemcpyAsync(P.bounds, P.bounds_host.data(), P.bounds_host.size() * 4, cudaMemcpyHostToDevice, ps); - } else { - std::memcpy(P.host_bounds, P.bounds_host.data(), P.bounds_host.size() * 4); - copy_i32(P.bounds, P.host_bounds, (int64_t) P.bounds_host.size(), ps); - } - pe.mark(kPeMoeGemm, ps); - const auto& f = lay.fmt[(size_t) l]; - for (size_t g2 = 0; g2 < ng; ++g2) { - const size_t j0 = P.groups[g2].first, j1 = P.groups[g2].second; - const int ngx = (int) (j1 - j0); - int64_t maxr = 0; - for (size_t j = j0; j < j1; ++j) { - const int32_t e = order_peer[j]; - maxr = std::max(maxr, m.cnt[(size_t) e]); - const uint8_t* bd = nullptr; - int psl = -1; - if (on_peer[(size_t) e] == 2) { // from the peer's ring - p_release_to(l, e, ps); - if (P.pk >= P.pseq_start[(size_t) l + 1] || P.pseq[P.pk].e != e) { - err = "prefill: a peer-streamed expert is not next in the peer's ring"; - cudaSetDevice(prevd); - return false; - } - psl = (int) (P.pk % (size_t) P.RP); - cudaStreamWaitEvent(ps, P.pcopied[(size_t) psl], 0); - bd = P.pstage[(size_t) psl]; - ++P.ps_experts; - } else { - bd = P.peer->slot_ptr(l, e); - } - const size_t q = j - j0; - if (lay.native) - mmq::gather_native(bd, bd + f.up_off, mmq_gub / 2, bd + f.down_off, mmq_db, - P.grp_gu + q * mmq_gub, P.grp_d + q * mmq_db, ps); - else - mmq::gather_strata_q2(bd, P.grp_gu + q * mmq_gub, P.grp_d + q * mmq_db, ps); - if (psl >= 0) { // the slot is free once gathered - cudaEventRecord(P.pused[(size_t) psl], ps); - ++P.pk; - p_issue_until(P.pk + (size_t) P.RP); - } - } - const int64_t r0 = P.bounds_host[j0], nr = P.bounds_host[j1] - r0; - if (nr <= 0) continue; - const int32_t* rel = P.bounds + n + 1 + g2 * (MMQ_GROUP + 1); - 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::quantize(P.mixed, P.src + r0, P.Xq_g, mmq_gt, N, N, nr, ps); - mmq::Product gu; - gu.w = P.grp_gu; gu.type = mmq_gt; gu.w_rows = G.ff2; gu.w_cols = N; gu.expert_bytes = mmq_gub; - gu.n = ngx; gu.xq = P.Xq_g; gu.bounds = rel; gu.ids = P.ident; - gu.total_rows = nr; gu.max_rows = maxr; gu.dst = P.GU_g; gu.ld_dst = G.ff2; - P.run_ctx->run(gu, ps); - mmq::swiglu(P.GU_g, P.H_g, nr, G.ff, !lay.native, ps); - mmq::quantize(P.H_g, nullptr, P.Hq_g, mmq_dt, G.ff, G.ff, nr, ps); - const int b = (int) (g2 & 1); - if (P.dm_live[b]) cudaStreamWaitEvent(ps, P.ev_dm[b], 0); // its last rows have left - mmq::Product dn; - dn.w = P.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = G.ff; dn.expert_bytes = mmq_db; - dn.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; - P.run_ctx->run(dn, ps); - cudaEventRecord(P.ev_grp[g2 % PeerPrefill::kGrpEv], ps); - cudaStreamWaitEvent(P.s_out, P.ev_grp[g2 % PeerPrefill::kGrpEv], 0); - if (P.p2p) - cudaMemcpyPeerAsync(m.Dm + (size_t) (rows_local + r0) * N, prevd, P.Dm_b[b], P.dev, - (size_t) nr * N * 4, P.s_out); - else // the primary reads them when it combines (below) - cudaMemcpyAsync(P.host_rows + (size_t) r0 * N, P.Dm_b[b], (size_t) nr * N * 4, - cudaMemcpyDeviceToHost, P.s_out); - cudaEventRecord(P.ev_dm[b], P.s_out); - P.dm_live[b] = true; - } - } else { - const size_t ng = (n + MMQ_GROUP - 1) / MMQ_GROUP; - P.bounds_host.resize(n + 1 + ng * (MMQ_GROUP + 1)); - for (size_t j = 0; j < n; ++j) P.bounds_host[j] = m.off[(size_t) order_peer[j]] - (int32_t) rows_local; - P.bounds_host[n] = (int32_t) rows_peer; - for (size_t g2 = 0; g2 < ng; ++g2) - for (size_t i = 0; i <= MMQ_GROUP; ++i) - P.bounds_host[n + 1 + g2 * (MMQ_GROUP + 1) + i] = - P.bounds_host[std::min(n, g2 * MMQ_GROUP + i)] - P.bounds_host[g2 * MMQ_GROUP]; - if (P.p2p || P.bounds_host.size() > PeerPrefill::kHostBounds) { - cudaMemcpyAsync(P.bounds, P.bounds_host.data(), P.bounds_host.size() * 4, cudaMemcpyHostToDevice, ps); - } else { - std::memcpy(P.host_bounds, P.bounds_host.data(), P.bounds_host.size() * 4); - copy_i32(P.bounds, P.host_bounds, (int64_t) P.bounds_host.size(), ps); - } - mmq::quantize(P.mixed, P.src, P.Xq, mmq_gt, N, N, rows_peer, ps); - pe.mark(kPeMoeGemm, ps); - const auto& f = lay.fmt[(size_t) l]; - for (size_t j = 0; j < n; ++j) { - const int32_t e = order_peer[j]; - const uint8_t* bd = P.peer->slot_ptr(l, e); - const size_t q = j % MMQ_GROUP; - if (lay.native) - mmq::gather_native(bd, bd + f.up_off, mmq_gub / 2, bd + f.down_off, mmq_db, - P.grp_gu + q * mmq_gub, P.grp_d + q * mmq_db, ps); - else - mmq::gather_strata_q2(bd, P.grp_gu + q * mmq_gub, P.grp_d + q * mmq_db, ps); - if (q + 1 < MMQ_GROUP && j + 1 < n) continue; - const size_t j0 = j - q, g2 = j0 / MMQ_GROUP; - const int ngx = (int) (q + 1); - const int64_t r0 = P.bounds_host[j0], nr = P.bounds_host[j + 1] - r0; - int64_t maxr = 0; - for (size_t i = j0; i <= j; ++i) maxr = std::max(maxr, m.cnt[(size_t) order_peer[i]]); - cudaMemsetAsync(P.grp_gu + (size_t) ngx * mmq_gub, 0, MMQ_TAIL, ps); - cudaMemsetAsync(P.grp_d + (size_t) ngx * mmq_db, 0, MMQ_TAIL, ps); - mmq::Product gu; - gu.w = P.grp_gu; gu.type = mmq_gt; gu.w_rows = G.ff2; gu.w_cols = N; gu.expert_bytes = mmq_gub; - gu.n = ngx; gu.xq = P.Xq; gu.bounds = P.bounds + j0; gu.ids = P.ident; - gu.total_rows = rows_peer; gu.max_rows = maxr; gu.dst = P.GU; gu.ld_dst = G.ff2; - P.run_ctx->run(gu, ps); - mmq::swiglu(P.GU + r0 * G.ff2, P.H + r0 * G.ff, nr, G.ff, !lay.native, ps); - mmq::quantize(P.H + r0 * G.ff, nullptr, P.Hq, mmq_dt, G.ff, G.ff, nr, ps); - mmq::Product dn; - dn.w = P.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = G.ff; dn.expert_bytes = mmq_db; - dn.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; - P.run_ctx->run(dn, ps); - if (P.out_pipe && nr > 0) { // this group's rows go back while the next group computes - cudaEventRecord(P.ev_grp[g2], ps); - cudaStreamWaitEvent(P.s_out, P.ev_grp[g2], 0); - cudaMemcpyPeerAsync(m.Dm + (size_t) (rows_local + r0) * N, prevd, P.Dm + (size_t) r0 * N, - P.dev, (size_t) nr * N * 4, P.s_out); - } - } - } - pe.mark(kPeMoeOut, ps); - if (P.out_pipe) { - cudaEventRecord(P.ev_done, P.s_out); - P.out_pending = true; - } else { - cudaMemcpyPeerAsync(m.Dm + (size_t) rows_local * N, prevd, P.Dm, P.dev, (size_t) rows_peer * N * 4, ps); - cudaEventRecord(P.ev_done, ps); - } - pe.mark(kPeIdle, ps); - cudaSetDevice(prevd); - ++P.layers; - P.experts += (int64_t) n; - P.rows += rows_peer; - } - if (ps_on) { // multi-GPU: this layer's peer-ring entries the routing did not pick give their slots back - int pd = 0; - cudaGetDevice(&pd); - cudaSetDevice(m.pp->dev); - p_release_to(l, (int32_t) m.g->n_expert, m.pp->s); - cudaSetDevice(pd); - } - // Stage ahead: the copy stream moves blobs host -> device while the compute stream works. - int stage_next = 0; - std::vector stage_of(order.size(), -1); - // the unpinned ones are copied to pinned buffers by the stager's threads, in this order - std::vector job_of(order.size(), -1); - if (!stream_all) { - std::vector js; - for (size_t j = 0; j < order.size(); ++j) { - const int32_t e = order[j]; - if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue; - if (m.src->pinned(l, e)) continue; - job_of[j] = (int) js.size(); - if (m.src->transient(l, e)) { // CS-T: copied by the source - js.push_back({nullptr, (size_t) lay.blob_bytes(l), m.src, (int32_t) l, e}); - continue; - } - const uint8_t* b = m.src->blob(l, e); - if (!b) { err = "prefill: expert source has no blob"; return false; } - js.push_back({b, (size_t) lay.blob_bytes(l)}); - } - m.stager->start(std::move(js)); - } - StagerDone stager_done{stream_all ? nullptr : m.stager.get()}; - auto stage_one = [&](size_t j) -> bool { - const int32_t e = order[j]; - const bool resident = m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0; - if (resident) return true; - const int sl = stage_next; - stage_next = (stage_next + 1) % STAGE; - const auto th = Clock::now(); - const bool pinned = m.src->pinned(l, e); // pinned: never transient - const uint8_t* b = pinned ? m.src->blob(l, e) : nullptr; - if (pinned && !b) { err = "prefill: expert source has no blob"; return false; } - if (pinned) { - // DMA straight from the page-locked arena: the copy stream only waits for the slot - if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[m.used_of[sl]], 0); - cudaMemcpyAsync(m.stage_dev[sl], b, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy); - ++stats_.experts_dma; - } else { - // copied to a pinned buffer by the stager (waits only if it is behind), then DMA - const uint8_t* hb = m.stager->wait(job_of[j]); - if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[m.used_of[sl]], 0); - cudaMemcpyAsync(m.stage_dev[sl], hb, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy); - m.stager->issued_one(job_of[j], m.copy); - } - cudaEventRecord(m.copied[sl], m.copy); - m.stage_live[sl] = true; - stage_of[j] = sl; - stats_.ms_experts_host += ms_since(th); - ++stats_.experts_streamed; - return true; - }; - // In the streamed walk an MMQ group is gathered in ONE launch, after ONE wait on its last - // streamed copy (the copy stream is in order), and its ring slots are released by ONE event. A - // wait and a record per expert put ~10 us of GPU bubble each on the compute stream under WDDM - // (226 ms of a 32K prompt on an NVFP4 pack). The same bytes into the same group slots. A ring - // entry the routing skipped inside an open group first gathers what the group holds so far - // (`flush`), so no more than a group's entries are ever held back from the issuer. - // STRATA_PREFILL_GROUP_GATHER=0: one gather, one wait and one record per expert. - static const bool group_env = [] { - const char* v = std::getenv("STRATA_PREFILL_GROUP_GATHER"); - return v == nullptr || std::atoi(v) != 0; - }(); - const bool group_gather = group_env && stream_all && use_mmq && lay.native && - MMQ_GROUP <= mmq::kGatherGroupMax; - mmq::GatherGroup gg; - int gg_slots[MMQ_GROUP]; - int gg_nslots = 0; // ring slots gathered by the next flush - auto flush = [&]() { - if (gg.n <= gg.first) return; - const auto& f = lay.fmt[(size_t) l]; - if (gg_nslots > 0) { // the copies land in order: the last one covers the others - pt.mark(kPfWaitCopy, cs); - cudaStreamWaitEvent(m.cs, m.copied[gg_slots[gg_nslots - 1]], 0); - pt.mark(kPfDequant, cs); - } - if (!mmq::gather_native_group(gg, f.up_off, mmq_gub / 2, f.down_off, mmq_db, m.grp_gu, mmq_gub, - m.grp_d, mmq_db, m.cs)) { - for (int i = gg.first; i < gg.n; ++i) { // not 16-byte aligned: one at a time - const uint8_t* b = gg.blob[i]; - mmq::gather_native(b, b + f.up_off, mmq_gub / 2, b + f.down_off, mmq_db, - m.grp_gu + i * mmq_gub, m.grp_d + i * mmq_db, m.cs); - } - } - if (gg_nslots > 0) { - const int rel = gg_slots[gg_nslots - 1]; - cudaEventRecord(m.used[rel], m.cs); - for (int i = 0; i < gg_nslots; ++i) m.used_of[gg_slots[i]] = rel; - } - gg_nslots = 0; - gg.first = gg.n; - }; - // one expert's products from its blob on the device; `slot` (a ring slot, or -1 for a resident - // expert) is released once the blob is read - auto compute = [&](size_t j, const uint8_t* blob_dev, int slot) -> bool { - const int32_t e = order[j]; - pt.mark(kPfDequant, cs); - if (use_mmq) { - // gather the expert into its group slot (GGUF blocks, unchanged or converted) - const size_t q = j % MMQ_GROUP; - if (group_gather) { - gg.blob[q] = blob_dev; - gg.n = (int) q + 1; - if (slot >= 0) gg_slots[gg_nslots++] = slot; - if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true; - flush(); - gg = mmq::GatherGroup{}; - } else if (lay.native) { - const auto& f = lay.fmt[(size_t) l]; - mmq::gather_native(blob_dev, blob_dev + f.up_off, mmq_gub / 2, blob_dev + f.down_off, - mmq_db, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs); - } else { - mmq::gather_strata_q2(blob_dev, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs); - } - if (slot >= 0 && !group_gather) { cudaEventRecord(m.used[slot], m.cs); m.used_of[slot] = slot; } - if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true; - // the group's products: gate/up, swiglu, the group's H to q8_1, down - const size_t j0 = j - q, g = j0 / MMQ_GROUP, n = order.size(); - const int ngx = (int) (q + 1); - const int64_t r0 = m.bounds_host[j0], nr = m.bounds_host[j + 1] - r0; - int64_t maxr = 0; - for (size_t i = j0; i <= j; ++i) maxr = std::max(maxr, m.cnt[(size_t) order[i]]); - pt.mark(kPfGemmGU, cs); - // the zeroed tail after the group's last expert (see MMQ_TAIL) - cudaMemsetAsync(m.grp_gu + (size_t) ngx * mmq_gub, 0, MMQ_TAIL, m.cs); - cudaMemsetAsync(m.grp_d + (size_t) ngx * mmq_db, 0, MMQ_TAIL, m.cs); - mmq::Product gu; - gu.w = m.grp_gu; gu.type = mmq_gt; gu.w_rows = G.ff2; gu.w_cols = N; gu.expert_bytes = mmq_gub; - gu.n = ngx; gu.xq = m.Xq; gu.bounds = m.bounds_dev + j0; gu.ids = m.ids_identity; - gu.total_rows = T * K; gu.max_rows = maxr; gu.dst = m.GU; gu.ld_dst = G.ff2; - m.mmq_ctx->run(gu, m.cs); - mmq::swiglu(m.GU + r0 * G.ff2, m.H + r0 * G.ff, nr, G.ff, !lay.native, m.cs); - pt.mark(kPfGemmD, 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 = 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; - m.mmq_ctx->run(dn, m.cs); - return true; - } - const int q = (int) (j % DQ); - if (lay.native) { - // plan v0.3 P6: a native pack's layer, dequantized by llama.cpp's own formulas - const auto& f = lay.fmt[(size_t) l]; - strata::kernels::iq_dequant_gu_f16(f.gu_type, blob_dev, blob_dev + f.up_off, f.n_ff, f.n_embd, - m.dq_gu[q], m.cs); - strata::kernels::iq_dequant_f16(f.d_type, blob_dev + f.down_off, f.n_embd * f.n_ff, m.dq_d[q], m.cs); - } else { - blob_dequant_f16(blob_dev, m.dq_gu[q], m.dq_d[q], m.cs); - } - if (slot >= 0) { cudaEventRecord(m.used[slot], m.cs); m.used_of[slot] = slot; } - const int64_t o0 = m.off[(size_t) e], ne = m.cnt[(size_t) e]; - pt.mark(kPfGemmGU, cs); - m.gemm.f16(m.Xs + o0 * N, m.dq_gu[q], m.GU + o0 * G.ff2, ne, G.ff2, N); - swiglu_interleaved(m.GU + o0 * G.ff2, m.Hh + o0 * G.ff, ne, G.ff, m.cs); - pt.mark(kPfGemmD, cs); - 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) { - size_t staged = 0; - const size_t lookahead = STAGE - 1; - for (size_t j = 0; j < order.size(); ++j) { - while (staged < order.size() && staged <= j + lookahead) { - if (!stage_one(staged)) return false; - ++staged; - } - const int32_t e = order[j]; - if (stage_of[j] < 0) { - ++stats_.experts_resident; - if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false; - } else { - pt.mark(kPfWaitCopy, cs); - cudaStreamWaitEvent(m.cs, m.copied[stage_of[j]], 0); - if (!compute(j, m.stage_dev[stage_of[j]], stage_of[j])) return false; - } - } - } else { - // the streamed walk: this layer's entries [k, kend) in id order; an entry the routing did not - // pick only gives its slot back - size_t k = seq_start[(size_t) l]; - const size_t kend = seq_start[(size_t) l + 1]; - auto release_to = [&](int32_t e_stop) { - while (k < kend && seq[k].e < e_stop) { - if (gg_nslots > 0) flush(); // the open group's slots get their event first - const int sl = (int) (k % (size_t) m.ring); - cudaEventRecord(m.used[sl], m.cs); - m.used_of[sl] = sl; - consumed = ++k; - give_back(consumed); - } - }; - for (size_t j = 0; j < order.size(); ++j) { - const int32_t e = order[j]; - release_to(e); - if (k < kend && seq[k].e == e) { - const int sl = (int) (k % (size_t) m.ring); - wait_issued(k); - if (!group_gather) { - pt.mark(kPfWaitCopy, cs); - cudaStreamWaitEvent(m.cs, m.copied[sl], 0); - } - if (!compute(j, m.stage_dev[sl], sl)) return false; - consumed = ++k; - if (!group_gather || gg_nslots == 0) give_back(consumed); // its group was gathered - } else { - const bool r0 = m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0; - const uint8_t* bp = r0 ? m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]) - : (m.pp && m.pp->peer ? m.pp->peer->slot_ptr(l, e) : nullptr); // over the cap: P2P - if (bp == nullptr) { err = "prefill: an expert is neither resident, streamed nor on the peer"; return false; } - ++stats_.experts_resident; - if (!compute(j, bp, -1)) return false; - if (group_gather && gg_nslots == 0) give_back(consumed); - } - } - release_to(m.g->n_expert); - } - } - pt.mark(kPfCombine, cs); - if (peer_now) { // multi-GPU: the peer's rows are in Dm (or, without P2P, in host memory) - cudaStreamWaitEvent(m.cs, m.pp->ev_done, 0); - if (!m.pp->p2p) - copy_f32_wide(m.Dm + (size_t) m.pp->back_at * N, m.pp->host_rows, m.pp->back_rows * N, m.cs); - } - moe_combine(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.bo, T, N, K, m.cs); - // 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); - auto bad = [&](const float* d, int64_t n) { - std::vector h((size_t) n); - cudaMemcpy(h.data(), d, (size_t) n * 4, cudaMemcpyDeviceToHost); - int64_t c = 0; - for (float v : h) c += !std::isfinite(v); - return c; - }; - // (fused: GU and H hold the grouping tables and int8 rows, not floats) - const int64_t bgu = fused_l ? 0 : bad(m.GU, T * K * G.ff2), bdm = bad(m.Dm, T * K * N), - bbo = bad(m.bo, T * N); - 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; - std::fprintf(stderr, "strata dbg: layer %lld (mmq %d, types %d/%d, %zu experts): non-finite GU %lld " - "H %lld Dm %lld bo %lld of T %lld\n", (long long) l, (int) use_mmq, mmq_gt, mmq_dt, - n_order, (long long) bgu, (long long) bh, (long long) bdm, (long long) bbo, - (long long) T); - } - } - } - 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) - const int64_t nl = half == 0 ? l : l + 1; - const bool fuse = !gr_unfused() && nl < LE && !(half == 1 && nl == 1 && ple_on) && - !(half == 1 && strata::kernels::cvec().covers(l)); - const core::WeightRef* wnn = nullptr; - if (fuse) { - const core::LayerView vn(*m.wt, nl); - wnn = need(vn, half == 0 ? "hc_ffn_norm.weight" : "hc_attn_norm.weight", err); - if (!wnn) return false; - } - if (wnn) { - gr_write_norm_rs(m.R, m.bo, m.inj, HC, (const float*) wnn->data, EPS, m.grs, m.xn16, T, m.cs, - m.xn16_lo); - normed = true; - } 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 - if (issuer.joinable()) { - issuer.join(); - stats_.ms_experts_host += iss_ms; - stats_.experts_streamed += iss_streamed; - stats_.experts_dma += iss_dma; - } - stats_.tokens += T; - core::progress_at("reading the prompt (batched): finishing the chunk from token", p0); - pt.mark(kPfStart, cs); - if (next_ != nullptr) { - // The current hand-off slot was used two chunks ago. - float* h = m.hand[hand_buf_]; - if (cudaMemcpyAsync(h, m.R, (size_t) T * D * 4, cudaMemcpyDeviceToHost, m.cs) != cudaSuccess || - cudaStreamSynchronize(m.cs) != cudaSuccess) { - err = std::string("prefill: the layer split's hand-off: ") + cudaGetErrorString(cudaGetLastError()); - return false; - } - // Wait only for the DIRECT successor's previous chunk. That successor - // may already have forwarded its older chunk to later GPUs. - if (on_stage_chunk && !on_stage_chunk(p0 + T, err)) return false; - if (next_run_.valid() && !next_run_.get()) { err = next_err_; return false; } - next_err_.clear(); - next_->hand_in_ = h; - next_->single_chunk_ = single_chunk; - next_run_ = std::async(std::launch::async, [this, tokens, c0, T, p0] { - return next_->run_impl(tokens + c0, T, p0, next_err_); - }); - hand_buf_ ^= 1; - continue; // the last stage reports the chunk (on_chunk) - } - if (const char* dump = std::getenv("STRATA_PREFILL_DUMP_R")) { // debug: the final residuals, every 64th - cudaStreamSynchronize(m.cs); // position (A/B quality of this path) - if (std::FILE* f = std::fopen(dump, c0 == 0 ? "wb" : "ab")) { - std::vector row((size_t) D); - for (int64_t t = (64 - p0 % 64) % 64; t < T; t += 64) { - cudaMemcpy(row.data(), m.R + t * D, (size_t) D * 4, cudaMemcpyDeviceToHost); - const int64_t pos = p0 + t; - std::fwrite(&pos, sizeof pos, 1, f); - std::fwrite(row.data(), 4, row.size(), f); - } - std::fclose(f); - } - } - if (on_chunk || on_stage_chunk) { - const auto toc = Clock::now(); - if (cudaStreamSynchronize(m.cs) != cudaSuccess) { - err = std::string("prefill: ") + cudaGetErrorString(cudaGetLastError()); - return false; - } - const auto toc2 = Clock::now(); - if (on_stage_chunk && !on_stage_chunk(p0 + T, err)) return false; - if (on_chunk && !on_chunk(m.R, T, p0, err)) return false; - host_sync_ms += std::chrono::duration(toc2 - toc).count(); - host_chunk_ms += ms_since(toc2); - } - } - // Do not drain the successor here. This is the overlap: an intermediate - // stage can return while later GPUs are still processing the previous chunk. - ss.ple_prev[0] = prev[0]; - ss.ple_prev[1] = prev[1]; - if (std::getenv("STRATA_DBG_NAN") != nullptr) { // debug: the state the prompt leaves for the token path - cudaStreamSynchronize(m.cs); - auto bad = [&](const float* d, int64_t n) { - std::vector h((size_t) n); - cudaMemcpy(h.data(), d, (size_t) n * 4, cudaMemcpyDeviceToHost); - int64_t c = 0; - double mx = 0; - for (float v : h) { c += !std::isfinite(v); if (std::isfinite(v)) mx = std::max(mx, (double) std::fabs(v)); } - std::fprintf(stderr, " %lld non-finite (max |x| %.3g)", (long long) c, mx); - }; - const int64_t last = (n - 1) % m.T; - std::fprintf(stderr, "strata dbg: prompt end: last residual row"); - bad(m.R + last * D, D); - if (ss.ple.ready()) { std::fprintf(stderr, "; PLE history"); bad(ss.ple.hist, (int64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM); } - std::fprintf(stderr, "; GDN state 0"); - bad(ss.gdn_state, 64 * 1024); - std::fprintf(stderr, "\n"); - } - if (cudaStreamSynchronize(m.cs) != cudaSuccess) { - err = std::string("prefill: ") + cudaGetErrorString(cudaGetLastError()); - return false; - } - // (PR #121) an expert copy that failed on the copy stream surfaces here, not in the next request - if (const cudaError_t cst = cudaStreamSynchronize(m.copy); cst != cudaSuccess) { - err = std::string("prefill: expert copy stream: ") + cudaGetErrorString(cst); - return false; - } - stats_.ms_total += ms_since(t_start); - if (pt.on) { - pt.fold(); - double total = 0.0; - for (double v : pt.ms) total += v; - std::string line; - char b[96]; - for (int i = 0; i < kPfCount; ++i) { - if (pt.ms[i] <= 0.0) continue; - std::snprintf(b, sizeof b, " %s %.0f (%.1f%%)", kPfNames[i], pt.ms[i], total > 0 ? 100.0 * pt.ms[i] / total : 0.0); - line += b; - } - std::fprintf(stderr, "strata prefill timing: %lld tokens, GPU timeline %.0f ms, wall %.0f ms, host staging %.0f ms:%s\n", - (long long) n, total, ms_since(t_start), stats_.ms_experts_host, line.c_str()); - std::fprintf(stderr, "strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) %.0f ms, " - "waiting for each chunk %.0f ms, after each chunk (the draft layer, progress) %.0f ms, " - "PLE %.0f ms\n", host_setup_ms, host_sync_ms, host_chunk_ms, stats_.ms_ple); - if (pe.on) { - int pd = 0; cudaGetDevice(&pd); cudaSetDevice(pe.dev); cudaStreamSynchronize(m.pp->s); pe.fold(); cudaSetDevice(pd); - std::string pl; - for (int i = 0; i < kPeCount; ++i) { - std::snprintf(b, sizeof b, " %s %.0f", kPeNames[i], pe.ms[i]); - pl += b; - } - std::fprintf(stderr, "strata prefill timing (peer GPU, ms):%s; MoE layers %lld, rows/layer %.0f of %lld cap, experts/layer %.0f, " - "over the cap %lld\n", pl.c_str(), (long long) m.pp->layers, - m.pp->layers ? (double) m.pp->rows / m.pp->layers : 0.0, (long long) m.pp->cap_rows, - m.pp->layers ? (double) m.pp->experts / m.pp->layers : 0.0, (long long) m.pp->over_cap); - if (m.pp->ps_frac > 0.0) - std::fprintf(stderr, "strata prefill timing: peer-streamed experts %lld (%.0f per MoE layer)\n", - (long long) m.pp->ps_experts, m.pp->layers ? (double) m.pp->ps_experts / m.pp->layers : 0.0); - } - } - if (std::getenv("STRATA_STATE_HASH_GDN") != nullptr) { // debug: the GDN states as the prompt path leaves them - cudaStreamSynchronize(m.cs); - std::vector b((size_t) gdn_floats * 4); - std::string line; - char h[8]; - for (int64_t i = 0; i < ss.gdn_alloc; ++i) { - cudaMemcpy(b.data(), ss.gdn_state + (size_t) i * gdn_floats, b.size(), cudaMemcpyDeviceToHost); - uint64_t x = 1469598103934665603ull; - for (uint8_t c : b) x = (x ^ c) * 1099511628211ull; - std::snprintf(h, sizeof(h), "%04llx ", (unsigned long long) (x & 0xffff)); - line += h; - } - std::fprintf(stderr, "strata prefill: GDN_HASH %s\n", line.c_str()); - } - return true; -} - -bool Prefill::drain_pipeline(std::string& err) { - bool ok = true; - - if (next_run_.valid()) { - if (!next_run_.get()) { - err = next_err_; - ok = false; - } - } - - if (next_ != nullptr) { - std::string tail_err; - if (!next_->drain_pipeline(tail_err)) { - if (ok) err = tail_err; - ok = false; - } - } - - return ok; -} - -bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err) { - const bool body_ok = run_impl(tokens, n, pos0, err); - - std::string drain_err; - const bool drain_ok = drain_pipeline(drain_err); - - if (!body_ok) return false; - if (!drain_ok) { - err = drain_err; - return false; - } - return true; -} - -} // namespace strata::prefill diff --git a/src/program/conv_cache_test.cpp b/src/program/conv_cache_test.cpp deleted file mode 100644 index f4a0c2b..0000000 --- a/src/program/conv_cache_test.cpp +++ /dev/null @@ -1,67 +0,0 @@ -// src/program/conv_cache_test.cpp - the conversation cache's retention policy: the shared root survives, -// the leaves rotate by least recent use. -// -// The scenarios, in the serve loop's terms (generate.cpp): checkpoints are a prefix chain - stamps[0] is -// the root, the deepest point every request so far has shared (the end of the system prompt, in practice). -// A stamp advances on creation, when a new checkpoint lands on an existing length, and when a request -// mounts through the checkpoint. -// -// 1. one conversation over its budget: the oldest leaf leaves - with fresh stamps in creation order this -// is exactly the previous first-in-first-out behaviour; -// 2. the root survives arbitrarily many newer checkpoints however old its stamp is; -// 3. a mount advances a checkpoint's stamp and the rotation then takes a different leaf; -// 4. a one-slot budget has no room for root and leaf, so the pin is off and the oldest leaves (the -// newest point stays, as before); -// 5. the policy is pure: the same stamps, the same victim. -#include "strata/program/conv_cache.hpp" - -#include -#include -#include - -using strata::program::conv_cache::eviction_victim; - -namespace { -int g_fail = 0; -void check(bool ok, const char* what) { - std::printf(" %-66s %s\n", what, ok ? "ok" : "FAIL"); - if (!ok) ++g_fail; -} -} // namespace - -int main() { - std::printf("conv_cache_test\n"); - { - const std::vector stamps = {1, 2, 3, 4, 5, 6, 7}; // chat A: root + six turns, one over - check(eviction_victim(stamps.data(), stamps.size(), 6) == 1, - "over budget with fresh stamps: the oldest leaf leaves (the FIFO it was)"); - } - { - // chat B mounts through the root long after it was created; its stamp stays ancient - const std::vector stamps = {1, 100, 101, 102, 103, 104, 105}; - const size_t v = eviction_victim(stamps.data(), stamps.size(), 6); - check(v == 1, "the root's stale stamp never makes it the victim"); - check(v != 0, "the root - the shared prefix - is never the victim"); - } - { - // the same chain after mounting checkpoint 1: its stamp jumps, the rotation moves to the next leaf - const std::vector stamped = {1, 8, 3, 4, 5, 6, 7}; - check(eviction_victim(stamped.data(), stamped.size(), 6) == 2, - "after a mount, the rotation takes the next least recently used leaf"); - } - { - const std::vector stamps = {1, 90, 91, 92}; - check(eviction_victim(stamps.data(), stamps.size(), 2) == 1, - "a two-slot budget keeps root + newest and drops the leaf in between"); - check(eviction_victim(stamps.data(), stamps.size(), 1) == 0, - "a one-slot budget has no pin: the oldest leaves, the newest point stays"); - } - { - const std::vector stamps = {7, 3, 3, 5}; - const size_t a = eviction_victim(stamps.data(), stamps.size(), 4); - const size_t b = eviction_victim(stamps.data(), stamps.size(), 4); - check(a == 1 && b == 1, "ties among equally stale leaves: the earlier index, deterministically"); - } - std::printf(g_fail ? "FAIL\n" : "PASS\n"); - return g_fail ? 1 : 0; -} diff --git a/src/program/generate.cpp b/src/program/generate.cpp deleted file mode 100644 index d34c915..0000000 --- a/src/program/generate.cpp +++ /dev/null @@ -1,8843 +0,0 @@ -// src/program/generate.cpp - P2.S6: `strata generate`. -// -// THE DRIVER, and the first program in this project that answers a question. Everything below it is a -// component; this is the thing that composes them into a token: -// -// embed_row(token) -> 48 captured layer graphs (the CPU expert pool behind the doorbell) -> -// lm_head(R) -> sample -> embed_row(next) -> ... -// -// WHAT IT IS NOT. There is no tokenizer here. `pack/full/tokenizer/` and `tools/strata_tokenizer.py` exist, -// and a C++ BPE is Phase 1's deliverable rather than this program's, so the prompt arrives as IDS via -// `--tokens`. That is not a placeholder: it is exactly what Gate C1 needs, because C1 compares logits against -// llama.cpp on the SAME ids, and a tokenizer on only one side of that comparison is a second variable. -// -// AND IT IS PHASE 2, so hit rate is `h = 0` and the number it prints is slow on purpose -// (`phase-2-correct-engine.md:5-9`). What it is FOR is the honest tok/s figure and the logit dump. - -#include "strata/core/device.hpp" -#include "strata/core/remote_expert_opt.hpp" -#include "strata/core/expert_cache.hpp" -#include "strata/core/conversation_snapshot.hpp" -#include "strata/core/conversation_memory.hpp" -#include "strata/core/coupled_draft.hpp" -#include "strata/core/expert_source.hpp" -#include "strata/core/pinned.hpp" -#include "strata/core/remote_experts.hpp" -#include "strata/core/on_device.hpp" -#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" -#include "strata/kernels/cpu/pool.hpp" -#include "strata/kernels/cpu/expert_layout.hpp" -#include "strata/kernels/ngram.hpp" -#include "strata/kernels/iq_kernels.hpp" -#include "strata/kernels/s2_expert_grouped.hpp" -#include "strata/kernels/sampler.hpp" -#include "strata/kernels/verify_kernels.hpp" -#include "strata/kernels/shared_expert.hpp" -#include "strata/kernels/native_moe.hpp" -#include "strata/kernels/native_gdn.hpp" -#include "strata/kernels/native_router.hpp" -#include "strata/kernels/native_qsa.hpp" -#include "strata/kernels/native_qsa_indexer.hpp" -#include "strata/kernels/native_rope.hpp" -#include "strata/kernels/mrope.hpp" -#include "strata/kernels/kv_q4.hpp" -#include "strata/kernels/qsa.hpp" -#include "strata/core/native_head.hpp" -#include "strata/core/verify.hpp" -#include "strata/core/mtp.hpp" -#include "strata/prefill/prefill.hpp" -#include "strata/core/native_dense.hpp" -#include "strata/program/logits_selection.hpp" -#include "strata/program/conv_cache.hpp" -#include "strata/spec/draft_policy.hpp" -#include "strata/spec/suffix_drafter.hpp" -#include "strata/kernels/cvec.hpp" -#include "strata/core/progress.hpp" -#include "strata/core/device.hpp" -#include "strata/core/emulate.hpp" -#ifndef NOMINMAX -#define NOMINMAX // gguf_reader.hpp includes windows.h -#endif -#include "strata/artifact/gguf_reader.hpp" -#if defined(_WIN32) -#include -#include -#include -#else -#include -#include -#include -#include -#endif - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { -// Windows' WDDM driver model: native Windows, or WSL2 (its GPU goes through /dev/dxg to the Windows driver). There, -// pinning a large arena into two CUDA contexts leaves WDDM refusing every later allocation (the 5080 + 3090 rig); -// a Linux driver has no such limit (#253: the 8 GiB cap cost a 4090 + 3060 split 3x of its prompt speed). -bool under_wddm() { -#ifdef _WIN32 - return true; -#else - static const bool dxg = std::filesystem::exists("/dev/dxg"); - return dxg; -#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 (vram_info(&free_b, &total_b) != cudaSuccess) { - (void) cudaGetLastError(); - return {}; - } - char buf[96]; - std::snprintf(buf, sizeof buf, " (%llu MiB of %llu MiB VRAM free on this GPU)", (unsigned long long) (free_b >> 20), - (unsigned long long) (total_b >> 20)); - return buf; -} - -// perf-review D-4: the lent slots are refilled with queued copies and one wait; STRATA_REFILL_BLOCKING=1 waits on each -// A file-backed arena on AMD (STRATA_ARENA_MMAP; the engine raises ROCclr's pin-in-place threshold, see main): an -// adaptive swap copies one expert straight from the mapped file. Through ROCclr's staging that copy blocks the host -// (decode windows of 150+ ms); instead the batch's pages are locked here for the async copies and unlocked when they -// have landed (unpin_blobs), so the release that follows can hand them back. Neighbouring experts share a page and -// a copy from a range only PART of which is registered fails ("invalid argument"), so the page ranges are merged -// first and each merged span is registered once. A span that does not register is copied through the staging -// path. Portable: a layer split copies to either card. -// Whether pin_blobs locks anything (AMD on Linux with STRATA_ARENA_MMAP=1): the callers only gather the swaps' spans -// then - `blob()` is not free (it counts reads, and the file tier may assemble the blob), so the default runs skip it. -bool pin_blobs_on() { -#if (defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)) && !defined(_WIN32) - static const bool on = std::getenv("STRATA_ARENA_MMAP") && std::getenv("STRATA_ARENA_MMAP")[0] == '1'; - return on; -#else - return false; -#endif -} -int pin_blobs(std::vector> r, std::vector& live) { - int failed = 0; // ranges left pageable (a copy from them still works, through the driver's staging) -#if (defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)) && !defined(_WIN32) - if (!pin_blobs_on() || r.empty()) return 0; - for (auto& [a, e] : r) { a &= ~(uintptr_t) 4095; e = (e + 4095) & ~(uintptr_t) 4095; } - std::sort(r.begin(), r.end()); - size_t k = 0; - for (size_t i = 1; i < r.size(); ++i) { - if (r[i].first <= r[k].second) r[k].second = std::max(r[k].second, r[i].second); - else r[++k] = r[i]; - } - r.resize(k + 1); - for (const auto& [a, e] : r) { - if (cudaHostRegister((void*) a, (size_t) (e - a), cudaHostRegisterReadOnly | cudaHostRegisterPortable) == - cudaSuccess) - live.push_back((void*) a); - else { - (void) cudaGetLastError(); - ++failed; - } - } -#else - (void) r; (void) live; -#endif - return failed; -} -void unpin_blobs(std::vector& v) { - for (void* p : v) (void) cudaHostUnregister(p); - (void) cudaGetLastError(); - v.clear(); -} - -// STRATA_RSS_TRACE=1: the process's mapped file pages (the arena) at a startup step - who reads the arena back -void rss_probe(const char* where) { - static const bool on = std::getenv("STRATA_RSS_TRACE") != nullptr; - if (!on) return; - FILE* f = std::fopen("/proc/self/status", "r"); - if (!f) return; - char line[256]; - long long kb = -1; - while (std::fgets(line, sizeof line, f)) - if (std::strncmp(line, "RssFile:", 8) == 0) { kb = std::atoll(line + 8); break; } - std::fclose(f); - std::fprintf(stderr, "strata rss: %s: RssFile %.2f GiB\n", where, (double) kb / (1024.0 * 1024.0)); - std::fflush(stderr); -} - -bool refill_blocking() { - static const bool v = std::getenv("STRATA_REFILL_BLOCKING") != nullptr; - return v; -} - -using Clock = std::chrono::steady_clock; - -// The resident RAM mode and the adaptive tier. A swap copies `in` (held in RAM) into the slot of `out` (held only -// by that slot). Before the slot is overwritten, `out`'s bytes are copied back from it into an exchange buffer, so -// the CPU computes `out` from RAM while the swap is in flight; when the swap has landed, `commit_exchanges` moves -// them into `in`'s place in RAM. The RAM copy then again holds exactly the experts no core slot does, and no swap -// reads the file. Swaps that need no exchange (`out` in the lend region is held in RAM already; or `in` is not) go -// on as before; ones beyond the buffers' room wait for a later round. Runs on the adaptive tier's thread while the -// GPU commits and drafts: the copies back are on its stream, and waited for before the refills are queued. -template -bool resident_stage_swaps(strata::core::FileExpertSource& src, strata::core::ExpertCache& cache, - const std::vector& host_res, int64_t n_expert, std::vector& swaps, - cudaStream_t stream) { - if (!src.complement_ready() || swaps.empty()) return true; - struct Staged { int32_t layer, in, out; int64_t q; }; - std::vector staged; - std::vector kept; - kept.reserve(swaps.size()); - for (const Swap& s : swaps) { - if (!src.has_resident(s.layer, s.in) || src.has_resident(s.layer, s.out)) { kept.push_back(s); continue; } - const int64_t q = (int64_t) staged.size(); - if (q >= src.exchange_capacity()) continue; - const int32_t slot = host_res[(size_t) s.layer * (size_t) n_expert + (size_t) s.out]; - if (slot < 0) continue; - if (cudaMemcpyAsync(src.exchange_buffer(q), cache.device_slot(slot), - (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer), cudaMemcpyDeviceToHost, - stream) != cudaSuccess) - return false; - staged.push_back({s.layer, s.in, s.out, q}); - kept.push_back(s); - } - if (!staged.empty()) { - if (cudaStreamSynchronize(stream) != cudaSuccess) return false; - for (const Staged& x : staged) - if (!src.stage_exchange(x.layer, x.in, x.out, x.q)) return false; - } - swaps.swap(kept); - return true; -} - -struct Options { - std::string pack = "pack/full"; - std::vector tokens; // the prompt, PRE-TOKENIZED - int64_t max_new = 16; - int64_t max_context = 4096; - bool greedy = true; - uint64_t seed = 0; - int top_k = 20; - float top_p = 0.95f; - float temperature = 1.0f; - std::string dump_logits; // one line of logits per generated position - int64_t logits_stride = 1; // storage selection; all prompt tokens remain conditioned - /// **THE RESIDUAL, SO THE HEAD CAN BE CHECKED WITHOUT THE LAYERS.** - /// - /// C1 fails (LEDGER L116) and the pipeline is `embed -> 48 layers -> head`. Dumping `R` splits it in half: - /// the head is one norm, two bf16 projections and one 794 MB GEMV, all of which can be recomputed in Python - /// from the manifest. If Python agrees with the engine on the same `R`, the head is right and the layers - /// are wrong; if it disagrees, the head is wrong. Nothing else in the engine can be split that cheaply. - std::string ple_gguf; // the ORIGINAL second GGUF shard: the PLE table is not in the pack - bool no_ple = false; // explicit diagnostic ablation; never a normal inference default - bool stream_token = false; // R2.6 experiment: ordered work on the session stream - bool check_logits = false; // optional full-vocabulary finite scan - bool gr_fp32_activations = false; // pinned CUDA single-token BF16 activation contract - bool gr_native_mmvf = false; // pinned projection reduction tree as well as FP32 inputs - bool native_bf16 = false; // SSM gates, router and indexer projections only - bool native_bf16_extra = false; // PLE value and shared expert scalar gate - bool native_ple_key = false; // unchanged Q2_0 key and CUDA Q8_1 activations - bool native_moe_combine = false; // pinned fused CUDA weighted reduction - bool native_gdn = false; // pinned CUDA recurrence and preprocessing - bool native_flash_attn_short = false; // diagnostic pinned attention, context <=256 - bool native_qsa_indexer = false; // pinned F16 key cache and F32 pooling - bool native_qsa = false; // pinned F32 QSA norms and gate - /// THE CONTEXT EXTENSION (rope scaling, rope_scaling.hpp). These knobs resolve to ONE process config, - /// set once before `session_init` builds the rope table and the graphs capture the kernels. There is - /// deliberately no per-request form: K sits in the cache POST-RoPE, so one cache must never mix two - /// scalings. Precedence: an EXPLICIT flag over the model file's rope keys over the struct defaults - - /// `none` and `1` are explicit values (the opt-outs), the absent flag is not. - std::string rope_scaling; ///< --rope-scaling none|linear|yarn (llama.cpp's names); empty = the flag is absent - double rope_scale = 0; ///< --rope-scale F: the extension factor; 0 = the flag is absent (the model file's, else 1 = off) - double rope_freq_base = 0; ///< --rope-freq-base N: 0 = the model's (1e7) - double rope_freq_scale = 0; ///< --rope-freq-scale F: the raw ggml knob; 0 = 1/--rope-scale - double yarn_orig_ctx = 0; ///< --yarn-orig-ctx N: 0 = the model's, else 262144 - double yarn_ext_factor = -1.0; ///< --yarn-ext-factor F: <0 = auto (1 for yarn, 0 otherwise) - double yarn_attn_factor = 1.0; ///< --yarn-attn-factor F - double yarn_beta_fast = 32.0; ///< --yarn-beta-fast F - double yarn_beta_slow = 1.0; ///< --yarn-beta-slow F - bool native_rope = false; // pinned text-only CUDA rotary arithmetic - bool native_ple_postops = false; // pinned PLE postprojection arithmetic - bool native_router = false; // pinned fused 512-expert top-10 router - bool cpu_oracle_q8_0 = false; // pinned x86 activation scales/codes at both expert stages - std::string native_head_gguf; // native output.weight experiment; same model shard as the pack - std::vector native_dense_gguf; // repeat for native GDN/QSA projection shards - /// Every shard of --native's model (strata::gguf_split_paths: the metadata shard first; a missing shard is an - /// error) and of --native-head-gguf's (the same list unless that names another model). - std::vector native_shards, native_head_shards; - /// Plan v0.3 P1: the whole native arithmetic set as ONE switch (model shard 1). It enables exactly the - /// combination recorded in bench/results/2026-09-23-attention-ple plus the native indexer, and never the - /// <=256-token attention adapter. It becomes the default once P0 shows it is not slower. - std::string native_preset; - /// The token embedding from this GGUF instead of --native's (tools/embd_bf16_pack.py: BF16 as shipped) - std::string embd_gguf; - /// Plan v0.3 P2: how the n-gram table is read. Direct (default) = unbuffered SSD reads, table never in RAM. - std::string ple_io = "direct"; - int64_t ple_row_cache = 1 << 20; ///< bounded row cache (rows of 90 B); 0 disables - int ple_inflight = 256; // the prompt path reads a chunk's rows at once: 64 left the SSD half idle (32K: 303 -> 189 ms) - double ple_delay_us = 0; ///< fault injection: every row read completes no earlier than this - bool ple_sync_submit = false; ///< A/B arm: submit reads on the token thread, no I/O worker - std::string kv = "fp16"; ///< plan v0.3 P7: KV storage, fp16 (default) or int8 (half the VRAM) - int64_t kv_resident = 0; ///< KV streaming: resident cells per QSA layer (0: all in VRAM) - std::string dump_residual; - /// The head input, `bb.mixed`. It exists so the head can be SPLIT: steps 1-4 (the per-stream norm, the two - /// bf16 projections and the stream mean) recompute cheaply in Python, and only the 794 MB GEMV does not. - std::string dump_mixed; - /// One residual snapshot per layer per position: `n_layers * hc * n_embd` floats per position, appended in - /// position order. This is the C1 BISECTION LADDER - it is what `llama-debug --tensor-filter l_last` prints - /// for the reference, so the first layer whose `sum` diverges is the layer that holds the bug. It needs the - /// captured path (the expert pool only exists there), so it is refused with `--no-capture`. - std::string dump_layers; - /// `2 * n_embd + 2 * hc` floats per layer per position: the attention half's block output, the MoE half's, - /// and the two injection vectors. It separates `linear_attn_out-` from `ffn_out-`, which the residual - /// ladder cannot. **CAPTURED INTO THE LAYER GRAPHS**, so it must be armed before `session_capture`. - std::string dump_halves; - /// P0.S8's routing trace, and a prerequisite the Phase 3 plan names explicitly. One record per layer per - /// position: `int32 layer, int32 k, k int32 ids, k float weights`. It is what a hit-rate curve for a - /// candidate VRAM expert cache is computed from, and it needs no new kernels - the doorbell already - /// publishes exactly this much to pinned memory. - std::string dump_routing; - bool no_capture = false; // run the layers directly instead of replaying graphs - bool no_pool = false; // skip the CPU expert pool: the GPU-only floor - bool sync_every_layer = false; - /// Per-stage CUDA-event timings inside the layer halves. `--no-capture` only: an event recorded inside a - /// stream capture is silently dropped, so the captured path cannot carry this. - bool stage_timing = false; - /// Launch the 48 captured `pre` graphs back to back with no host work between them and report the pure GPU - /// time per token. This is the only measurement that separates host-bound from GPU-bound, because the - /// stage events include every gap where the GPU waited for the host. - bool graph_only = false; - bool gpu_only_full = false; ///< R0.3: pre + post + head, the true per-token GPU floor - int pool_workers = 0; ///< R2.2: 0 = "all physical cores minus the host's"; >0 overrides - /// #272: the pool's core layout; `all` (the default) is the layout it always had, auto / p-cores are opt-in - strata::kernels::cpu::PoolAffinity pool_affinity = strata::kernels::cpu::PoolAffinity::All; - /// R2.2's first half, as an A/B arm. **ON by default**, because the measurement that justifies it is the - /// pool's own drain: 33.7 GB/s against 5/6 x 44.14 = 36.8 for five workers, on a machine whose sixth core - /// is reserved for a host thread that has nothing to do while the drain runs. - bool no_host_worker = false; - bool coupled_draft = strata::core::coupled_draft_env(); ///< Coupled draft sampling for MTP drafter under sampling - bool mmap_experts = false; ///< R2.1: opt OUT of the resident arena, back to MapViewOfFile - std::string shared_expert_arena; ///< Linux: optional file backing for the resident arena shared by processes - bool resident_cpu_experts = false; ///< mmap-backed static-cache misses copied into ordinary RAM - /// `--resident-experts` (the low-RAM PC's resident mode, chosen by setup): `--resident-cpu-experts` with the copy - /// page-locked when the driver allows (else locked in the working set), 4 GiB of RAM headroom, and plain mmap - /// (with a warning) when even the experts no slot holds do not fit. - bool resident_pin = false; - uint64_t resident_headroom = 8ull << 30; - bool resident_soft = false; - bool resident_cpu_explicit = false; ///< #384: --resident-cpu-experts given by itself (not only implied) - /// CS-T `--resident-budget-gib N`: the resident mode with a RAM budget - the N GiB of experts the GPU cache does - /// not hold that the expert profile ranks hottest are copied into RAM, the rest are read from the files in place - /// (the GGUF shards when the pack has no experts.bin). 0 = the whole complement (--resident-experts). - uint64_t resident_budget = 0; - /// R4: slots of VRAM-resident experts. **0 = off, and off is the default.** - /// **THE COMMENT THAT USED TO BE HERE WAS FALSE AND ROUND 328 MEASURED IT.** It said "the cache has no - /// consumer yet - `moe_hit_grouped_s2` does not exist - so switching it on costs the fill traffic and - /// saves nothing". The kernel exists (`src/kernels/cuda/s2_expert_grouped.cu`), it is wired at line ~660 - /// via `expert_hit_run`, and switching the cache on **does** move work off the CPU pool: the drain fell - /// **19.076 -> 10.312 ms/token** at 4096 per-layer slots, for **-2.7 ms/token** end to end. What was - /// true is that the ADMISSION POLICY gave every slot to the first position, which is why the earlier - /// measurement found nothing - see `expert_cache_per_layer`. - int expert_cache = 0; - std::array expert_cache_remote{}; ///< CUDA1..3 slots; CUDA0 keeps dense/state/MTP - std::array expert_cache_remote_auto{}; - bool remote_expert_opt = false; ///< optional optimization of the existing remote-expert decode path - std::string expert_cache_remote_placement = "stripe"; ///< stripe experts or assign complete layers to CUDA1..3 - bool expert_cache_cpu_order = false; - /// **R4.2g. ROUND 328 MEASURED THAT THE GLOBAL ADMISSION POLICY CANNOT WORK, AND THIS IS THE FIX.** - /// The default policy hands out slots in arrival order from one counter shared by all 48 layers, so the - /// first `n_slots` distinct pairs - about 26 LAYERS OF POSITION 0 - take every slot and hits are confined - /// to them. Measured at 256 slots: **1781 of 60000 = 2.97%**, against **21.4%** for 8 slots per layer and - /// **70.4%** for 64, from `Memory/cache_allocation.py` on the same run's routing. Off by default. - bool expert_cache_per_layer = false; - /// Multi-GPU: a second expert tier on CUDA device `peer_device` (-1 = off), `peer_reserve_mib` left free - /// there, `peer_slots` caps its size (0 = as many as fit), `peer_adapt_swaps` per adaptive round - /// (-1 = adapt_swaps). - int peer_device = -1; - int peer_reserve_mib = 600; - int64_t peer_slots = 0; - int peer_adapt_swaps = -1; - /// the prompt path's rows per layer the peer computes: -1 = half of chunk x top-k, 0 = the prompt path stays on - /// the primary - int64_t peer_prefill_rows = -1; - /// The PLE gather's prefetch, as an A/B arm. The gather measured 2.10-2.61 ms/token because its sixteen - /// row reads are sixteen SEPARATE page faults into a 26.8 GB mapping; see `ple_prefetch_enable`. - bool no_ple_prefetch = false; - /// R4.2e: a `profile.bin` from `tools/make_profile.py`. **When given, it decides residency instead of the - /// compulsory-miss policy**, which is the whole point: a profile ranked by routing frequency over a whole - /// trace is what the plan's `h = 0.6447` refers to, and compulsory-miss measured 0.4864 because it fills - /// with whatever the prompt touched FIRST. Empty means no profile. - std::string expert_profile; - /// #477 (--serve, opt-in): where to save what the adaptive tier learned, as a profile `--expert-profile` reads - /// (the resident experts first, then the routing counted since the start); on QUIT and every - /// `expert_profile_save_min` minutes between requests. Empty (the default): nothing is counted or written. - std::string expert_profile_save; - double expert_profile_save_min = 10.0; - /// R4.2d: **ON by default**, because the measurement is unambiguous and the alternative is known-broken. - /// Without it, 17 of 10,562 layers had the hit work done when the pool returned; with it, 9,190. The - /// A/B arm is `--no-hit-poke`. - bool no_hit_poke = false; - /// R0.9: capture each layer as THREE graphs and time them from outside the capture, which is the only - /// valid way to get a per-stage table on the real graph. Prints and exits; it is a measurement, not a run. - bool gpu_stages = false; - bool stats = false; - bool shared_late = false; ///< plan v0.3 P3 A/B: shared expert inside post[l] (old order) - bool keep_canonical = false; ///< plan v0.3 P1 A/B: load canonical copies of natively served tensors - bool no_token_graph = false; ///< plan v0.3 P3 A/B: two graphs per layer instead of one per token - bool no_fused_gr = false; ///< plan v0.3 P3 A/B: the six-kernel native gr_read + separate gr_write - bool no_fast_attn = false; ///< plan v0.3 P3 A/B: gather + one-block-per-head QSA attention - bool no_publish_kernel = false; ///< plan v0.3 P3 A/B: memcpy nodes for the doorbell and QSA step - bool no_fused_gdn = false; ///< plan v0.3 P3 A/B: llama.cpp-layout GDN step + separate out norm - bool no_fast_select = false; ///< plan v0.3 P7 A/B: FP64 row scores + bit-serial cell top-k - /// Plan v0.3 P4: `--expert-cache auto` sizes the VRAM tier from what is free after the weights, the session - /// 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 ` command can give part of it back to other programs and take it again. Off: one cudaMalloc. - bool vram_elastic = false; - int64_t vram_segment_mib = 512; - /// Plan v0.3 P5: batched prompt processing in chunks of this many tokens (0 = the token path). - int64_t prefill_chunk = 0; - /// `--prefill auto`: the largest chunk (up to 8192) whose buffers the expert cache can lend. Every expert a chunk - /// routes to is streamed once per chunk, so a bigger chunk streams fewer bytes per token (the "ubatch" effect). - bool prefill_auto = false; - /// #282, opt-in: the largest chunk `--prefill auto` may take - 8192 by default; `--prefill auto:16384` or - /// `auto:32768` (or STRATA_PREFILL_AUTO_MAX) lets it go further, never past the context - int64_t prefill_auto_max = 8192; - bool no_split_rows = false; ///< plan v0.3 P4 A/B: one whole expert per pool thread - /// Plan v0.3 P5: the prompt path borrows the top expert-cache slots for its buffers and refills them after - /// the prompt (default); `--no-prefill-borrow` reserves the buffers' VRAM for the whole session instead. - bool no_prefill_borrow = false; - /// Plan v0.3 P5 validation: batch only positions [0, P) and run the rest of the prompt through the token path - /// (teacher-forced), so the logits of positions >= P - which depend on the batched state - can be scored - /// against the oracle at many positions. 0 = the whole prompt but the last position. - int64_t prefill_until = 0; - /// Plan v0.3 P6: after every processed position, append the residual after the last layer (hc x n_embd - /// floats, the MTP draft head's input) to this file. Token path only. - std::string dump_final_r; - /// Plan v0.3 P6: speculative decoding with a verify window of this many tokens (the last accepted token and - /// spec-1 drafts); 0 = plain decode. `spec_oracle` drafts from a token file (the expected continuation, for - /// the exactness test); `spec_corrupt` N > 0 replaces every Nth draft with a wrong token. - int spec = 0; - /// --serve runs up to this many sequences at once, one token each per batch window (0 = off). A request - /// sent as `BGEN ...` reads its prompt and its first token through the usual path, then - /// continues in slot of the batch windows (`BT ` lines, then `BDONE ...`). - int batch = 0; - /// With an explicit --layer-split, every GPU loads only its own layers' dense weights instead of the whole - /// model's: the VRAM they took goes back to the expert cache (opt-in) - bool trim_stage_weights = false; - /// The --batch slots in this many groups pipelined through the stages of a layer split (stage k - /// runs one group while stage k+1 runs another). 1 = every slot in one window, stage after stage. - 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) - /// Plan v0.3 P6: the share (0..1) of each layer's distinct missed experts the GPU reads over PCIe from the - /// pinned arena while the CPU computes the rest (verify windows). - double pcie_frac = -1.0; ///< < 0: the model's default (0.2 direct for the Q2_0 pack, 0.55 DMA for native packs) - std::string pcie_mode = "auto"; ///< auto | dma | kernel | direct - /// Plan v0.3 P6: every `adapt_every` rounds, swap up to `adapt_swaps` of the most-routed missing experts into - /// the VRAM tier in place of the least-routed resident ones (decayed counts). 0 = static residency. - int adapt_every = 4; - float adapt_decay = 0.7f; ///< the usage counts are multiplied by this after each adaptation (--adapt-decay) - /// Plan v0.3 P6: a draft enters the verify window only while every draft before it (and itself) has at least - /// this probability under the draft layer; 0 = always --spec-1 drafts. - double spec_min_p = 0.0; - /// Stop when the model emits an end-of-turn token (<|endoftext|> 248044, <|im_end|> 248046, or --eos-ids). - bool stop_eos = false; - std::vector eos_ids = {248044, 248046}; - bool spec_split = false; ///< opt-in split verify window (the overlap study: exact, ~7% slower) - /// --serve, multi-GPU layer split: "K" or "K1,K2,.." (the first layer of each later stage) or "auto" (placed - /// from each GPU's free VRAM); empty = one GPU - std::string layer_split; - /// the later stages' devices "D1,D2,.." (default: the next visible GPUs; "0" with one K: both stages on this - /// GPU, sharing everything - the bit-exact A/B of the hand-off) - std::string split_device; - /// --split-skip-if-fits (opt-in; the server passes it for a config's "split_skip_if_fits"): with - /// --layer-split auto, run on CUDA0 alone when it holds every profiled expert pair plus the whole session (KV), - /// the drafter and the reserve - a split then only adds hand-offs (two RDNA4 cards: 1,384 vs 1,794 tok/s at 4K) - bool split_skip_if_fits = false; - /// Plan v0.3 P8: stay resident and take requests on stdin (see the --serve block in main). - bool serve = false; - /// The vision path: keep a per-cell (t, h, w) rotary position table so --serve can take GENI requests. - bool vision = false; - int adapt_swaps = 96; - /// --serve: how many conversation checkpoints to keep between requests (0 = every request reads its whole - /// prompt again, the v0.1.2 behaviour). One is the GDN recurrence of the 36 layers, the QSA indexer tails and - /// the PLE history (~118 MB of host RAM); the KV cache itself is positional and stays where it is. - int prompt_cache = 6; - int64_t conversation_cache_mib = 0; // opt-in host RAM for independent conversations - int conversation_cache_slots = 4; - int64_t conversation_cache_min_free_mib = 2560; - /// --serve: also keep a checkpoint every N freshly read prompt tokens (0 = only at the last turn boundary) - int64_t prompt_cache_every = 16384; - /// --serve: a prompt read from token 0 is also checkpointed at its first turn boundary - the end of the system - /// prompt, which every chat of the same client shares - when that is at least N tokens (0 = never) - int64_t prompt_cache_root = 2048; - /// --serve: the token that opens a chat turn (<|im_start|>). The last one in a prompt is where the chat's - /// history ends and the new assistant turn begins, which is the checkpoint the next request can reuse. - int64_t turn_token = 248045; - /// --serve (#458, opt-in): the role token of a short turn the server puts right before the new assistant turn - /// (the "system" of a trailing reasoning-effort turn). When the turn before the last <|im_start|> opens with it, - /// the checkpoint goes in front of that turn instead, so it holds the conversation and not the effort text. - /// -1 = off (the checkpoint at the last <|im_start|>, as before). - int64_t tail_role_token = -1; - /// --serve: a text part of the prompt of at most N tokens (a chat message, the assistant header, a short tool - /// result) goes through the verify windows, S tokens at a time, instead of the batched prompt path (0 = always - /// the batched path) - int64_t short_read = 64; - /// The suffix drafter (prompt lookup): when the text being written repeats an earlier stretch of the context (code - /// edits, quoted input, tool-call JSON) by at least this many tokens, the window may be filled with what followed - /// it there instead of the MTP's drafts, where the MTP's own first guess agrees and the draft policy expects it to - /// pay (strata/spec/draft_policy.hpp). On by default; 0 = MTP only. - int suffix_draft = 3; - /// The MTP's own window cap (0 = --spec): with --spec 6 --mtp-max-t 4 the long windows come from suffix matches. - int mtp_max_t = 0; - /// A control vector on the residual stream (strata/kernels/cvec.hpp), with llama.cpp's flags: the - /// `experimental-speed-projection` profile passes `--control-vector-scaled FILE:1.0 --control-vector-layer-range - /// 4 44 --cvec-mode project --cvec-dir per-layer`. None by default; --serve switches a loaded one per request. - std::vector> cvec_files; - int cvec_first = -1, cvec_last = -1; ///< llama.cpp's defaults: 1 .. the last layer - int cvec_mode = 1; ///< 0 = project, 1 = add (llama.cpp's default) - int cvec_single = -1; ///< --cvec-dir single:L (project mode): layer L's direction everywhere -}; - -void usage() { - std::fprintf(stderr, - "strata generate --pack DIR --tokens \"1,2,3\" [options]\n" - "\n" - " --pack DIR the pack directory (default pack/full)\n" - " --tokens LIST the prompt as comma-separated token IDS (required)\n" - " --tokens-file PATH pretokenized prompt, commas or whitespace (alternative to --tokens)\n" - " --ple-gguf PATH required PLE table (original second GGUF shard); with --native, the model's\n" - " shard that holds per_layer_token_embd.weight when not given\n" - " --no-ple explicit diagnostic ablation of the PLE layer\n" - " --ple-io direct|mmap|ram n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n" - " reads, the table never enters RAM or the file cache; mmap: A/B arm;\n" - " ram: mmap with the whole table locked in RAM at start (Linux/macOS)\n" - " --ple-row-cache N bounded cache of fetched rows, 90 B each (default 1048576; 0 = off)\n" - " --ple-inflight N outstanding SSD reads (default 256)\n" - " --ple-delay-us U fault injection: each row read completes no earlier than U us\n" - " --ple-sync-submit A/B arm: submit table reads on the token thread (default: an I/O thread)\n" - " --kv fp16|int8 KV storage (plan v0.3 P7): int8 codes + fp16 scale per 64 values, half the\n" - " VRAM; default fp16 until gate G-C accepts int8\n" - " --kv q4_0 4-bit K/V after a Hadamard rotation (PR #21): half of int8's memory,\n" - " slightly lower precision (see bench/results/2026-09-27-kv-q4)\n" - " --kv k8v4 hybrid: INT8 K (exact attention scores) + rotated Q4_0 V, 816 B/cell\n" - " (vs int8's 1,056); not with --kv-resident\n" - " --kv-resident N KV streaming: keep N cells of each QSA layer in VRAM (min 20480) and the\n" - " whole K/V in pinned RAM; the freed VRAM goes to expert slots. 0 (default):\n" - " all of it in VRAM. A context of N cells or fewer is not streamed\n" - " --stream-token enqueue token work on the session stream (experimental)\n" - " --check-logits copy and check all logits in the stream-token path\n" - " --gr-fp32-activations experimental CUDA-oracle GR activation precision\n" - " --gr-native-mmvf experimental pinned GR norm/projections; implies FP32 activations\n" - " --native-bf16 experimental CUDA-oracle SSM/router/indexer BF16 projections\n" - " --native-bf16-extra experimental CUDA-oracle PLE/shared gate BF16 projections\n" - " --native-ple-key experimental native PLE key; requires --native-dense-gguf\n" - " --native-moe-combine experimental pinned CUDA routed/shared combination\n" - " --native-gdn experimental pinned CUDA GDN norms/gates/recurrence\n" - " --native-flash-attn-short diagnostic pinned vector attention; --max-context <=256\n" - " --native-qsa-indexer experimental pinned indexer key cache and pooling\n" - " --native-qsa experimental pinned QSA normalization and output gate\n" - " --native-rope experimental pinned text-only CUDA rotary arithmetic\n" - " --native-ple-postops experimental pinned PLE postprojection arithmetic\n" - " --native-router experimental pinned CUDA 512-expert top-10 routing\n" - " --cpu-oracle-q8-0 experimental pinned CPU expert quantization and dot reduction\n" - " --native SHARD1 every full-context native path at once (plan v0.3 P1): stream-token,\n" - " GR MMVF, BF16, head, dense + PLE key, MoE combine, GDN, router, QSA,\n" - " indexer, RoPE, PLE postops, and the CPU q8_0 contract unless the\n" - " expert cache is on. Individual --native-* flags stay for A/B.\n" - " --native-head-gguf PATH native Q5_K head from model shard 1; requires --stream-token\n" - " --embd-gguf PATH the token embedding from this GGUF instead of --native's (tools/embd_bf16_pack.py:\n" - " BF16 as the checkpoint ships it; mapped host memory, no VRAM)\n" - " --native-dense-gguf PATH native GDN/QSA/shared projections; repeat for each source model shard\n" - " --expert-cache-cpu-order experimental GPU expert reduction matching CPU order\n" - " --max-new N tokens to generate (default 16)\n" - " --max-context N KV/state capacity (default 4096)\n" - " --rope-scaling T extend the context past the trained one: none, linear\n" - " (position interpolation) or yarn - llama.cpp's types and names.\n" - " Default: the model file's rope keys, else none. Fixed at startup:\n" - " K in the cache is post-RoPE, so one run one scaling\n" - " --rope-scale F the extension factor for linear/yarn (default: the model file's\n" - " factor, else 1 = off)\n" - " --rope-freq-base N the raw ggml knobs: the frequency base (0 = the model's 1e7) and\n" - " --rope-freq-scale F the angle shrink (0 = 1/--rope-scale)\n" - " --yarn-orig-ctx N the trained context the correction targets (0 = 262144)\n" - " --yarn-ext-factor F --yarn-attn-factor F --yarn-beta-fast F --yarn-beta-slow F\n" - " YaRN's knobs; defaults: -1 (auto: 1 for yarn), 1, 32, 1\n" - " --greedy argmax (the default)\n" - " --seed S enable sampling with this Philox seed\n" - " --top-k N --top-p F --temperature F\n" - " --dump-logits PATH write one line of raw logits per position\n" - " --logits-stride N store every Nth row plus final input (default 1); N>1 requires --max-new 1\n" - " --dump-residual PATH write the final R (hc x n_embd, f32) for head bisection\n" - " --dump-layers PATH write R after EVERY layer, per position: the C1 bisection ladder\n" - " --dump-halves PATH write both halves' block_out and inject per layer: the half bisection\n" - " --dump-routing PATH write the routed expert ids and weights per layer per position (P0.S8)\n" - " --no-capture run the layers directly instead of replaying graphs\n" - " --shared-late A/B: shared expert after the CPU pool (default: overlapped with it)\n" - " --keep-canonical A/B: also load canonical copies of natively served tensors (more VRAM)\n" - " --vision --serve takes images too (GENI requests; embeddings from strata-vision)\n" - " --prompt-cache N --serve: keep N conversation checkpoints between requests (default 6, ~118 MB\n" - " of RAM each; 0 = read every prompt from the start)\n" - " --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 ` (the server's POST /v1/vram) can\n" - " give VRAM back to other programs between requests and take it back later\n" - " --batch N / --slots N --serve (opt-in): up to N requests decode together in batch slots (2..8),\n" - " each slot with its own session (VRAM like the main one); docs/BATCHING.md\n" - " --batch-groups G --batch with a layer split: the slots in G groups pipelined through the GPUs\n" - " --trim-stage-weights an explicit --layer-split: each GPU loads only its own layers' dense weights\n" - " --prompt-cache-every N --serve: also checkpoint every N fresh prompt tokens (default 16384, 0 = off)\n" - " --turn-token ID --serve: the token that opens a chat turn (default 248045, <|im_start|>)\n" - " --tail-role-token ID --serve: a turn of this role right before the last turn is left out of\n" - " the conversation checkpoint (a trailing effort turn; default -1 = off)\n" - " --short-read N --serve: read at most N fresh text tokens through the decode windows instead\n" - " of the batched prompt path (default 64, 0 = off)\n" - " --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" - " --cvec-mode add|project h += s v (default) or h -= s (h.v) v with v unit\n" - " --cvec-dir per-layer|single:L each layer's own direction (default) or layer L's everywhere (project)\n" - " --no-token-graph A/B: two graphs per layer (the host launches each) instead of one per token\n" - " --no-fused-gr A/B: the six-kernel hyper-connection read and a separate write (native)\n" - " --prefill CHUNK batched prompt processing in chunks of CHUNK tokens (needs --native); auto =\n" - " the largest chunk up to 8192 whose buffers the expert cache can lend;\n" - " auto:16384 / auto:32768 (or STRATA_PREFILL_AUTO_MAX) allow bigger ones\n" - " --no-pool skip the CPU expert pool (the GPU-only floor)\n" - " --sync-every-layer debug: synchronise after every layer\n" - " --ple-gguf PATH the n-gram/PLE shard. WITHOUT IT LAYER 1's PLE IS SILENTLY SKIPPED,\n" - " which changes every number downstream - pass it for any real run\n" - " --dump-mixed PATH write the post-attention residual (n_embd, f32)\n" - " --stage-timing per-stage KERNEL-COUNT shares. NOT a time profile: an uncaptured\n" - " event interval includes host gaps, so run with --gpu-only-full first\n" - " --graph-only MEASURE: replay the 48 `pre` graphs only. OMITS the 48 `post` graphs\n" - " and the LM head, so it is NOT the GPU floor (R0.3, Memory/ERRORS.md A4)\n" - " --gpu-only-full MEASURE: replay pre+post for all 48 layers plus the LM head, no pool.\n" - " THE TRUE PER-TOKEN GPU FLOOR. Quote this one, not --graph-only.\n" - " --stats print the per-stage breakdown\n" - " --gpu-stages R0.9: capture the layer as three graphs (mixer / ffn+router / post)\n" - " and time them from OUTSIDE the capture. The per-stage table on the\n" - " real graph that --stage-timing cannot give. Prints and exits.\n" - " --expert-profile P R4.2e: pre-load the VRAM tier from a `profile.bin` (see\n" - " tools/make_profile.py) instead of admitting on first use.\n" - " --expert-profile-save P --serve, #477: save what the adaptive tier learned (the experts in\n" - " VRAM, then the routing counted since the start) as a profile at P, on\n" - " QUIT and every --expert-profile-save-every MIN minutes (default 10;\n" - " 0 = on QUIT only) between requests; start from it with --expert-profile P\n" - " --no-hit-poke R4.2d's A/B arm. The hit path pokes the driver once right after its\n" - " launch so the GPU starts while the CPU pool runs; without it the work\n" - " waits for the next driver entry and does not overlap at all.\n" - " --no-ple-prefetch A/B arm: read the PLE table's sixteen rows one at a time, instead of\n" - " issuing them in one PrefetchVirtualMemory call.\n" - " --expert-cache N R4: keep N expert blobs resident in VRAM and compute their rows on the\n" - " GPU via `moe_hit_grouped_s2`. DEFAULT 0. Measured at 4096 slots\n" - " with --expert-cache-per-layer: 54.4%% hits, CPU pool drain 19.1 -> 10.3\n" - " ms/token, -2.7 ms/token end to end.\n" - " --expert-cache-device1 N|auto fill CUDA1 with N experts or as many as fit\n" - " --expert-cache-device2 N|auto fill CUDA2 with more experts\n" - " --expert-cache-device3 N|auto fill CUDA3 with more experts\n" - " --remote-expert-opt enable remote-expert decode optimizations (serve mode)\n" - " --expert-cache-remote-placement stripe|layer distribute expert ranks or whole\n" - " layers across CUDA1..3 (default: stripe)\n" - " --peer-device N a second GPU as an adaptive expert-cache tier (rows over P2P; it also\n" - " computes its experts' prompt rows). Not with --layer-split or\n" - " --expert-cache-device1..3. Default output unchanged without it.\n" - " --peer-reserve-mib N VRAM the peer tier leaves free on its card (default 600)\n" - " --peer-slots N expert slots on the peer (default: what fits)\n" - " --peer-adapt-swaps N peer cache swaps per adaptation step (default: --adapt-swaps)\n" - " --peer-prefill-rows N prompt rows per layer the peer computes (default half of chunk x top-k;\n" - " 0 = the prompt path stays on the primary)\n" - " --expert-cache-per-layer R4.2g: give each layer its OWN slots instead of letting the first\n" - " position take all of them. The default policy fills in arrival order\n" - " from one shared counter, so 256 slots went to ~26 layers of position 0\n" - " and measured **2.97%%**. Per-layer, the same routing gives 21.4%% at 8\n" - " slots/layer and 70.4%% at 64.\n" - " --no-host-worker R2.2: the A/B arm. By default the HOST THREAD joins the drain, so the\n" - " pool is six threads on six cores instead of five plus an idle core;\n" - " this flag restores the five-worker form for comparison on `pool phases`.\n" - " --pool-workers N R2.2: CPU expert pool worker count. Default 0 = every physical core\n" - " except the one the host loop spins on (with --pool-affinity auto or\n" - " p-cores on a hybrid CPU: P-cores minus 1). A sweep is how the pool's\n" - " deviation from `cpu_s2` is attributed.\n" - " --pool-affinity MODE Worker CPU affinity: all (default: one worker per physical core, as\n" - " always), auto (hybrid CPUs: P-cores first, then their SMT siblings,\n" - " then E-cores) or p-cores (P-cores and their siblings only).\n" - " --coupled-draft enable coupled draft sampling for MTP drafter under sampling (STRATA_SPEC_COUPLED)\n" - " --no-coupled-draft disable coupled draft sampling (propose argmax drafts)\n" - " --mmap-experts R2.1: opt OUT of the resident expert arena, back to MapViewOfFile.\n" - " The A/B arm: the mmap's rate depends on the OS page cache holding\n" - " 34 GB, and measured 71.97 vs 34.78 ms/token cold vs warm.\n" - " --shared-expert-arena FILE Linux: back the resident arena with one MAP_SHARED file.\n" - " Put this file on /dev/shm, not ordinary SSD storage.\n" - " A small header binds an existing backing file to the same pack.\n" - " --resident-cpu-experts with mmap and a static profile, keep the experts the GPU cache does not\n" - " hold resident in ordinary RAM (and the prompt path's lend region as far as\n" - " RAM allows); adaptive swaps exchange them, so none is read from the file again.\n" - " --resident-experts the low-RAM PC's resident mode (setup): --mmap-experts --resident-cpu-experts\n" - " with the copy page-locked when possible, 4 GiB headroom, plain mmap if it\n" - " does not fit. Same answers as --mmap-experts for the same placement.\n"); -} - -bool parse_i64_list(const char* s, std::vector& out, std::string& err) { - out.clear(); - std::string text(s); - for (char& c : text) if (c == ',') c = ' '; - std::istringstream input(text); - std::string token; - while (input >> token) { - int32_t id = 0; - const auto parsed = std::from_chars(token.data(), token.data() + token.size(), id); - if (parsed.ec != std::errc{} || parsed.ptr != token.data() + token.size() || id < 0) { - err = "invalid token id: expected an integer in [0, 2147483647]"; - out.clear(); - return false; - } - out.push_back(id); - } - if (out.empty()) { err = "token list was empty"; return false; } - return true; -} - -/// The pool's adapter plus the wall-clock it spent, so the report can say how much of the token was the CPU. -struct Drive { - strata::core::ExpertDispatch d; - double cpu_ms = 0; - int64_t calls = 0; - /// THE ROUTING TRACE, which is P0.S8 and a stated prerequisite of Phase 3. `drive_pool` is called once - /// per layer from the main loop - the workers live inside `expert_pool_dispatch` - so a single FILE* here - /// 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, - float* out) { - Drive* t = (Drive*) user; - const Clock::time_point a = Clock::now(); - strata::core::expert_pool_dispatch(&t->d, x_f, ids, weights, n_embd, k, out); - t->cpu_ms += std::chrono::duration(Clock::now() - a).count(); - ++t->calls; - // THE ROUTING TRACE. Written AFTER the dispatch so the layer index is still this layer's: `d.layers` is - // advanced by the adapter as it consumes the blob, and reading it after the call is the same value the - // dispatch used. Record = int32 layer, int32 k, k int32 ids, k float weights. - if (t->routing != nullptr) { - // **`d.layers` HAS ALREADY BEEN ADVANCED BY THE TIME THIS RUNS, AND THE FIRST TRACE WAS OFF BY ONE - // BECAUSE OF IT.** The adapter walks the blob by incrementing `d.layers` as it consumes each layer's - // experts, so after the dispatch it holds the NEXT layer's index. `tools/make_profile.py` caught it - // with a bounds check when the trace turned out to span 1..48 instead of 0..47. The hit-rate CURVE was - // 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 >= 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}; - std::fwrite(rec, sizeof rec, 1, t->routing); - std::fwrite(ids, sizeof(int32_t), (size_t) k, t->routing); - std::fwrite(weights, sizeof(float), (size_t) k, t->routing); - } -} - -/// Plan v0.3 P6: the pool for a verify window. -void drive_pool_multi(void* user, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k, float* out, - int64_t layer) { - Drive* t = (Drive*) user; - t->d.layers = layer; - const Clock::time_point a = Clock::now(); - strata::core::expert_pool_dispatch_multi(t->d, x_f, ids, n_tok, k, out); - t->cpu_ms += std::chrono::duration(Clock::now() - a).count(); - ++t->calls; - // the routing trace for the serve path: the same record format drive_pool writes (layer, k, ids, weights), - // 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 < 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); - std::fwrite(ids + tok * k, sizeof(int32_t), (size_t) k, t->routing); - static const float one[64] = {}; // k <= 64 in a verify window; zeros read as unit weights - std::fwrite(one, sizeof(float), (size_t) k, t->routing); - } - } -} - -/// Layer split: every verify stage shares one Drive (its counters, usage and failure flags); the GPU plan, the expert -/// cache and the PCIe share the pool uses for a layer are those of the stage that runs it. -struct SplitDrive { - static constexpr int kMax = 8; - Drive* base = nullptr; - int n = 0; ///< stages - int64_t end[kMax] = {}; ///< stage i runs the layers from end[i - 1] (0) below end[i] - strata::core::GpuPlanSink* plan[kMax] = {}; - const uint8_t* cache_base[kMax] = {}; - const uint64_t* cache_slot_off[kMax] = {}; - int pcie_num[kMax] = {}; -}; -void drive_pool_split(void* user, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k, float* out, - int64_t layer) { - SplitDrive* s = (SplitDrive*) user; - int st = 0; - while (st + 1 < s->n && layer >= s->end[st]) ++st; - Drive& d = *s->base; - d.d.plan = s->plan[st]; - d.d.cache_base = s->cache_base[st]; - d.d.cache_slot_off = s->cache_slot_off[st]; - d.d.pcie_num = s->pcie_num[st]; - drive_pool_multi(s->base, x_f, ids, n_tok, k, out, layer); -} - -/// Layer split across GPUs: a later stage on its own device, with its own copy of the dense weights, a session, an -/// expert cache for its layers, a verify window and a prompt path; the last one also holds the head (the drafter -/// lives on its device too). -struct GpuStage { - int dev = 0; - int64_t lb = 0, le = 0; - double pcie_frac = 0.0; - strata::core::WeightTable wt; - strata::core::NativeDense dense; - strata::core::NativeHead head; - strata::core::SessionState ss; - cudaStream_t stream = nullptr; - strata::core::ExpertCache cache; - std::vector> profile; ///< its layers' share of the profile, hottest first - int32_t* d_res = nullptr; ///< the residency table on its device - strata::core::Verifier ver; - strata::prefill::Prefill sp; - cudaStream_t adapt_stream = nullptr; - cudaEvent_t adapt_ev = nullptr; - bool adapt_live = false; ///< swaps of this request are in flight on it - int32_t* mrope = nullptr; ///< --vision: the image-position table on its device -}; - -// ---- issue #31: what the watchdog prints before it stops a stalled engine -struct MemSample { - unsigned long long faults = 0, rss_mib = 0, avail_mib = 0, commit_mib = 0; // faults: hard (Linux) / all (Windows) -}; -MemSample mem_sample() { - MemSample m; -#if defined(_WIN32) - PROCESS_MEMORY_COUNTERS pmc{}; - if (K32GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof pmc)) { - m.faults = pmc.PageFaultCount; - m.rss_mib = pmc.WorkingSetSize >> 20; - m.commit_mib = pmc.PagefileUsage >> 20; - } - MEMORYSTATUSEX ms{}; - ms.dwLength = sizeof ms; - if (GlobalMemoryStatusEx(&ms)) m.avail_mib = ms.ullAvailPhys >> 20; -#else - if (std::FILE* f = std::fopen("/proc/self/stat", "r")) { - char buf[4096]; - const size_t n = std::fread(buf, 1, sizeof buf - 1, f); - buf[n] = 0; - std::fclose(f); - const char* s = std::strrchr(buf, ')'); // fields after the command name: 3 state ... 12 majflt - for (int field = 2; s && field < 12; ++field) s = std::strchr(s + 1, ' '); - if (s) m.faults = std::strtoull(s + 1, nullptr, 10); - } - auto kb = [](const char* path, const char* key) -> unsigned long long { - unsigned long long v = 0; - if (std::FILE* f = std::fopen(path, "r")) { - char line[256]; - const size_t kl = std::strlen(key); - while (std::fgets(line, sizeof line, f)) - if (std::strncmp(line, key, kl) == 0) { v = std::strtoull(line + kl, nullptr, 10); break; } - std::fclose(f); - } - return v; - }; - m.rss_mib = kb("/proc/self/status", "VmRSS:") >> 10; - m.commit_mib = kb("/proc/self/status", "VmSwap:") >> 10; - m.avail_mib = kb("/proc/meminfo", "MemAvailable:") >> 10; -#endif - return m; -} - -// the stage the watchdog names: " ", and the prompt chunk a batched read is in (#251) -std::string stage_text() { - const strata::core::Progress& p = strata::core::progress(); - std::string s = std::string(p.where.load()) + " " + std::to_string((long long) p.detail.load()); - if (const int64_t c = p.chunk.load(); c >= 0) s += " of the prompt chunk from token " + std::to_string((long long) c); - return s; -} - -#if !defined(_WIN32) -// #605: whether `path` is on a rotational disk (1), not (0) or unknown (-1), from sysfs; `dev` is the disk's name -int on_rotational_disk(const std::string& path, std::string& dev) { - struct stat st{}; - if (::stat(path.c_str(), &st) != 0) return -1; - char sys[64]; - std::snprintf(sys, sizeof sys, "/sys/dev/block/%u:%u", (unsigned) major(st.st_dev), (unsigned) minor(st.st_dev)); - std::error_code ec; - std::filesystem::path p = std::filesystem::canonical(sys, ec); - for (int up = 0; !ec && up < 2; ++up, p = p.parent_path()) { // a partition has its disk's queue - std::ifstream q(p / "queue" / "rotational"); - int r = -1; - if (q >> r) { - dev = p.filename().string(); - return r; - } - } - return -1; -} - -void thread_wait_channels(std::FILE* f) { - std::error_code ec; - for (const auto& e : std::filesystem::directory_iterator("/proc/self/task", ec)) { - std::ifstream wc(e.path() / "wchan"); - std::string where; - std::getline(wc, where); - std::fprintf(f, " thread %s%s wait channel: %s\n", e.path().filename().string().c_str(), - e.path().filename().string() == std::to_string((long long) ::getpid()) ? " (main)" : "", - where.empty() ? "unavailable" : where.c_str()); - } -} - -// #605: the engine's threads in uninterruptible sleep (state D - almost always waiting for the disk), and where -// (wchan): 16 threads in blk_io_schedule is a disk that cannot keep up, not a deadlock in the engine -void disk_wait_threads(std::FILE* f) { - std::map where; - int waiting = 0, threads = 0; - std::error_code ec; - for (const auto& e : std::filesystem::directory_iterator("/proc/self/task", ec)) { - ++threads; - std::ifstream st(e.path() / "stat"); - std::string line; - std::getline(st, line); - const size_t rp = line.rfind(')'); - if (rp == std::string::npos || rp + 2 >= line.size() || line[rp + 2] != 'D') continue; - ++waiting; - std::ifstream w(e.path() / "wchan"); - std::string wc; - std::getline(w, wc); - ++where[wc.empty() || wc == "0" ? "?" : wc]; - } - if (threads == 0) return; - std::string list; - for (const auto& [name, n] : where) list += (list.empty() ? " (" : ", ") + name + " x" + std::to_string(n); - if (!list.empty()) list += ")"; - std::fprintf(f, " threads waiting on the disk (state D): %d of %d%s%s\n", waiting, threads, list.c_str(), - waiting > 0 ? " - the engine is waiting for the drive: a rotational or failing disk with --ple-io " - "direct (#605: --ple-io ram), or a drive too slow for the reads asked of it" : ""); -} -#endif - -void stall_report(std::FILE* f, uint64_t layers_during) { - strata::core::Progress& p = strata::core::progress(); - std::fprintf(f, "strata serve: stall report (engine %s): stage \"%s\" for %lld s; %llu layers served since the " - "last finished step (0 = stopped, more = slow)\n", STRATA_VERSION, stage_text().c_str(), - (long long) ((strata::core::progress_now_ms() - p.since_ms.load()) / 1000), - (unsigned long long) layers_during); - for (int pass = 0; pass < 2; ++pass) { - if (pass == 1) { - std::this_thread::sleep_for(std::chrono::seconds(2)); - std::fprintf(f, " 2 s later:\n"); - } - if (auto fn = strata::core::diag_pool_fn().load()) fn(f); - if (auto fn = strata::core::diag_verify_fn().load()) fn(f); -#if !defined(_WIN32) - disk_wait_threads(f); - thread_wait_channels(f); -#endif - const MemSample m = mem_sample(); - std::fprintf(f, " memory: %llu MiB resident, %llu MiB %s, %llu MiB RAM available; %llu %s\n", m.rss_mib, - m.commit_mib, -#if defined(_WIN32) - "committed", m.avail_mib, m.faults, "page faults so far" -#else - "in swap", m.avail_mib, m.faults, "major page faults so far" -#endif - ); - std::fflush(f); - } -#if defined(_WIN32) - // every thread's stack, to read against this build's PDB: a few MB beside the engine's working directory - if (HMODULE dbg = LoadLibraryA("dbghelp.dll")) { - using Fn = BOOL(WINAPI*)(HANDLE, DWORD, HANDLE, int, void*, void*, void*); - if (auto write = (Fn) GetProcAddress(dbg, "MiniDumpWriteDump")) { - char path[64]; - std::snprintf(path, sizeof path, "strata-stall-%lu.dmp", (unsigned long) GetCurrentProcessId()); - HANDLE h = CreateFileA(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); - if (h != INVALID_HANDLE_VALUE) { - const int kThreadInfo = 0x1000; // MiniDumpWithThreadInfo; MiniDumpNormal = 0 - const BOOL ok = write(GetCurrentProcess(), GetCurrentProcessId(), h, kThreadInfo, nullptr, nullptr, nullptr); - CloseHandle(h); - char full[MAX_PATH]; - if (!GetFullPathNameA(path, MAX_PATH, full, nullptr)) std::snprintf(full, sizeof full, "%s", path); - std::fprintf(f, " %s the thread stacks to %s (attach it to the issue)\n", ok ? "wrote" : "could not write", - full); - } - } - } -#endif -} - -/// STRATA_TRACE=1: the VRAM left at a step of the startup (finds what fills the card after the cache is sized) -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; - vram_info(&free_b, &total_b); - std::fprintf(stderr, "strata trace: %lld MiB free after %s\n", (long long) (free_b >> 20), where); -} - -/// #463's A/B: STRATA_ADAPT_NOWAIT=1 lets a verify window start before the adaptive tier's copies have landed (0.1.37) -bool adapt_nowait() { - static const bool v = [] { const char* e = std::getenv("STRATA_ADAPT_NOWAIT"); return e && e[0] == '1'; }(); - return v; -} - -int argmax(const std::vector& v) { - int best = 0; - for (size_t i = 1; i < v.size(); ++i) - if (v[i] > v[best]) best = (int) i; - return best; -} - -// ---- --serve's conversation cache. A chat or an agent sends the whole conversation again with every request, and -// reading it again is what made a long session wait minutes for every turn. What a sequence leaves behind splits in -// two, and only one half needs copying: -// * POSITIONAL state - the KV cache of the 12 QSA layers and their pooled indexer keys, the draft layer's KV. A -// cell is written once for its position and read only by later positions (the block scores take `dead` for the -// block being filled, never its pooled row), so rewinding to a position just means writing from there again. -// * RUNNING state - the 36 GDN recurrences and conv histories, each QSA layer's indexer tail (the unfinished -// block's raw keys) and the PLE's normalized history. Each describes "everything so far" and cannot be -// rewound, so a checkpoint is a copy of exactly these: ~118 MB, the same set the verifier snapshots to roll -// back rejected drafts. -// A checkpoint is only valid while the positional cells below it still hold ITS tokens, so the serve loop keeps -// just the checkpoints that are prefixes of the tokens the session holds now. -using ImgKey = strata::core::ConversationImageKey; -using ConvCheckpoint = strata::core::ConversationCheckpoint; - -uint64_t fnv1a(const void* data, size_t n, uint64_t h = 1469598103934665603ull) { - const uint8_t* p = (const uint8_t*) data; - for (size_t i = 0; i < n; ++i) { h ^= p[i]; h *= 1099511628211ull; } - return h; -} - -using ConvStateSizes = strata::core::ConversationStateSizes; - -ConvStateSizes conv_state_sizes(const strata::core::ModelGeometry& g, const strata::core::SessionState& ss) { - ConvStateSizes z; - std::string error; - // a split stage's session owns only its layer range's state (see SessionState's carve note); the geometry - // and the carve have already passed engine validation - strata::core::conversation_session_sizes(g, ss, z, error); - return z; -} - -/// Copies the running state out (this session's carve only). The caller has synchronized the device. -bool checkpoint_save(ConvCheckpoint& c, const strata::core::SessionState& ss, const strata::core::ModelGeometry& g) { - std::string error; - if (strata::core::conversation_checkpoint_save(c, ss, g, error)) return true; - std::fprintf(stderr, "strata serve: checkpoint save: %s\n", error.c_str()); // the caller's ERR has no reason - return false; -} - -/// Puts a checkpoint's running state back; the positional cells below it are the caller's to guarantee. -bool checkpoint_restore(const ConvCheckpoint& c, strata::core::SessionState& ss, const strata::core::ModelGeometry& g) { - std::string error; - if (strata::core::conversation_checkpoint_restore(c, ss, g, error)) return true; - std::fprintf(stderr, "strata serve: checkpoint restore: %s\n", error.c_str()); - return false; -} - -// --control-vector-scaled: llama.cpp's `common_control_vector_load` (every file's `direction.` times its scale, -// summed; layer 0 has none) and `llama_adapter_cvec::apply` with the projection-mode patch (project: the unit -// direction and its norm as the scale), into the tables `cvec_upload` takes. `summary` is what INFO reports. -bool load_control_vectors(const Options& o, const strata::core::ModelGeometry& g, std::string& summary, std::string& err) { - const int64_t L = g.n_layers, N = g.n_embd; - std::vector data((size_t) (L * N), 0.0f); - std::vector have((size_t) L, false); - for (const auto& [path, scale] : o.cvec_files) { - try { - strata::GgufFile f(path); - const strata::MetaValue* arch = f.get("general.architecture"); - if (arch == nullptr || arch->s != "controlvector") { - err = path + ": not a control vector GGUF (general.architecture is not 'controlvector')"; - return false; - } - const strata::MetaValue* hint = f.get("controlvector.model_hint"); - if (hint != nullptr && hint->s != "qwen4exp") - std::fprintf(stderr, "strata generate: %s was made for '%s', not qwen4exp\n", path.c_str(), hint->s.c_str()); - int found = 0; - for (const strata::TensorInfo& t : f.tensors()) { - if (t.name.rfind("direction.", 0) != 0) continue; - const long l = std::strtol(t.name.c_str() + 10, nullptr, 10); - if (l < 1 || l >= L) continue; // layer 0 has no vector; past the model is ignored, as in llama.cpp - if (t.type != 0 || t.elements() != (uint64_t) N) { - err = path + ": " + t.name + " must be " + std::to_string((long long) N) + " f32"; - return false; - } - const float* src = reinterpret_cast(f.tensor_data(t)); - for (int64_t j = 0; j < N; ++j) data[(size_t) (l * N + j)] += scale * src[j]; - have[(size_t) l] = true; - ++found; - } - if (found == 0) { err = path + ": no direction. tensors"; return false; } - } catch (const std::exception& e) { - err = e.what(); - return false; - } - } - const int first = o.cvec_first <= 0 ? 1 : o.cvec_first; - const int last = (o.cvec_last <= 0 || o.cvec_last >= L) ? (int) L - 1 : o.cvec_last; - const int single = o.cvec_mode == 0 ? o.cvec_single : -1; - if (single >= 0 && (single >= L || !have[(size_t) single])) { - err = "--cvec-dir single:" + std::to_string(single) + ": the vector has no direction for that layer"; - return false; - } - std::vector dir((size_t) (L * N), 0.0f), s((size_t) L, 0.0f); - int steered = 0; - for (int64_t l = first; l <= last; ++l) { - const int64_t src = single >= 0 ? single : l; - if (!have[(size_t) src]) continue; - const float* d = data.data() + (size_t) (src * N); - if (o.cvec_mode == 0) { - double nrm = 0.0; - for (int64_t j = 0; j < N; ++j) nrm += (double) d[j] * d[j]; - nrm = std::sqrt(nrm); - if (nrm <= 0.0) continue; - s[(size_t) l] = (float) nrm; - for (int64_t j = 0; j < N; ++j) dir[(size_t) (l * N + j)] = (float) (d[j] / nrm); - } else { - s[(size_t) l] = 1.0f; - std::copy(d, d + N, dir.begin() + (size_t) (l * N)); - } - ++steered; - } - if (steered == 0) { err = "the control vector has no direction in layers " + std::to_string(first) + ".." + std::to_string(last); return false; } - if (!strata::kernels::cvec_upload(dir, s, o.cvec_mode, first, last, N, g.hc, err)) return false; - summary = std::string(o.cvec_mode == 0 ? "project" : "add") + ":" + std::to_string(first) + "-" + std::to_string(last) + - (single >= 0 ? ":single" + std::to_string(single) : ""); - // the line llama.cpp's patched build prints, so a log shows the same thing - std::fprintf(stderr, "strata generate: control vector mode = %s, dir = %s, layers %d..%d (%d steered)\n", - o.cvec_mode == 0 ? "project" : "add", single >= 0 ? "single" : "per-layer", first, last, steered); - return true; -} - -// The effective host->device bandwidth of the PCIe link: copies from pinned host memory, as the expert arena's -// reads are. The native default share (0.55) was measured on x16 links (~26-28 GB/s); a x8 card in a x8 slot -// carries about half of that. Returns < 0 when the probe cannot run (then the caller keeps the default). -// -// #485: a single timed burst read an x16 PCIe 4 link (RTX A3000 laptop) at 18.5, 6.9 and 5.8 GB/s in three starts - -// a link still in a low-power state, other DMA, a context not yet up to speed - and the low reading set the share. -// Such a disturbance only ever slows a copy: nothing makes a correctly timed copy faster than the link carries. So -// the same 1 GiB is now copied as four bursts of 256 MiB, timed one by one, and the fastest is the link's figure (the -// median would still follow a disturbance that lasts through half the bursts). Each burst takes ~10 ms on an x16 -// PCIe 4 link, so the probe takes no longer than the one 1 GiB burst did. `samples`, when given, gets every -// burst's reading for the log. -double probe_pcie_h2d_gbps(std::string* samples = nullptr) { - constexpr size_t kBytes = 256ull << 20; - constexpr int kBursts = 4; - void* h = nullptr; - void* d = nullptr; - if (cudaMallocHost(&h, kBytes) != cudaSuccess) return -1.0; - if (cudaMalloc(&d, kBytes) != cudaSuccess) { - cudaFreeHost(h); - return -1.0; - } - std::memset(h, 0, kBytes); // fault the pages in before timing - cudaMemcpyAsync(d, h, kBytes, cudaMemcpyHostToDevice); // warmup: context up, copy engine primed - float ms[kBursts] = {}; -#if defined(STRATA_USE_HIP) && defined(_WIN32) - // Windows HIP: the events do not bracket the copies there (an RX 6800 read 3,300-26,000 GB/s, so every link kept - // the x16 share), so each burst is timed on the host between two synchronizes: 256 MiB takes ~10 ms, so the - // synchronize around it hardly matters - bool ok = cudaDeviceSynchronize() == cudaSuccess; - for (int b = 0; b < kBursts && ok; ++b) { - const Clock::time_point t0 = Clock::now(); - cudaMemcpyAsync(d, h, kBytes, cudaMemcpyHostToDevice); - ok = cudaDeviceSynchronize() == cudaSuccess; - ms[b] = (float) std::chrono::duration(Clock::now() - t0).count(); - } -#else - // the bursts run back to back on the stream, an event between each two - cudaEvent_t ev[kBursts + 1]; - int n_ev = 0; - while (n_ev <= kBursts && cudaEventCreate(&ev[n_ev]) == cudaSuccess) ++n_ev; - bool ok = n_ev == kBursts + 1; - if (ok) { - cudaEventRecord(ev[0]); - for (int b = 0; b < kBursts; ++b) { - cudaMemcpyAsync(d, h, kBytes, cudaMemcpyHostToDevice); - cudaEventRecord(ev[b + 1]); - } - ok = cudaEventSynchronize(ev[kBursts]) == cudaSuccess; - for (int b = 0; b < kBursts && ok; ++b) ok = cudaEventElapsedTime(&ms[b], ev[b], ev[b + 1]) == cudaSuccess; - } - for (int i = 0; i < n_ev; ++i) cudaEventDestroy(ev[i]); -#endif - double bw = -1.0; - if (samples != nullptr) samples->clear(); - for (int b = 0; b < kBursts && ok; ++b) { - const double s = ms[b] > 0.01f ? (double) kBytes / (ms[b] * 1e-3) / 1e9 : -1.0; - bw = std::max(bw, s); - if (samples != nullptr) { - char buf[32]; - std::snprintf(buf, sizeof(buf), "%s%.1f", b == 0 ? "" : " ", s); - *samples += buf; - } - } - if (!ok) (void) cudaGetLastError(); - cudaFree(d); - cudaFreeHost(h); - return bw; -} - -// The PCIe share of the missed experts for a link measured at `gbps`: `base` (the share measured on x16 links) from -// 20 GB/s up, and below that in proportion to the bandwidth, so the time the link spends on its share stays about -// what the x16 share costs. Continuous (#485): before, 19.9 GB/s gave 0.42 and 20.0 the full 0.55 (and 4.0 GB/s -// gave 0.08, 3.9 none), so a reading near either edge moved the share by a quarter of its range. From 20 GB/s up -// (an x16 PCIe 4/5 link: ~26-28 GB/s) the share is unchanged. -double pcie_frac_for_gbps(double gbps, double base) { - return gbps <= 0.0 ? base : base * std::min(1.0, gbps / 20.0); -} - -} // namespace - -int main(int argc, char** argv) { - // **UNBUFFERED, BECAUSE THE INTERESTING OUTPUT IS THE OUTPUT BEFORE A CRASH.** `stdout` redirected to a - // pipe or a file is block-buffered, so a program that dies loses every line it had already printed - which - // turns "it crashed at step 7" into "it crashed somewhere", and the difference is a debugging session. - std::setvbuf(stdout, nullptr, _IONBF, 0); -#if (defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)) && !defined(_WIN32) - // AMD, a file-backed arena (STRATA_ARENA_MMAP): ROCclr copies a pageable source of 1 MiB or more by locking its - // pages in place (a GPU userptr), and keeps them - so every expert the VRAM fill copied from the mapped - // experts.bin stayed resident, the release of the VRAM-held ones was undone by the driver at once, and a - // 32 GB PC ran with ~0.3 GB free: the kernel swapped, and a turn's checkpoint took 25-80 s. Above this size - // ROCclr stages through its own pinned buffers instead; decode is unchanged (49.06 vs 49.16 ms/window). - if (std::getenv("STRATA_ARENA_MMAP") && std::getenv("STRATA_ARENA_MMAP")[0] == '1') - setenv("GPU_PINNED_MIN_XFER_SIZE", "1000000", 0); // MiB; an explicit setting wins -#endif - // Load every CUDA kernel when the context is created, before the expert cache takes the free VRAM. With the - // default lazy loading, a kernel first used mid-prompt (MMQ for IQ3_XXS at 64K+ on a 12 GB card) found no VRAM - // left for its code and the engine ended ("out of memory: cudaFuncSetAttribute"). Costs ~30 MB of VRAM. - if (std::getenv("CUDA_MODULE_LOADING") == nullptr) { -#if defined(_WIN32) - _putenv_s("CUDA_MODULE_LOADING", "EAGER"); -#else - setenv("CUDA_MODULE_LOADING", "EAGER", 0); -#endif - } - Options o; - bool have_tokens = false; - bool have_logits_stride = false; - for (int i = 1; i < argc; ++i) { - const std::string a = argv[i]; - auto next = [&](const char* what) -> const char* { - if (i + 1 >= argc) { std::fprintf(stderr, "%s needs a value\n", what); std::exit(2); } - return argv[++i]; - }; - bool parsed = true; - if (a == "--help" || a == "-h") { usage(); return 0; } - else if (a == "--pack") o.pack = next("--pack"); - else if (a == "--tokens") { - if (have_tokens) { std::fprintf(stderr, "supply one token input only\n"); return 2; } - std::string e; - if (!parse_i64_list(next("--tokens"), o.tokens, e)) { std::fprintf(stderr, "%s\n", e.c_str()); return 2; } - have_tokens = true; - } - else if (a == "--tokens-file") { - if (have_tokens) { std::fprintf(stderr, "supply one token input only\n"); return 2; } - std::ifstream input(next("--tokens-file")); - if (!input) { std::fprintf(stderr, "cannot open token file\n"); return 2; } - std::string text((std::istreambuf_iterator(input)), std::istreambuf_iterator()); - if (input.bad()) { std::fprintf(stderr, "cannot read token file\n"); return 2; } - std::string error; - if (text.find('\0') != std::string::npos || !parse_i64_list(text.c_str(), o.tokens, error)) { - std::fprintf(stderr, "malformed token file: %s\n", error.c_str()); return 2; - } - have_tokens = true; - } - else if (a == "--max-new") o.max_new = std::atoll(next("--max-new")); - else if (a == "--max-context") o.max_context = std::atoll(next("--max-context")); - else if (a == "--rope-scaling") o.rope_scaling = next("--rope-scaling"); - else if (a == "--rope-scale") o.rope_scale = std::atof(next("--rope-scale")); - else if (a == "--rope-freq-base") o.rope_freq_base = std::atof(next("--rope-freq-base")); - else if (a == "--rope-freq-scale") o.rope_freq_scale = std::atof(next("--rope-freq-scale")); - else if (a == "--yarn-orig-ctx") o.yarn_orig_ctx = std::atof(next("--yarn-orig-ctx")); - else if (a == "--yarn-ext-factor") o.yarn_ext_factor = std::atof(next("--yarn-ext-factor")); - else if (a == "--yarn-attn-factor") o.yarn_attn_factor = std::atof(next("--yarn-attn-factor")); - else if (a == "--yarn-beta-fast") o.yarn_beta_fast = std::atof(next("--yarn-beta-fast")); - else if (a == "--yarn-beta-slow") o.yarn_beta_slow = std::atof(next("--yarn-beta-slow")); - else if (a == "--greedy") o.greedy = true; - else if (a == "--seed") { o.seed = (uint64_t) std::atoll(next("--seed")); o.greedy = false; } - else if (a == "--top-k") o.top_k = std::atoi(next("--top-k")); - else if (a == "--top-p") o.top_p = (float) std::atof(next("--top-p")); - else if (a == "--temperature") o.temperature = (float) std::atof(next("--temperature")); - else if (a == "--dump-logits") o.dump_logits = next("--dump-logits"); - else if (a == "--logits-stride") { - if (have_logits_stride) { std::fprintf(stderr, "--logits-stride must be supplied only once\n"); return 2; } - if (!strata::program::logits_selection::parse_stride(next("--logits-stride"), o.logits_stride)) { - std::fprintf(stderr, "--logits-stride requires a positive decimal int64\n"); return 2; - } - have_logits_stride = true; - } - else if (a == "--dump-residual") o.dump_residual = next("--dump-residual"); - else if (a == "--dump-mixed") o.dump_mixed = next("--dump-mixed"); - else if (a == "--dump-layers") o.dump_layers = next("--dump-layers"); - else if (a == "--dump-halves") o.dump_halves = next("--dump-halves"); - else if (a == "--dump-routing") o.dump_routing = next("--dump-routing"); - else if (a == "--ple-gguf") o.ple_gguf = next("--ple-gguf"); - else if (a == "--no-ple") o.no_ple = true; - else if (a == "--ple-io") o.ple_io = next("--ple-io"); - else if (a == "--ple-row-cache") o.ple_row_cache = std::atoll(next("--ple-row-cache")); - else if (a == "--ple-inflight") o.ple_inflight = std::atoi(next("--ple-inflight")); - else if (a == "--ple-delay-us") o.ple_delay_us = std::atof(next("--ple-delay-us")); - else if (a == "--ple-sync-submit") o.ple_sync_submit = true; - else if (a == "--kv") o.kv = next("--kv"); - else if (a == "--kv-resident") o.kv_resident = std::atoll(next("--kv-resident")); - else if (a == "--stream-token") o.stream_token = true; - else if (a == "--check-logits") o.check_logits = true; - else if (a == "--gr-fp32-activations") o.gr_fp32_activations = true; - else if (a == "--gr-native-mmvf") o.gr_native_mmvf = true; - else if (a == "--native-bf16") o.native_bf16 = true; - else if (a == "--native-bf16-extra") o.native_bf16_extra = true; - else if (a == "--native-ple-key") o.native_ple_key = true; - else if (a == "--native-moe-combine") o.native_moe_combine = true; - else if (a == "--native-gdn") o.native_gdn = true; - else if (a == "--native-flash-attn-short") o.native_flash_attn_short = true; - else if (a == "--native-qsa-indexer") o.native_qsa_indexer = true; - else if (a == "--native-qsa") o.native_qsa = true; - else if (a == "--native-rope") o.native_rope = true; - else if (a == "--native-ple-postops") o.native_ple_postops = true; - else if (a == "--native-router") o.native_router = true; - else if (a == "--cpu-oracle-q8-0") o.cpu_oracle_q8_0 = true; - else if (a == "--native") o.native_preset = next("--native"); - else if (a == "--native-head-gguf") o.native_head_gguf = next("--native-head-gguf"); - else if (a == "--embd-gguf") o.embd_gguf = next("--embd-gguf"); - else if (a == "--native-dense-gguf") o.native_dense_gguf.push_back(next("--native-dense-gguf")); - else if (a == "--no-capture") o.no_capture = true; - else if (a == "--no-pool") o.no_pool = true; - else if (a == "--sync-every-layer") o.sync_every_layer = true; - else if (a == "--stage-timing") o.stage_timing = true; - else if (a == "--graph-only") o.graph_only = true; - else if (a == "--gpu-only-full") o.gpu_only_full = true; - else if (a == "--pool-workers") o.pool_workers = std::atoi(next("--pool-workers")); - else if (a == "--pool-affinity") { - const std::string v = next("--pool-affinity"); - if (v == "auto") o.pool_affinity = strata::kernels::cpu::PoolAffinity::Auto; - else if (v == "p-cores" || v == "pcores") o.pool_affinity = strata::kernels::cpu::PoolAffinity::PCores; - else if (v == "all") o.pool_affinity = strata::kernels::cpu::PoolAffinity::All; - else { - std::fprintf(stderr, "strata generate: unknown --pool-affinity value '%s' (expected auto, p-cores, or all)\n", v.c_str()); - return 2; - } - } - else if (a == "--no-host-worker") o.no_host_worker = true; - else if (a == "--no-ple-prefetch") o.no_ple_prefetch = true; - else if (a == "--coupled-draft") o.coupled_draft = true; - else if (a == "--no-coupled-draft") o.coupled_draft = false; - else parsed = false; - // The chain continues here in a second statement: one chain of 120+ `else if` passed MSVC's limit of 128 - // nested blocks (C1061). The order of the tests and what each does are unchanged. - if (!parsed) { - if (a == "--expert-cache") { - const std::string v = next("--expert-cache"); - o.expert_cache = (v == "auto") ? -1 : std::atoi(v.c_str()); - } - else if (a == "--expert-cache-device1" || a == "--expert-cache-device2" || a == "--expert-cache-device3") { - const size_t r = (size_t) (a.back() - '1'); - const std::string v = next(a.c_str()); - o.expert_cache_remote_auto[r] = v == "auto"; - o.expert_cache_remote[r] = v == "auto" ? std::numeric_limits::max() : std::atoi(v.c_str()); - } - else if (a == "--remote-expert-opt") o.remote_expert_opt = true; - 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; - // #282: auto:N (N = 16384 or 32768) or STRATA_PREFILL_AUTO_MAX lets auto take chunks above 8192 - const char* env_max = std::getenv("STRATA_PREFILL_AUTO_MAX"); - const long long want_max = v.rfind("auto:", 0) == 0 ? std::atoll(v.c_str() + 5) - : (o.prefill_auto && env_max != nullptr ? std::atoll(env_max) : 8192); - o.prefill_auto_max = want_max >= 32768 ? 32768 : want_max >= 16384 ? 16384 : 8192; - o.prefill_chunk = o.prefill_auto ? o.prefill_auto_max : std::atoll(v.c_str()); - } - else if (a == "--no-split-rows") o.no_split_rows = true; - else if (a == "--no-prefill-borrow") o.no_prefill_borrow = true; - else if (a == "--vram-elastic") o.vram_elastic = true; - else if (a == "--vram-segment-mib") o.vram_segment_mib = std::atoll(next("--vram-segment-mib")); - else if (a == "--prefill-until") o.prefill_until = std::atoll(next("--prefill-until")); - else if (a == "--dump-final-r") o.dump_final_r = next("--dump-final-r"); - else if (a == "--spec") o.spec = std::atoi(next("--spec")); - else if (a == "--batch") o.batch = std::atoi(next("--batch")); - else if (a == "--slots") o.batch = std::atoi(next("--slots")); // the same as --batch - 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")); - else if (a == "--pcie-frac") o.pcie_frac = std::atof(next("--pcie-frac")); - else if (a == "--adapt-every") o.adapt_every = std::atoi(next("--adapt-every")); - else if (a == "--adapt-decay") o.adapt_decay = (float) std::atof(next("--adapt-decay")); - else if (a == "--spec-min-p") o.spec_min_p = std::atof(next("--spec-min-p")); - else if (a == "--stop-eos") o.stop_eos = true; - else if (a == "--spec-split") o.spec_split = true; - else if (a == "--layer-split") o.layer_split = next("--layer-split"); - else if (a == "--split-device") o.split_device = next("--split-device"); - else if (a == "--split-skip-if-fits") o.split_skip_if_fits = true; - else if (a == "--pcie-mode") o.pcie_mode = next("--pcie-mode"); - else if (a == "--serve") o.serve = true; - else if (a == "--vision") o.vision = true; - else if (a == "--prompt-cache") o.prompt_cache = std::max(0, std::atoi(next("--prompt-cache"))); - else if (a == "--conversation-cache-mib" || a == "--conversation-cache-slots" || - a == "--conversation-cache-min-free-mib") { - const std::string value = next(a.c_str()); - int64_t number = 0; - const auto result = std::from_chars(value.data(), value.data() + value.size(), number); - const int64_t limit = a == "--conversation-cache-slots" ? INT32_MAX : INT64_MAX / (1024 * 1024); - if (result.ec != std::errc{} || result.ptr != value.data() + value.size() || number < 0 || number > limit) { - std::fprintf(stderr, "%s needs a nonnegative integer within range\n", a.c_str()); - return 2; - } - if (a == "--conversation-cache-mib") o.conversation_cache_mib = number; - else if (a == "--conversation-cache-min-free-mib") o.conversation_cache_min_free_mib = number; - else o.conversation_cache_slots = (int) number; - } - else if (a == "--prompt-cache-every") o.prompt_cache_every = std::max(0LL, std::atoll(next("--prompt-cache-every"))); - else if (a == "--prompt-cache-root") o.prompt_cache_root = std::max(0LL, std::atoll(next("--prompt-cache-root"))); - else if (a == "--turn-token") o.turn_token = std::atoll(next("--turn-token")); - else if (a == "--tail-role-token") o.tail_role_token = std::atoll(next("--tail-role-token")); - else if (a == "--short-read") o.short_read = std::max(0LL, std::atoll(next("--short-read"))); - else if (a == "--suffix-draft") o.suffix_draft = std::max(0, std::atoi(next("--suffix-draft"))); - else if (a == "--mtp-max-t") o.mtp_max_t = std::max(0, std::atoi(next("--mtp-max-t"))); - else if (a == "--control-vector") o.cvec_files.push_back({next("--control-vector"), 1.0f}); - else if (a == "--control-vector-scaled") { - // FILE:SCALE, comma-separated; the LAST colon splits, so a Windows path (C:\...) keeps its drive - std::stringstream list(next("--control-vector-scaled")); - std::string item; - while (std::getline(list, item, ',')) { - const size_t colon = item.rfind(':'); - char* end = nullptr; - const float sc = colon == std::string::npos ? 0.0f : std::strtof(item.c_str() + colon + 1, &end); - if (colon == std::string::npos || colon == 0 || end == item.c_str() + colon + 1 || *end != '\0') { - std::fprintf(stderr, "--control-vector-scaled: expected FILE:SCALE, got '%s'\n", item.c_str()); - return 2; - } - o.cvec_files.push_back({item.substr(0, colon), sc}); - } - } - else if (a == "--control-vector-layer-range") { - o.cvec_first = std::atoi(next("--control-vector-layer-range")); - o.cvec_last = std::atoi(next("--control-vector-layer-range")); - } - else if (a == "--cvec-mode") { - const std::string m = next("--cvec-mode"); - if (m == "project") o.cvec_mode = 0; - else if (m == "add") o.cvec_mode = 1; - else { std::fprintf(stderr, "--cvec-mode: add or project, got '%s'\n", m.c_str()); return 2; } - } - else if (a == "--cvec-dir") { - const std::string d = next("--cvec-dir"); - if (d == "per-layer") o.cvec_single = -1; - else if (d.rfind("single:", 0) == 0) o.cvec_single = std::atoi(d.c_str() + 7); - else { std::fprintf(stderr, "--cvec-dir: per-layer or single:L, got '%s'\n", d.c_str()); return 2; } - } - else if (a == "--no-spec-split") o.spec_split = false; - else if (a == "--eos-ids") { - std::string e; - if (!parse_i64_list(next("--eos-ids"), o.eos_ids, e)) { std::fprintf(stderr, "--eos-ids: %s\n", e.c_str()); return 2; } - o.stop_eos = true; - } - else if (a == "--adapt-swaps") o.adapt_swaps = std::atoi(next("--adapt-swaps")); - else if (a == "--expert-cache-cpu-order") o.expert_cache_cpu_order = true; - else if (a == "--expert-cache-per-layer") o.expert_cache_per_layer = true; - else if (a == "--peer-device") o.peer_device = std::atoi(next("--peer-device")); - else if (a == "--peer-reserve-mib") o.peer_reserve_mib = std::atoi(next("--peer-reserve-mib")); - else if (a == "--peer-slots") o.peer_slots = std::atoll(next("--peer-slots")); - else if (a == "--peer-adapt-swaps") o.peer_adapt_swaps = std::atoi(next("--peer-adapt-swaps")); - else if (a == "--peer-prefill-rows") o.peer_prefill_rows = std::atoll(next("--peer-prefill-rows")); - else if (a == "--no-hit-poke") o.no_hit_poke = true; - else if (a == "--expert-profile") o.expert_profile = next("--expert-profile"); - else if (a == "--expert-profile-save") o.expert_profile_save = next("--expert-profile-save"); - else if (a == "--expert-profile-save-every") - o.expert_profile_save_min = std::atof(next("--expert-profile-save-every")); - else if (a == "--gpu-stages") o.gpu_stages = true; - else if (a == "--mmap-experts") o.mmap_experts = true; - else if (a == "--shared-expert-arena") o.shared_expert_arena = next("--shared-expert-arena"); - else if (a == "--resident-cpu-experts") o.resident_cpu_experts = o.resident_cpu_explicit = true; - else if (a == "--resident-experts") { - o.mmap_experts = o.resident_cpu_experts = o.resident_pin = o.resident_soft = true; - o.resident_headroom = 4ull << 30; - // A/B arms: STRATA_RESIDENT_PIN=0 keeps the copy pageable (the --resident-cpu-experts form); - // STRATA_RESIDENT_HEADROOM_GIB=N leaves N GiB of the available RAM free instead of 4 - if (const char* v = std::getenv("STRATA_RESIDENT_PIN"); v != nullptr && std::string(v) == "0") - o.resident_pin = false; - if (const char* v = std::getenv("STRATA_RESIDENT_HEADROOM_GIB"); v != nullptr && std::atof(v) >= 0.0) - o.resident_headroom = (uint64_t) (std::atof(v) * 1073741824.0); - } - else if (a == "--resident-budget-gib") { - const double gib = std::atof(next("--resident-budget-gib")); - if (!(gib > 0.0)) { std::fprintf(stderr, "strata generate: --resident-budget-gib needs N > 0\n"); return 2; } - o.resident_budget = (uint64_t) (gib * 1073741824.0); - o.mmap_experts = o.resident_cpu_experts = o.resident_pin = true; - o.resident_headroom = 4ull << 30; - if (const char* v = std::getenv("STRATA_RESIDENT_PIN"); v != nullptr && std::string(v) == "0") - o.resident_pin = false; - if (const char* v = std::getenv("STRATA_RESIDENT_HEADROOM_GIB"); v != nullptr && std::atof(v) >= 0.0) - o.resident_headroom = (uint64_t) (std::atof(v) * 1073741824.0); - } - else if (a == "--stats") o.stats = true; - else if (a == "--shared-late") o.shared_late = true; - else if (a == "--keep-canonical") o.keep_canonical = true; - else if (a == "--no-token-graph") o.no_token_graph = true; - else if (a == "--no-fused-gr") o.no_fused_gr = true; - else if (a == "--no-fast-attn") o.no_fast_attn = true; - else if (a == "--no-publish-kernel") o.no_publish_kernel = true; - else if (a == "--no-fused-gdn") o.no_fused_gdn = true; - else if (a == "--no-fast-select") o.no_fast_select = true; - else { - // An unknown flag is an ERROR and not a warning: a typo'd `--max-neww` that silently generated 16 - // tokens would look like a working run. - std::fprintf(stderr, "unknown argument: %s\n", a.c_str()); - usage(); - return 2; - } - } - } - strata::core::set_coupled_draft(o.coupled_draft); - strata::core::set_peer_portable(o.peer_device >= 1); // multi-GPU: the Portable flag on mapped host buffers only with a peer device (before any allocation) - if (o.serve && o.conversation_cache_mib > 0 && (o.prompt_cache == 0 || o.conversation_cache_slots == 0)) - std::fprintf(stderr, "strata serve: warning: conversation caching is disabled by %s\n", - o.prompt_cache == 0 ? "--prompt-cache 0" : "--conversation-cache-slots 0"); - // parking with --layer-split saves every stage (SavedConversation::stage_images) - // Layer split (multi-GPU): the later stages run layers [K_i, K_i+1) on their own GPUs (--split-device, default - // the next visible ones); "auto" places the K from each GPU's free VRAM once the weights are in (below). KV - // streaming and images (the server's GPU encoder) run across a split, also with parking and --batch. Across - // GPUs, not yet: control vectors, the helper caches (--expert-cache-remote), and lending cache slots to the - // prompt path (each stage's prompt path has its own buffers). - // --pcie-frac given: that one share is every stage's (the stages' own link probes are skipped), so a split over - // a fast and a slow link cannot set the two apart from the command line (#485) - const bool pcie_given = o.pcie_frac >= 0.0; - std::vector split_at; - std::vector split_devs; - bool split_auto = false, split_same = false; - if (!o.layer_split.empty()) { - int n_dev = 1; - if (cudaGetDeviceCount(&n_dev) != cudaSuccess || n_dev < 1) n_dev = 1; - cudaGetLastError(); - auto ints = [](const std::string& str, auto& out) -> bool { - using V = typename std::decay_t::value_type; - size_t a = 0; - while (a < str.size()) { - size_t b = str.find(',', a); - if (b == std::string::npos) b = str.size(); - const std::string t = str.substr(a, b - a); - if (t.empty() || t.find_first_not_of("0123456789") != std::string::npos) return false; - out.push_back((V) std::atoll(t.c_str())); - a = b + 1; - } - return !out.empty(); - }; - split_auto = o.layer_split == "auto"; - bool ok = o.serve && (split_auto || ints(o.layer_split, split_at)); - if (ok && !o.split_device.empty()) ok = ints(o.split_device, split_devs); - else if (ok) - for (int d = 1; d < n_dev && (split_auto || split_devs.size() < split_at.size()); ++d) split_devs.push_back(d); - if (ok && !split_auto && split_devs.empty() && split_at.size() == 1) split_devs.push_back(0); // one GPU - split_same = ok && split_devs.size() == 1 && split_devs[0] == 0 && !split_auto; - if (split_same && o.conversation_cache_mib > 0 && o.conversation_cache_slots > 0 && o.prompt_cache > 0) { - std::fprintf(stderr, "strata serve: conversation parking does not support a layer split on one GPU " - "(--split-device 0); disable parking with --conversation-cache-mib 0\n"); - return 2; - } - if (ok && split_auto && split_devs.empty()) { - std::fprintf(stderr, "strata generate: --layer-split auto: one GPU visible, so no split\n"); - o.layer_split.clear(); - split_auto = false; - } else if (ok) { - ok = (split_auto || split_at.size() == split_devs.size()) && split_devs.size() < (size_t) SplitDrive::kMax; - for (size_t i = 0; ok && i < split_at.size(); ++i) ok = split_at[i] >= 2 && (i == 0 || split_at[i] > split_at[i - 1]); - for (size_t i = 0; ok && !split_same && i < split_devs.size(); ++i) { - ok = split_devs[i] > 0 && split_devs[i] < n_dev; - for (size_t j = 0; ok && j < i; ++j) ok = split_devs[i] != split_devs[j]; - } - } - if (!ok) { - std::fprintf(stderr, "strata generate: --layer-split K[,K2..]|auto needs --serve, rising K from 2, and one " - "distinct GPU per K in --split-device (1..%d; or 0 with one K: the same GPU). K is the " - "FIRST LAYER of each later GPU, not a count of layers per card: \"24,36,42\" for 4 " - "GPUs, not \"24,12,6,6\" (got \"%s\")\n", n_dev - 1, o.layer_split.c_str()); - return 2; - } - } - bool multi_gpu = !split_devs.empty() && !split_same; // cleared by --split-skip-if-fits before any stage loads - bool split_own_auto = false; // #340: the split keeps own prompt buffers by its rule (not --no-prefill-borrow) - if (o.mmap_experts && !o.shared_expert_arena.empty()) { - std::fprintf(stderr, "strata generate: --shared-expert-arena backs the resident arena and cannot be used with --mmap-experts\n"); - return 2; - } - if (o.resident_cpu_experts && (!o.mmap_experts || o.expert_profile.empty())) { - std::fprintf(stderr, "strata generate: --resident-cpu-experts requires --mmap-experts and a static --expert-profile\n"); - return 2; - } - const bool remote_caches = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 || - o.expert_cache_remote[2] > 0; - if (o.resident_cpu_experts && !o.layer_split.empty() && !remote_caches && o.resident_soft && - !o.resident_cpu_explicit && o.resident_budget == 0) { - // #364 #384: setup's --resident-experts with a layer split (--gpus at start, or a config edited by hand) runs - // as the plain mmap mode - the placement those users measured 1.3-1.6x faster than one GPU - instead of - // refusing. Exactly --mmap-experts: nothing else reads these flags (the headroom only sizes the copy). - std::fprintf(stderr, "strata generate: WARNING: the resident RAM mode (--resident-experts) does not support a " - "layer split yet: the experts the GPUs do not hold are read through the OS file cache " - "(--mmap-experts), and RAM may fill up during long prompts\n"); - o.resident_cpu_experts = o.resident_pin = o.resident_soft = false; - o.resident_headroom = 8ull << 30; - } - if (o.resident_cpu_experts && (!o.layer_split.empty() || remote_caches)) { - std::fprintf(stderr, "strata generate: --resident-cpu-experts does not support layer splits or remote expert caches\n"); - return 2; - } - // the helper-GPU expert caches (--expert-cache-remote, docs/SECOND_GPU.md): CUDA1..3 on one GPU; with a layer - // split, the visible GPUs no stage runs on, in order - int remote_dev[3] = {1, 2, 3}; - if (multi_gpu) { - if (o.expert_profile.empty()) { - std::fprintf(stderr, "strata generate: a layer split across GPUs needs --expert-profile\n"); - return 2; - } - // A STAGE'S PROMPT PATH BORROWS FROM THAT STAGE'S OWN EXPERT CACHE. This used to set - // `no_prefill_borrow = true` - "each stage's prompt path has its own buffers" - which is true, but it is - // a reason to give each stage its own LOAN, not a reason to make every stage withhold a chunk-sized - // reserve from its cache for the whole session. Forced on, it also collapsed `--prefill auto` to 2048 - // (below) and skipped the lend arm, so a stage paid for its prompt buffers twice over: once in VRAM it - // never got back, once in the smaller chunk. At `--prefill 5524` that reserve is 3.8 GiB per stage, - // more than either 8 GB card had - which is how adding two GPUs to the two 12 GB ones lost 260K. - // The loan is the tail of the stage's own cache (see `PfPart` in the serve block); outside the prompt - // that tail is expert cache, so a large chunk costs a stage nothing permanent. - // #340 - BUT A LOAN IS NOT FREE PER REQUEST: every stage streams the lent experts during the prompt and - // copies them back after it, so on cards that hold (nearly) every expert of their layers a 2K prompt read - // 37% slower than 0.1.29's own buffers (2x RX 9070 XT / R9700: 1570 -> 990 tok/s; 2x A5000 in #340: -35%). - // So a split keeps 0.1.29's own buffers (2048-token chunks, priced into the split search) when they are a - // small part of every card - at most 12% of its VRAM (16 GB and larger cards) - and borrows on smaller cards, - // where the reserve would cost the cache (and the context) the paragraph above is about. Measured with own - // buffers on the 9070 XT + R9700: 2K 1588 tok/s, 16K 2006 (0.1.29 1568 / 1935, 0.1.31 993 / 1852). - // OPT-IN (the owner's choice for 0.1.32): own buffers change which experts a full card keeps resident, so the - // split's output differs from 0.1.31's; the default borrows as 0.1.31 did - with the concurrent refill and the - // 96-blob split ring that alone gave 2K +27%, 16K +5% over 0.1.31, decode unchanged, output identical. - // STRATA_SPLIT_OWN=auto: the 12% rule above; 1: own buffers on any cards; unset/0: borrow. - // --split-skip-if-fits keeps the loans (it can fall back to one GPU, which must stay as it is). - const char* own_env = std::getenv("STRATA_SPLIT_OWN"); - if (!o.no_prefill_borrow && !o.split_skip_if_fits && own_env != nullptr && own_env[0] != '0') { - const char* v = std::string(own_env) == "auto" ? nullptr : own_env; - bool own = v ? v[0] == '1' : true; - // the buffers of a 2048-token chunk (or the --prefill one) + a 96-blob ring (as split_pf_mib prices them) - const int64_t own_chunk = o.prefill_auto || o.prefill_chunk <= 0 ? 2048 : o.prefill_chunk; - const int64_t reserve_mib = 160 + (own_chunk * 680) / 1024 + 96 * 4; - std::string why; - if (!v) { - std::vector devs = {0}; - for (const int d : split_devs) devs.push_back(d); - for (const int d : devs) { - cudaDeviceProp prop{}; - if (cudaGetDeviceProperties(&prop, d) != cudaSuccess) { cudaGetLastError(); own = false; break; } - const int64_t total_mib = (int64_t) (prop.totalGlobalMem >> 20); - if (reserve_mib * 100 > 12 * total_mib) { - own = false; - why = "CUDA" + std::to_string(d) + " has " + std::to_string(total_mib) + " MiB"; - break; - } - } - } - if (own) { - o.no_prefill_borrow = true; - split_own_auto = true; - std::fprintf(stderr, "strata generate: layer split: every stage keeps its own prompt buffers (~%lld MiB " - "each, %lld-token chunks)%s\n", (long long) reserve_mib, (long long) own_chunk, - v ? " (STRATA_SPLIT_OWN=1)" : ""); - } else if (!why.empty()) { - std::fprintf(stderr, "strata generate: layer split: the prompt paths borrow from the caches (%s)\n", - why.c_str()); - } - } - int n_vis = 1; - if (cudaGetDeviceCount(&n_vis) != cudaSuccess || n_vis < 1) n_vis = 1; - cudaGetLastError(); - int next_free = 1; - for (int r = 0; r < 3; ++r) { - if (o.expert_cache_remote[(size_t) r] <= 0) continue; - while (next_free < n_vis && - std::find(split_devs.begin(), split_devs.end(), next_free) != split_devs.end()) ++next_free; - if (next_free >= n_vis) { - std::fprintf(stderr, "strata generate: --expert-cache-remote with a layer split needs a GPU that runs no " - "stage (%d visible, %zu used by the split)\n", n_vis, split_devs.size() + 1); - return 2; - } - remote_dev[r] = next_free++; - } - std::string devs; - for (const int d : split_devs) devs += (devs.empty() ? "" : ",") + std::to_string(d); - std::fprintf(stderr, "strata generate: layer split across %zu GPUs: CUDA0, then CUDA%s (split %s)\n", - split_devs.size() + 1, devs.c_str(), o.layer_split.c_str()); - } -#if defined(STRATA_USE_HIP) - { - // every GPU this run uses must be an architecture the binary has code for (a gfx1100 build on a gfx1201 - // card would otherwise fail later with "invalid device function") - std::vector used{0}; - if (multi_gpu) used.insert(used.end(), split_devs.begin(), split_devs.end()); - for (int r = 0; r < 3; ++r) - if (o.expert_cache_remote[(size_t) r] > 0) used.push_back(remote_dev[r]); - for (const int d : used) { - if (const std::string why = strata::core::gpu_arch_problem(d); !why.empty()) { - std::fprintf(stderr, "strata generate: %s\n", why.c_str()); - return 1; - } - } - } -#endif - if (o.prefill_auto && (o.no_prefill_borrow || o.expert_profile.empty())) { - o.prefill_auto = false; // nothing to lend from: the buffers are reserved for the session, so keep them small - o.prefill_chunk = 2048; - } - if (!have_tokens && o.serve) { // plan v0.3 P8: requests bring their own tokens - o.tokens = {248045}; - o.max_new = 1; - have_tokens = true; - o.stop_eos = true; - } - if (!have_tokens) { - std::fprintf(stderr, "strata generate: --tokens is required (this build has no tokenizer; see the " - "header of src/program/generate.cpp)\n"); - usage(); - return 2; - } - - if ((o.ple_io != "direct" && o.ple_io != "mmap" && o.ple_io != "ram") || o.ple_row_cache < 0 || o.ple_inflight < 1 || - o.ple_inflight > 1024 || !(o.ple_delay_us >= 0)) { - std::fprintf(stderr, "strata generate: invalid --ple-io/--ple-row-cache/--ple-inflight/--ple-delay-us\n"); - return 2; - } -#if defined(_WIN32) - if (o.ple_io == "ram") { - std::fprintf(stderr, "strata generate: --ple-io ram is not available on Windows (no mlock); use --ple-io mmap\n"); - return 2; - } -#endif - if (o.kv == "q4") o.kv = "q4_0"; - if (o.kv != "fp16" && o.kv != "int8" && o.kv != "q4_0" && o.kv != "k8v4") { - std::fprintf(stderr, "strata generate: --kv must be fp16, int8, q4_0 or k8v4\n"); - return 2; - } - strata::core::qsa_set_kv_int8(o.kv == "int8"); - strata::core::qsa_set_kv_q4(o.kv == "q4_0"); // PR #21: 4-bit codes after a Hadamard rotation (kv_q4.hpp) - // STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation --kv q4_0 already uses. Opt-in: first-token KL to - // fp16 K/V improved on an NVFP4 pack (0.0066 -> 0.0051) but not on IQ2_XS (0.0022 -> 0.0054) - const char* kv_rot = std::getenv("STRATA_KV_ROT"); - strata::core::qsa_set_kv_int8_rotate(kv_rot != nullptr && kv_rot[0] == '1'); - if (kv_rot != nullptr && kv_rot[0] == '1' && o.kv == "int8") - std::fprintf(stderr, "strata generate: STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation (opt-in)\n"); - strata::core::qsa_set_kv_hybrid(o.kv == "k8v4"); // K8V4: INT8 K + rotated Q4_0 V, 816 B/cell - if (o.kv_resident < 0) { - std::fprintf(stderr, "strata generate: --kv-resident must be >= 0\n"); - return 2; - } - if (o.kv == "k8v4" && o.kv_resident > 0) { - std::fprintf(stderr, "strata generate: --kv k8v4 does not support --kv-resident streaming (yet)\n"); - return 2; - } - strata::core::qsa_set_kv_resident(o.kv_resident); - // Prompt lookup (the suffix drafter, on by default): the MTP keeps its --spec windows and a lookup window may be - // up to 2 tokens longer; the draft policy (strata/spec/draft_policy.hpp) takes one only where it pays. Code - // edits +6-11%, ordinary text unchanged (bench/results/2026-09-27-spec). --suffix-draft 0 turns it off. - if (o.suffix_draft > 0 && o.spec >= 2 && o.mtp_max_t == 0) { - o.mtp_max_t = o.spec; - o.spec = std::min(o.spec + 2, 8); // kVerifyMaxT - } - strata::core::layer_set_shared_early(!o.shared_late); - if (!o.native_preset.empty()) { - try { - // every shard of the model (-0000N-of-0000M.gguf beside --native). A missing shard is an error - // here: it used to be skipped, leaving a model with some tensors absent and a later error, or none. - o.native_shards = strata::gguf_split_paths(o.native_preset); - // --ple-gguf defaults to the shard that holds the PLE table, found by name: shard 2 of the ISTA files - // and of Unsloth's UD-Q4_K_XL, shard 1 of Swift's - if (o.ple_gguf.empty() && !o.no_ple) { - const strata::GgufModel model(o.native_shards); - size_t at = 0; - if (model.find("per_layer_token_embd.weight", &at) != nullptr) o.ple_gguf = o.native_shards[at]; - } - } catch (const std::exception& e) { - std::fprintf(stderr, "strata generate: --native %s: %s\n", o.native_preset.c_str(), e.what()); - return 2; - } - // 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; - } - o.stream_token = true; - o.gr_native_mmvf = true; - o.native_bf16 = o.native_bf16_extra = 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 (-0000N-of-0000M.gguf beside --native), then the PLE shard: a split - // may put any layer in any shard (Swift's GGUFs: layers 13-47 in shard 2, the PLE table in shard 1) - o.native_dense_gguf = o.native_shards; - // a PLE-only table (tools/ple_fp8_pack.py: architecture strata-ple) holds no projections - bool ple_only = false; - try { - 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 && !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); - } - // Plan v0.3 (24 Sep): the CPU experts stay on the VNNI kernel. The llama.cpp-CPU-exact q8_0 contract - // cost 27.0 vs 17.2 ms/token of pool time and G-C does not need it; `--cpu-oracle-q8-0` still selects it. - } - if (o.logits_stride > 1 && (o.max_new != 1 || o.dump_logits.empty())) { - 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; - } - if (o.native_ple_postops && o.no_ple) { - std::fprintf(stderr, "strata generate: --native-ple-postops requires PLE enabled\n"); - return 2; - } - if (!o.no_ple && o.ple_gguf.empty()) { - std::fprintf(stderr, "strata generate: --ple-gguf is required; --no-ple explicitly enables a diagnostic ablation\n"); - return 2; - } - // P7 audit: positions, cells and pooled-block indices are cast to int32 on the device path. - if (o.max_context > 2147483647LL - 8) { - std::fprintf(stderr, "strata generate: --max-context must be below 2^31\n"); - return 2; - } - if (o.max_new <= 0 || o.max_context <= 0 || o.max_new > o.max_context || - o.tokens.size() > (size_t) (o.max_context - o.max_new)) { - std::fprintf(stderr, "strata generate: positive --max-new and --max-context must fit the prompt and generation\n"); - return 2; - } - // THE ROPE KNOBS (rope_scaling.hpp). Anything invalid dies here, at second zero, rather than becoming a - // NaN angle inside one of the twelve QSA layers. Only the RANGES are checked - the config itself is - // resolved after the model file has had its say, right before session_init. - strata::kernels::RopeScaling rope_cfg; // type filled here; the rest at the resolution below - { - using RST = strata::kernels::RopeScalingType; - // an absent --rope-scaling (the empty default) leaves the type to the model file's rope keys, - // resolved below; anything present must be one of the three names - if (o.rope_scaling == "none") rope_cfg.type = RST::None; - else if (o.rope_scaling == "linear") rope_cfg.type = RST::Linear; - else if (o.rope_scaling == "yarn") rope_cfg.type = RST::YaRN; - else if (!o.rope_scaling.empty()) { - std::fprintf(stderr, "strata generate: --rope-scaling must be none, linear or yarn (got '%s')\n", - o.rope_scaling.c_str()); - return 2; - } - // every knob FINITE first: `atof("nan")` is NaN, and a NaN passes every range comparison below - for (const double v : {o.rope_scale, o.rope_freq_base, o.rope_freq_scale, o.yarn_orig_ctx, o.yarn_ext_factor, - o.yarn_attn_factor, o.yarn_beta_fast, o.yarn_beta_slow}) - if (!std::isfinite(v)) { - std::fprintf(stderr, "strata generate: a rope scaling knob is not a finite number (%g)\n", v); - return 2; - } - // 0 is the absent default; an explicit factor must extend, not shrink - if (o.rope_scale != 0 && o.rope_scale < 1.0) { - std::fprintf(stderr, "strata generate: --rope-scale %g must be >= 1 (it extends the context, not shrinks it)\n", - o.rope_scale); - return 2; - } - if (o.rope_freq_base != 0 && o.rope_freq_base <= 1.0) { - std::fprintf(stderr, "strata generate: --rope-freq-base must be a base above 1 (0 = the model's)\n"); - return 2; - } - if (o.rope_freq_scale < 0 || o.yarn_orig_ctx < 0 || o.yarn_ext_factor < -1.0 || o.yarn_attn_factor <= 0 || - o.yarn_beta_fast <= 0 || o.yarn_beta_slow <= 0) { - std::fprintf(stderr, "strata generate: invalid rope scaling knob (see usage: --yarn-ext-factor <0 = auto, " - "--yarn-orig-ctx 0 = default, the rest positive)\n"); - return 2; - } - } - if (!std::isfinite(o.temperature) || o.temperature < 0 || !std::isfinite(o.top_p) || - o.top_p <= 0 || o.top_p > 1 || o.top_k < 0 || o.expert_cache < -1 || - o.pool_workers < 0 || std::any_of(o.expert_cache_remote.begin(), o.expert_cache_remote.end(), - [](int slots) { return slots < 0; }) || - (o.expert_cache_remote[1] > 0 && o.expert_cache_remote[0] == 0) || - (o.expert_cache_remote[2] > 0 && o.expert_cache_remote[1] == 0)) { - std::fprintf(stderr, "strata generate: invalid sampling or resource parameter\n"); - return 2; - } - if (o.expert_cache_remote_placement != "stripe" && o.expert_cache_remote_placement != "layer") { - std::fprintf(stderr, "strata generate: --expert-cache-remote-placement must be stripe or layer\n"); - return 2; - } - if (o.remote_expert_opt && !o.serve) { - std::fprintf(stderr, "strata generate: --remote-expert-opt requires --serve\n"); - return 2; - } - // the peer tier is the second card's only user: a layer split or a remote expert cache would put a second engine - // part (and a second copy of the same experts) on it - if (o.peer_device >= 1 && (!o.layer_split.empty() || o.expert_cache_remote[0] > 0)) { - std::fprintf(stderr, "strata generate: --peer-device cannot be combined with %s\n", - !o.layer_split.empty() ? "--layer-split (use one or the other)" - : "--expert-cache-device1..3 (the peer tier already caches experts there)"); - return 2; - } - - if (o.native_flash_attn_short && o.max_context > 256) { - std::fprintf(stderr, "strata generate: --native-flash-attn-short requires --max-context <=256\n"); - return 2; - } - if (o.native_flash_attn_short && (o.gpu_only_full || o.graph_only || o.gpu_stages)) { - std::fprintf(stderr, "strata generate: --native-flash-attn-short requires the normal decode loop for status validation\n"); - return 2; - } - // The whole-model graph measurements replay every layer through CUDA0's session, which a layer split carves to - // CUDA0's own range - the answer would read another stage's state. Refused here rather than at the call, so - // the reason is visible before 55 GB is loaded. - if (multi_gpu && (o.gpu_only_full || o.gpu_stages)) { - std::fprintf(stderr, "strata generate: --gpu-only-full and --gpu-stages replay the whole model through one " - "session, which a layer split does not have; run them without --layer-split\n"); - return 2; - } - if (!o.native_head_gguf.empty()) { - try { - o.native_head_shards = o.native_head_gguf == o.native_preset ? o.native_shards - : strata::gguf_split_paths(o.native_head_gguf); - } catch (const std::exception& e) { - std::fprintf(stderr, "strata generate: --native-head-gguf %s: %s\n", o.native_head_gguf.c_str(), e.what()); - return 2; - } - } - if (o.native_ple_key && (o.native_dense_gguf.empty() || o.no_ple)) { - std::fprintf(stderr, "strata generate: --native-ple-key requires PLE and --native-dense-gguf\n"); - return 2; - } - if (o.cpu_oracle_q8_0 && (o.expert_cache != 0 || !o.expert_profile.empty())) { - std::fprintf(stderr, "strata generate: --cpu-oracle-q8-0 cannot be combined with --expert-cache or --expert-profile until the GPU expert contract matches\n"); - return 2; - } - - // **BEFORE ANYTHING ELSE.** The CPU expert kernel is AVX-512 (VNNI + VBMI) and its translation unit is - // compiled `/arch:AVX512`, so on a CPU without those features it does not fail - it executes an illegal - // instruction at some unpredictable token. Refusing at second zero is the whole point of P2.S3's check. - strata::kernels::cpu::expert_set_oracle_q8_0(o.cpu_oracle_q8_0); - // ... and nothing runs on a CPU without AVX2: every CPU expert kernel is AVX2 at least (the AVX-512 ones are - // chosen above it), and so is ggml-cpu in the release build, which the native pack's layout load initializes - // next. Refused here, by name, rather than an illegal instruction in the first expert. - // The experimental older-CPU build (STRATA_ISA_FLOOR=avx|none, compiled on that PC; #394 #595 #623) has ggml-cpu - // for that floor, so a native pack's experts run there on ggml-cpu (every AVX2 kernel is behind cpu_avx2_ok). - const char* isa_floor = strata::kernels::cpu::isa_floor_build(); - if (!strata::kernels::cpu::cpu_avx2_ok() && isa_floor[0] == '\0') { - std::fprintf(stderr, "strata generate: this CPU (%s) does not support AVX2 with FMA and F16C, which this engine's " - "CPU expert kernels need; Strata runs on Intel Haswell (2013), AMD Zen (2017) or newer. " - "Older CPUs are EXPERIMENTAL and slow: setup compiles an engine for them on this PC " - "(STRATA_ISA_FLOOR, see \"Older CPUs\" in docs/INSTALL.md)\n", - strata::kernels::cpu::cpu_name().c_str()); - return 2; - } - if (isa_floor[0] != '\0') { - const bool avx_floor = std::strcmp(isa_floor, "avx") == 0; - if (avx_floor ? !strata::kernels::cpu::cpu_avx1_ok() : !strata::kernels::cpu::cpu_sse42_ok()) { - std::fprintf(stderr, "strata generate: this engine is the older-CPU build for %s, which this CPU (%s) does " - "not have%s\n", avx_floor ? "AVX" : "SSE4.2 with POPCNT", - strata::kernels::cpu::cpu_name().c_str(), - avx_floor ? "; compile it with STRATA_ISA_FLOOR=none" : ""); - return 2; - } - if (!strata::kernels::cpu::cpu_avx2_ok()) - std::fprintf(stderr, "strata generate: EXPERIMENTAL older-CPU build (ggml-cpu for %s): this CPU has no AVX2, " - "so the CPU's experts run on ggml-cpu's kernels - expect it to be slow\n", isa_floor); - else - std::fprintf(stderr, "strata generate: this is the older-CPU build (ggml-cpu for %s); this CPU has AVX2, " - "and the normal build is faster on it\n", isa_floor); - } - - std::string err; - if (!o.native_head_gguf.empty() && !o.stream_token) { - 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 - // `.*` 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). - { - 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(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. - const auto& lay = strata::kernels::cpu::expert_layout(); - for (int64_t l = 0; lay.native && l < (int64_t) lay.fmt.size(); ++l) { - const auto& f = lay.fmt[(size_t) l]; - if (!strata::kernels::native_expert_supported(f.gu_type, f.d_type, f.n_embd, f.n_ff)) { - std::fprintf(stderr, "strata generate: layer %lld's experts are %s/%s (ggml types %d/%d), which this " - "engine has no GPU kernels for\n", (long long) l, - strata::ggml_type_name((uint32_t) f.gu_type), strata::ggml_type_name((uint32_t) f.d_type), - f.gu_type, f.d_type); - return 1; - } - } - } - // 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"). - const char* early_env = std::getenv("STRATA_EARLY_REMOTE_CONTEXTS"); - const bool early_remote = early_env && early_env[0] == '1'; - for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0 && (r == 0 || early_remote)) { - // Keep CUDA1's proven startup order: initialise its context before - // allocating GPU0 weights or mapping the large host expert arena. - double free_gib = 0; - if (!strata::core::RemoteExperts::preflight(remote_dev[r], free_gib, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - std::fprintf(stderr, "strata generate: CUDA%d context ready, %.2f GiB free before expert arena registration\n", - remote_dev[r], free_gib); - } - // plan v0.3 P6: the PCIe share of the missed experts, measured per kind of pack (the paper, finding on PCIe). - // PR #44: a x8 link carries half of what the native default assumes - the GPU's SMs read that share over the - // link (the copy kernel, since 0.1.14), so on a slower link it must shrink or the window waits for it. The - // real H2D bandwidth is probed once; from 20 GB/s up (x16 PCIe 4/5) the measured default stays. The canonical - // pack's 0.2 was never measured against the link, so it is left alone. `--calibrate` measures it outright. - if (o.pcie_frac < 0.0) { - const double base = native_pack ? 0.55 : 0.2; - std::string bursts; - const double bw = native_pack ? probe_pcie_h2d_gbps(&bursts) : -1.0; - if (!native_pack) { - o.pcie_frac = base; - } else if (bw > 0.0) { - o.pcie_frac = pcie_frac_for_gbps(bw, base); - std::fprintf(stderr, "strata generate: PCIe probe: %.1f GB/s host->device (best of %s) -> pcie_frac %.2f " - "(default %.2f)\n", bw, bursts.c_str(), o.pcie_frac, base); - } else { - o.pcie_frac = base; - std::fprintf(stderr, "strata generate: PCIe probe failed -> pcie_frac default %.2f\n", base); - } - } - // the canonical Q2_0 pack's CPU kernels are AVX-512 only; a native pack runs on AVX2 CPUs as well - if (!native_pack) strata::kernels::cpu::cpu_require_expert_support(); - else if (!strata::kernels::cpu::cpu_avx512_ok()) - std::fprintf(stderr, "strata generate: this CPU has no AVX-512: the expert kernels run on %s " - "(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)"); - // 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 - // scanning gigabytes of shards first. Precedence: an EXPLICIT flag over the model file's rope keys over - // the struct defaults. The empty --rope-scaling and the 0 --rope-scale mean the flag is absent, so the - // model file decides; an explicit value - `none` and `1` included, the opt-outs - wins over the model file. - { - // The model file's rope keys (llama.cpp's names under the arch prefix), when it carries any - the - // artifact today ships none, so this is a no-op defaults channel for future fine-tunes. - std::string gguf_rope_type; - double gguf_rope_base = 0, gguf_rope_factor = 0, gguf_rope_orig_ctx = 0; - if (!o.native_preset.empty()) { - // 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 - 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", - o.native_preset.c_str(), e.what()); - return 1; - } - } - using RST = strata::kernels::RopeScalingType; - if (!o.rope_scaling.empty()) { - // the early validation pinned the spelling; `none` here is the CLI opting OUT of the model file's keys - if (o.rope_scaling == "linear") rope_cfg.type = RST::Linear; - else if (o.rope_scaling == "yarn") rope_cfg.type = RST::YaRN; - else rope_cfg.type = RST::None; - } else if (!gguf_rope_type.empty()) { - if (gguf_rope_type == "linear") rope_cfg.type = RST::Linear; - else if (gguf_rope_type == "yarn") rope_cfg.type = RST::YaRN; - else if (gguf_rope_type != "none") { - std::fprintf(stderr, "strata generate: %s carries rope.scaling.type '%s' - none, linear or yarn only\n", - o.native_preset.c_str(), gguf_rope_type.c_str()); - return 2; - } - } - if (o.rope_scale > 0) rope_cfg.factor = o.rope_scale; // an explicit factor, 1 included - else if (gguf_rope_factor > 1.0) rope_cfg.factor = gguf_rope_factor; - if (o.rope_freq_base > 0) rope_cfg.freq_base = o.rope_freq_base; - else if (gguf_rope_base > 1.0) rope_cfg.freq_base = gguf_rope_base; - if (o.yarn_orig_ctx > 0) rope_cfg.orig_ctx = o.yarn_orig_ctx; - else if (gguf_rope_orig_ctx >= 1) rope_cfg.orig_ctx = gguf_rope_orig_ctx; - rope_cfg.freq_scale_in = o.rope_freq_scale; - rope_cfg.ext_factor = o.yarn_ext_factor >= 0 ? o.yarn_ext_factor - : (rope_cfg.type == RST::YaRN ? 1.0 : 0.0); - rope_cfg.attn_factor = o.yarn_attn_factor; - rope_cfg.beta_fast = o.yarn_beta_fast; - rope_cfg.beta_slow = o.yarn_beta_slow; - if (rope_cfg.type == RST::None) { - // none is the trained rotation, exactly: the scaling knobs are inert (the table builder and - // `kernel_args` ignore them), and resetting them keeps the logged/queried config honest. Only the - // frequency base survives - it is the rotation itself, not a scaling knob. - const bool knobs = o.rope_scale > 1.0 || o.rope_freq_scale > 0 || o.yarn_ext_factor > 0 || - o.yarn_attn_factor != 1.0; - const double base = rope_cfg.freq_base; - rope_cfg = strata::kernels::RopeScaling{}; - rope_cfg.freq_base = base; - if (knobs) - std::fprintf(stderr, "strata generate: note: no rope scaling is active (none), so --rope-scale, " - "--rope-freq-scale and the --yarn-* knobs have no effect\n"); - } - // THE RESOLVED CONFIG IS VALIDATED AS A WHOLE, with the one rule every rotation site also applies - // (rope_scaling.hpp): the CLI ranges above cannot see a model-file value, nor a combination such as a - // --rope-freq-scale that turns the resolved factor non-finite. - if (const char* why = strata::kernels::rope_scaling_invalid(rope_cfg)) { - std::fprintf(stderr, "strata generate: invalid rope scaling configuration: %s (type %s, factor %g, " - "freq_scale %g, base %g, original context %g)\n", - why, rope_cfg.type == RST::YaRN ? "yarn" : rope_cfg.type == RST::Linear ? "linear" : "none", - rope_cfg.factor, rope_cfg.freq_scale(), rope_cfg.freq_base, rope_cfg.orig_ctx); - return 2; - } - strata::kernels::rope_scaling_set(rope_cfg); - if (rope_cfg.type != RST::None) { - const char* tn = rope_cfg.type == RST::YaRN ? "yarn" : "linear"; - std::fprintf(stderr, - "strata generate: rope scaling %s, factor %.6g (freq_scale %.6g, base %.6g, mscale %.6f), " - "--max-context %lld against a trained context of %.0f\n", - tn, rope_cfg.factor, rope_cfg.freq_scale(), rope_cfg.freq_base, rope_cfg.mscale(), - (long long) o.max_context, rope_cfg.orig_ctx); - if ((double) o.max_context <= rope_cfg.orig_ctx) - std::fprintf(stderr, - "strata generate: note: the context is within the trained %.0f - no position needs the " - "extension, and the resolved scaling still applies to every angle\n", - rope_cfg.orig_ctx); - // only when there IS a magnitude correction: YaRN's log term (ext_factor != 0) or an explicit - // --yarn-attn-factor; plain linear (mscale 1) has none, and saying otherwise was TODO 22 - if (rope_cfg.mscale() != 1.0) - std::fprintf(stderr, - "strata generate: note: the %s magnitude correction scales cos and sin by %.6f " - "at every position\n", - rope_cfg.type == RST::YaRN ? "YaRN" : "--yarn-attn-factor", rope_cfg.mscale()); - } - } - strata::core::NativeEmbed native_embed; - if (native_pack) { - if (o.native_preset.empty() || o.spec < 2 || o.keep_canonical || - (o.prefill_chunk <= 0 && o.tokens.size() > 1)) { - std::fprintf(stderr, "strata generate: %s is a native (IQ) pack: it needs --native SHARD1, --spec T (T >= 2) " - "and --prefill CHUNK\n", o.pack.c_str()); - return 2; - } - if (!native_embed.load(o.embd_gguf.empty() ? o.native_shards : std::vector{o.embd_gguf}, g.n_embd, - g.n_vocab, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - strata::core::set_native_embed(&native_embed); - std::fprintf(stderr, "strata generate: native pack: %s experts (largest blob %.2f MB), token embedding " - "%s in mapped host memory (%.0f MiB)\n", - o.pack.c_str(), (double) strata::kernels::cpu::expert_layout().max_blob / 1e6, - strata::ggml_type_name((uint32_t) native_embed.type()), (double) native_embed.bytes() / 1048576.0); - } - // Plan v0.3 P1: tensors served in native form are not also loaded in canonical form (~2.7 GB of VRAM back - // to the expert cache with --native). `--keep-canonical` loads both, as before. - std::set skip; - if (!o.keep_canonical) { - if (!o.native_dense_gguf.empty() && - !strata::core::NativeDense::served_names(o.native_dense_gguf, o.native_ple_key, skip, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - if (!o.native_head_gguf.empty()) skip.insert("output.weight"); - // the PLE module validates its canonical key at construction (8 MB); a native pack has none to load - if (!native_pack) skip.erase("blk.1.ple_key.weight"); - // #326: a --compat-bf16 pack (OrcaRouter IQ3_XXS) keeps its BF16 key in the arena - if (native_pack && !strata::core::NativeDense::keep_unquantized_ple_key(o.pack, skip, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - if (native_pack) skip.insert("token_embd.weight"); - } - // Layer split with explicit split points: every GPU holds only the dense weights of ITS layers (the PLE tensors - // stay everywhere). Without this each card keeps a full copy (~3.4 GB for the Coder) that its stage never - // reads - VRAM the expert cache wants. Opt-in, STRATA_STAGE_TRIM=1, on HIP and CUDA alike: measured on 2x MI50 - // (PR #639), and the default waits for its author's re-run of the release branch on his cards. - const std::set skip_base = skip; - // --trim-stage-weights (PR #559) is the same switch as STRATA_STAGE_TRIM=1 (PR #639) - const bool stage_trim = multi_gpu && !split_auto && !split_at.empty() && (o.trim_stage_weights || [] { - const char* v = std::getenv("STRATA_STAGE_TRIM"); - return v != nullptr && v[0] != 0 && std::string(v) != "0"; - }()); - if (o.trim_stage_weights && !stage_trim) - std::fprintf(stderr, "strata generate: --trim-stage-weights needs an explicit --layer-split (ignored)\n"); - // keep_routers: CUDA0 with --mmap-experts keeps every layer's router (ffn_gate_inp, ~2.5 MiB a layer) - the file - // tier's routing-aware prefetch (RouterLookahead, below) copies all of them from CUDA0's arena, and would - // otherwise turn itself off - auto add_foreign = [&](int64_t lb, int64_t le, std::set& out, bool keep_routers) { - std::FILE* f = std::fopen((o.pack + "/index.txt").c_str(), "rb"); - if (!f) return; - char line[1024], name[256]; - while (std::fgets(line, sizeof line, f)) { - if (line[0] == '#' || std::sscanf(line, "%255s", name) != 1) continue; - const std::string n = name; - if (n.rfind("blk.", 0) != 0 || n.find("ple") != std::string::npos) continue; - if (keep_routers && n.ends_with(".ffn_gate_inp.weight")) continue; - const int64_t l = std::atoll(name + 4); - if (l < lb || l >= le) out.insert(n); - } - std::fclose(f); - }; - if (stage_trim) { - add_foreign(0, split_at[0], skip, o.mmap_experts); - strata::core::NativeDense::set_layer_range(0, (int) split_at[0]); - std::fprintf(stderr, "strata generate: layer split: CUDA0 loads the dense weights of layers 0-%lld only\n", - (long long) split_at[0] - 1); - } - uint64_t pool_bytes = 0; - if (!strata::core::WeightTable::pool_bytes(o.pack, pool_bytes, err, skip.empty() ? nullptr : &skip)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - void* arena = nullptr; - if (const cudaError_t ce = cudaMalloc(&arena, pool_bytes); ce != cudaSuccess) { - // #486: the arena is the first large allocation and its size does not depend on the context, so what is - // missing is held by something else: say how much was free - cudaGetLastError(); - size_t free_b = 0, total_b = 0; - 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 - " - "nvidia-smi / rocm-smi lists them\n", - (unsigned long long) pool_bytes, cudaGetErrorString(ce), (unsigned long long) (free_b >> 20), - (unsigned long long) (total_b >> 20)); - return 1; - } - strata::core::WeightTable wt; - if (!wt.load(o.pack, arena, pool_bytes, err, skip.empty() ? nullptr : &skip)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - std::fprintf(stderr, "strata generate: %llu MiB of weights loaded from %s (%zu canonical tensors skipped: " - "served natively)\n", - (unsigned long long) (pool_bytes >> 20), o.pack.c_str(), skip.size()); - - strata::core::NativeDense native_dense; - if (!o.native_dense_gguf.empty()) { - // 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); - // Plan v0.3 P3: the fused hyper-connection read rides the native (FP32-activation) contract; the per-stage - // and dump measurements need the unfused layout of R, so they keep the old kernels. - strata::core::layer_set_fast_attn(!o.no_fast_attn); - strata::core::layer_set_publish_kernel(!o.no_publish_kernel); - strata::core::layer_set_fused_gdn(!o.no_fused_gdn); - strata::core::layer_set_fast_select(!o.no_fast_select); - strata::core::layer_set_fused_gr(o.gr_native_mmvf && !o.no_fused_gr && !o.gpu_stages && o.dump_layers.empty() && - o.dump_halves.empty() && !o.stage_timing); - strata::core::layer_set_native_bf16(o.native_bf16); - strata::core::layer_set_native_flash_attn_short(o.native_flash_attn_short); - strata::kernels::ple_set_native_bf16(o.native_bf16_extra); - strata::kernels::shared_expert_set_native_bf16(o.native_bf16_extra); - strata::kernels::native_moe_combine_set_enabled(o.native_moe_combine); - strata::kernels::native_gdn_set_enabled(o.native_gdn); - strata::kernels::native_router_set_enabled(o.native_router); - strata::kernels::native_qsa_set_enabled(o.native_qsa); - strata::kernels::native_qsa_indexer_set_enabled(o.native_qsa_indexer); - strata::kernels::native_rope_set_enabled(o.native_rope); - // The vision path: every rope kernel reads a cell's (t, h, w) from this table (strata/kernels/mrope.hpp). It is - // the identity until an image request, and it is set here, before any CUDA graph captures a rope kernel. - int32_t* d_mrope = nullptr; - std::vector mrope_host; - if (o.vision) { - const int64_t cells = o.max_context + 64; - mrope_host.resize((size_t) cells * 3); - for (int64_t c = 0; c < cells; ++c) - mrope_host[(size_t) c * 3] = mrope_host[(size_t) c * 3 + 1] = mrope_host[(size_t) c * 3 + 2] = (int32_t) c; - if (cudaMalloc(&d_mrope, mrope_host.size() * sizeof(int32_t)) != cudaSuccess || - cudaMemcpy(d_mrope, mrope_host.data(), mrope_host.size() * sizeof(int32_t), cudaMemcpyHostToDevice) != - cudaSuccess) { - std::fprintf(stderr, "strata generate: cannot allocate the image position table\n"); - return 1; - } - strata::kernels::mrope_table_set(d_mrope); - } - strata::kernels::ple_set_native_postops(o.native_ple_postops); - // before session_init: every graph captured from here on has the vector's kernels where it applies - std::string cvec_summary = "0"; - if (!o.cvec_files.empty()) { - std::string ce; - if (!load_control_vectors(o, g, cvec_summary, ce)) { - std::fprintf(stderr, "strata generate: control vector: %s\n", ce.c_str()); - return 2; - } - } - if (o.max_context < (int64_t) o.tokens.size() + o.max_new) { - std::fprintf(stderr, "strata generate: --max-context %lld cannot hold %zu prompt + %lld new tokens\n", - (long long) o.max_context, o.tokens.size(), (long long) o.max_new); - return 2; - } - - strata::core::SessionState ss; - void* sbuf = nullptr; // allocated after the layer-split search, sized to CUDA0's own layer range (the carve) - // **THE ENGINE RAN ON THE LEGACY DEFAULT STREAM, WHICH ON WDDM IS THE SLOW PATH.** All four session - // calls - `session_capture`, `session_replay`, `session_token` and `session_loop` - were handed `nullptr`, - // i.e. stream 0. `bench/micro/kernel_costs.cu` measures what that costs: EVERY kernel it launches through - // a wrapper comes back at 28-31 us REGARDLESS OF SIZE, `scale_inplace` on 2,048 floats and `silu_inplace` - // on 10,240 floats being indistinguishable, which is a fixed per-launch cost and not execution. - // `bench/micro/graph_node_cost.cu` measures the same kernels on a real stream at 3.63 us ungrapped and - // 0.805 us inside a graph. **That is an ~8x penalty on every launch in the engine.** - cudaStream_t main_stream = nullptr; - if (cudaStreamCreateWithFlags(&main_stream, cudaStreamNonBlocking) != cudaSuccess) { - std::fprintf(stderr, "strata generate: cannot create the main stream\n"); - return 1; - } - void* const main_cs = (void*) main_stream; - - // ---- **THE HALF-LEVEL DUMP HAS TO BE ARMED BEFORE `session_capture`, AND THE LADDER MUST NOT BE.** The - // half copies are issued from inside `block_layer_pre`/`block_layer_post`, so they are only ever enqueued - // while a graph is being CAPTURED - arming `ss.block.dump` afterwards would produce a file of zeros that - // reads exactly like a wrong answer. The ladder is the opposite: `session_loop` enqueues it per token on - // the replay stream, so it must be armed after capture to stay out of the graph. - const uint64_t half_stride = (uint64_t) 2 * g.n_embd + (uint64_t) 2 * g.hc + - (uint64_t) g.n_head * g.head_dim + - (uint64_t) 5 * g.n_head_kv * g.head_dim + 8; - std::FILE* half_dump = nullptr; - float* half_stage = nullptr; - if (!o.dump_halves.empty()) { - half_dump = std::fopen(o.dump_halves.c_str(), "wb"); - if (half_dump == nullptr) { - std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_halves.c_str()); - return 1; - } - const size_t n = (size_t) g.n_layers * (size_t) half_stride; - if (cudaHostAlloc((void**) &half_stage, n * sizeof(float), cudaHostAllocDefault) != cudaSuccess) { - std::fprintf(stderr, "strata generate: cannot pin the half-dump staging buffer\n"); - return 1; - } - ss.block.dump = half_stage; - } - - strata::core::Doorbell db; - if (strata::core::doorbell_init(g, K, db) == 0) { - std::fprintf(stderr, "strata generate: doorbell_init failed\n"); - return 1; - } - ss.db = &db; - - // ================================ THE PLE ================================ - // - // **ITS ABSENCE IS WHY GATE C1 FAILED** (LEDGER L123): layer 1 carries six `blk.1.ple_*` tensors, the whole - // module was built and parity-tested, and nothing called it. Everything below is construction - the table - // is a mapping of the ORIGINAL second GGUF shard, the six weights are already loaded in the arena, and the - // three buffers are the only allocation. - strata::kernels::PleTable ple_table; - std::vector ple_emb_host((size_t) strata::kernels::NG_N_EMBD); - float* ple_emb_dev = nullptr; - float* ple_scratch = nullptr; - if (!o.ple_gguf.empty()) { - strata::kernels::PleIoOptions pio; - pio.mode = o.ple_io == "mmap" || o.ple_io == "ram" ? strata::kernels::PleIo::Mmap : strata::kernels::PleIo::Direct; - pio.lock = o.ple_io == "ram"; - const auto tpl = Clock::now(); - pio.max_inflight = (uint32_t) o.ple_inflight; - pio.cache_rows = (uint64_t) o.ple_row_cache; - pio.io_thread = !o.ple_sync_submit; - // Keep the SSD awake while rows are being asked for (PleReader::set_keepalive): some SSDs stall the first - // reads 50-150 ms after ~250 ms without a command. STRATA_SSD_KEEPALIVE = ms without a read before one - // page is read anyway (default 100, 0 = off), STRATA_SSD_KEEPALIVE_WINDOW = seconds after the last row - // request that this goes on (default 60; then the SSD may sleep until the next request). - { - const char* ka = std::getenv("STRATA_SSD_KEEPALIVE"); - const char* kw = std::getenv("STRATA_SSD_KEEPALIVE_WINDOW"); - pio.keepalive_ms = ka != nullptr && *ka ? std::clamp(std::atof(ka), 0.0, 10000.0) : 100.0; - pio.keepalive_window_s = kw != nullptr && *kw ? std::clamp(std::atof(kw), 1.0, 86400.0) : 60.0; - if (pio.mode != strata::kernels::PleIo::Direct || !pio.io_thread) pio.keepalive_ms = 0; - } - if (!ple_table.open(o.ple_gguf, err, pio)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } -#if !defined(_WIN32) - if (pio.mode == strata::kernels::PleIo::Direct) { - // #605: --ple-io direct's random reads (up to --ple-inflight at once) are for SSDs; a rotational disk - // can take longer than the stall watchdog's 60 s for one prompt chunk's rows. Recommended, not forced. - std::string dev; - if (!under_wddm() && on_rotational_disk(o.ple_gguf, dev) == 1) // (WSL's virtual disk says rotational) - std::fprintf(stderr, "strata generate: WARNING: the n-gram table (%s) is on a rotational disk (%s): " - "--ple-io direct reads it at random and can stall a prompt for minutes (#605). " - "--ple-io ram (it then needs RAM for the table) or the model on an SSD is " - "recommended\n", o.ple_gguf.c_str(), dev.c_str()); - } -#endif - if (pio.lock) - std::fprintf(stderr, "strata generate: PLE table %s (--ple-io ram) in %.1f s\n", - ple_table.locked() ? "locked in RAM" : "loaded (not locked)", - std::chrono::duration(Clock::now() - tpl).count()); - if (pio.keepalive_ms > 0) - std::fprintf(stderr, "strata generate: the SSD is kept awake while rows are read: one page of the table after " - "%.0f ms without a read, until %.0f s after the last request " - "(STRATA_SSD_KEEPALIVE=0 turns it off)\n", pio.keepalive_ms, pio.keepalive_window_s); - else if (pio.mode == strata::kernels::PleIo::Direct) - std::fprintf(stderr, "strata generate: SSD keep-alive off: the SSD may fall asleep between reads\n"); - const strata::core::WeightRef* wk = wt.find("blk.1.ple_key.weight"); - const strata::core::WeightRef* wv = wt.find("blk.1.ple_value.weight"); - const strata::core::WeightRef* wnk = wt.find("blk.1.ple_norm_key.weight"); - const strata::core::WeightRef* wnq = wt.find("blk.1.ple_norm_query.weight"); - const strata::core::WeightRef* wnc = wt.find("blk.1.ple_norm_conv.weight"); - const strata::core::WeightRef* wc = wt.find("blk.1.ple_conv1d.weight"); - if (!wk || !wv || !wnk || !wnq || !wnc || !wc) { - std::fprintf(stderr, "strata generate: the pack has no blk.1.ple_* tensors, so the PLE cannot be " - "wired - and running without it is a DIFFERENT MODEL (LEDGER L123)\n"); - return 1; - } - // `ple_key` is S2 and the loader has already widened its scales to f32, so the two planes are located - // by the sizes the `WeightRef` records rather than re-derived - the same rule `plane_ptrs` follows. - if (!wk->quantized()) { - // plan v0.3 P6: the IQ model files' BF16 key (the pack's extra.bin, raw BF16) - ss.ple.w.key_bf16 = (const uint16_t*) wk->data; - } else if (wk->data != nullptr) { - ss.ple.w.key_codes = (const uint8_t*) wk->data; - ss.ple.w.key_scales = (const float*) ((const uint8_t*) wk->data + wk->codes_bytes); - } - if (o.native_ple_key && wk->quantized()) { - if (!wk->native_data || (wk->native_type != 42 && wk->native_type != 18 && wk->native_type != 23 && - wk->native_type != 8) || !wk->native_q8_1) { - std::fprintf(stderr, "strata generate: native PLE key is absent or incompatible\n"); - return 1; - } - ss.ple.w.key_native_data = wk->native_data; - ss.ple.w.key_native_type = wk->native_type; - ss.ple.w.key_native_q8_1 = wk->native_q8_1; - } - ss.ple.w.value_bf16 = (const uint16_t*) wv->data; - ss.ple.w.norm_key = (const float*) wnk->data; - ss.ple.w.norm_query = (const float*) wnq->data; - ss.ple.w.norm_conv = (const float*) wnc->data; - // The conv1d kernel reads F16, so this cast is a claim about the pack's storage. A checkpoint that keeps - // the tensor F32 (Q8_0, UD-Q4_K_XL) would hand the kernel the low halves of the f32 words - not an error, - // a plausible wrong layer-1 routing. tools/iq_pack.py narrows it (index kind 3); a pack that did not is - // refused here (#255, gopinath87607). F16 is index kind 5 or 3 (F16InF32) in a native pack and kind 0 - // (verbatim 2-byte F16) in the canonical Q2_0 pack; BF16 (kind 4) has the same size and is not F16. - const bool f16 = wc->kind == strata::core::WeightKind::F16InF32 || - (wc->kind == strata::core::WeightKind::Verbatim && wc->code_bits == 0); - if (!f16 || wc->bytes != (uint64_t) wc->elements * 2) { - std::fprintf(stderr, "strata generate: blk.1.ple_conv1d.weight is not stored as F16 (pack index kind %d, " - "%llu B for %lld values); the PLE conv1d kernel reads F16 - repack with " - "tools/iq_pack.py\n", - (int) wc->kind, (unsigned long long) wc->bytes, (long long) wc->elements); - return 1; - } - ss.ple.w.conv1d_f16 = (const uint16_t*) wc->data; - ss.ple.consts = strata::kernels::ple_artifact_consts(); - if (o.ple_delay_us > 0) ple_table.set_injected_delay_us(o.ple_delay_us); - ss.ple.table = &ple_table; - ss.ple.token = &ss.ple_token; - ss.ple.prev = ss.ple_prev; - // `ss.ple.hist` and the ready() check wait for `session_init`, which carves the history - the session is - // now allocated after the layer-split search (see the carve), and the wiring lands there - ss.ple.emb_host = ple_emb_host.data(); - if (cudaMalloc((void**) &ple_emb_dev, (size_t) strata::kernels::NG_N_EMBD * 4) != cudaSuccess || - cudaMalloc((void**) &ple_scratch, strata::core::ple_run_scratch_bytes()) != cudaSuccess) { - std::fprintf(stderr, "strata generate: the PLE buffers failed\n"); - return 1; - } - ss.ple.emb_dev = ple_emb_dev; - ss.ple.scratch = ple_scratch; - } else { - std::fprintf(stderr, - "strata generate: PLE OFF by explicit --no-ple diagnostic request.\n" - " The tokens below are NOT this model's; this is only useful for A/B measurement.\n"); - } - - float* d_parts = nullptr; - if (cudaMalloc(&d_parts, (size_t) K * g.n_embd * 4) != cudaSuccess || - cudaMemset(d_parts, 0, (size_t) K * g.n_embd * 4) != cudaSuccess) { - std::fprintf(stderr, "strata generate: the parts buffer failed\n"); - return 1; - } - - // ---- --split-skip-if-fits: before any later stage loads, does CUDA0 alone hold every profiled pair? What it - // still has to allocate on one GPU is the whole session (the KV of every layer), the drafter and the head - // (kDrafterMib below), the verify windows and the reserve; the prompt path borrows from the cache. If the - // profile's pairs fit in what is left, a split would only add the hand-offs: run on CUDA0 alone. - if (multi_gpu && split_auto && o.split_skip_if_fits) { - std::vector> prof; - int64_t pslots = 0; - std::string perr; - const bool remote = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0; - if (remote || o.expert_profile.empty() || - !strata::core::read_expert_profile(o.expert_profile, g.n_layers, g.n_expert, prof, pslots, perr)) { - std::fprintf(stderr, "strata generate: --split-skip-if-fits: %s; the split stays\n", - remote ? "remote expert caches are in use" : perr.empty() ? "no expert profile" : perr.c_str()); - } else { - const auto& lay = strata::kernels::cpu::expert_layout(); - int64_t pairs_bytes = 0; - 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; - 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; - cudaDeviceProp dp{}; - cudaGetDeviceProperties(&dp, 0); - if (pairs_bytes <= room) { - std::fprintf(stderr, "strata generate: layer split skipped (--split-skip-if-fits): CUDA0 (%s) holds all " - "%zu profiled pairs (%.2f GiB) with the session (%.2f GiB, %lld-token context), " - "the drafter and the reserve: %.2f GiB free, %.2f GiB to spare - one GPU\n", - dp.name, prof.size(), (double) pairs_bytes / 1073741824.0, (double) session / 1073741824.0, - (long long) o.max_context, (double) fb / 1073741824.0, - (double) (room - pairs_bytes) / 1073741824.0); - multi_gpu = false; - split_auto = false; - split_devs.clear(); - split_at.clear(); - o.layer_split.clear(); - } else { - std::fprintf(stderr, "strata generate: --split-skip-if-fits: CUDA0 (%s) would hold only %.2f of the " - "profile's %.2f GiB (%.2f GiB free, %.2f GiB for the session, drafter and " - "reserve): the split stays\n", dp.name, - (double) std::max(room, 0) / 1073741824.0, (double) pairs_bytes / 1073741824.0, - (double) fb / 1073741824.0, (double) held_back / 1073741824.0); - } - } - } - strata::core::Verifier::set_commit_async(!multi_gpu); // see Verifier::set_commit_async - // ---- layer split across GPUs: each later stage's own copy of the dense weights, its session and (the last) the - // head, made on its device before the host arena is mapped (as the drafter below, for the same WDDM reason) - std::vector> stages; - for (size_t i = 0; multi_gpu && i < split_devs.size(); ++i) { - stages.push_back(std::make_unique()); - GpuStage& st = *stages.back(); - st.dev = split_devs[i]; - double free_gib = 0; - if (!strata::core::RemoteExperts::preflight(st.dev, free_gib, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - const strata::core::OnDevice on(st.dev); - std::set skip_s = skip_base; - uint64_t pool_s = pool_bytes; - if (stage_trim) { - const int64_t lb = split_at[i], le = i + 1 < split_at.size() ? split_at[i + 1] : g.n_layers; - add_foreign(lb, le, skip_s, false); - strata::core::NativeDense::set_layer_range((int) lb, (int) le); - if (!strata::core::WeightTable::pool_bytes(o.pack, pool_s, err, &skip_s)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - std::fprintf(stderr, "strata generate: layer split: CUDA%d loads the dense weights of layers %lld-%lld only\n", - st.dev, (long long) lb, (long long) le - 1); - } else { - skip_s = skip; - } - void* arena_s = nullptr; - if (cudaMalloc(&arena_s, pool_s) != cudaSuccess || - !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 - 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(), - (unsigned long long) (pool_s >> 20), (unsigned long long) (free_b >> 20), - (unsigned long long) (total_b >> 20)); - return 1; - } - if (!o.native_dense_gguf.empty() && !st.dense.load(o.native_dense_gguf, st.wt, err, o.native_ple_key)) { - std::fprintf(stderr, "strata generate: layer split, CUDA%d native dense projections: %s\n", st.dev, - err.c_str()); - return 1; - } - // THE SESSION AND THE HEAD WAIT FOR THE SPLIT SEARCH. `session_bytes` prices a stage's session by its - // LAYER RANGE (the carve - every stage used to hold all 48 layers' state whatever it ran), so the - // sessions are allocated after the search below has set `st.lb`/`st.le`; the last stage's head follows. - if (cudaStreamCreateWithFlags(&st.stream, cudaStreamNonBlocking) != cudaSuccess || - cudaStreamCreateWithFlags(&st.adapt_stream, cudaStreamNonBlocking) != cudaSuccess || - cudaEventCreateWithFlags(&st.adapt_ev, cudaEventDisableTiming) != cudaSuccess) { - std::fprintf(stderr, "strata generate: layer split, CUDA%d: its streams failed\n", st.dev); - return 1; - } - // a control vector (the speed projection): its tables on this device too - the stage's layers apply it here - if (!strata::kernels::cvec_replicate(err)) { - std::fprintf(stderr, "strata generate: layer split, CUDA%d: %s\n", st.dev, err.c_str()); - return 1; - } - // --vision: this device's image-position table (the identity until a picture request), read by every rope - // kernel its stage runs - set before any of its graphs is captured - if (o.vision) { - if (cudaMalloc(&st.mrope, mrope_host.size() * sizeof(int32_t)) != cudaSuccess || - cudaMemcpy(st.mrope, mrope_host.data(), mrope_host.size() * sizeof(int32_t), cudaMemcpyHostToDevice) != - cudaSuccess) { - std::fprintf(stderr, "strata generate: layer split, CUDA%d: the image position table failed\n", st.dev); - return 1; - } - strata::kernels::mrope_table_set(st.mrope); - } - // its own PCIe share of the missed experts (the same rule as CUDA0's above: its link is probed). A given - // --pcie-frac is every stage's share and skips these probes (pcie_given); there is no per-stage setting yet. - st.pcie_frac = o.pcie_frac; - if (!pcie_given && native_pack) { - std::string bursts; - const double bw = probe_pcie_h2d_gbps(&bursts); - if (bw > 0.0) st.pcie_frac = pcie_frac_for_gbps(bw, 0.55); - std::fprintf(stderr, "strata generate: layer split: CUDA%d PCIe probe %.1f GB/s (best of %s) -> pcie_frac " - "%.2f\n", st.dev, bw, bursts.c_str(), st.pcie_frac); - } - size_t fb = 0, tb = 0; - 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); - } - GpuStage* const last_st = stages.empty() ? nullptr : stages.back().get(); - - std::vector> profile; - if (!o.expert_profile.empty()) { - int64_t pslots = 0; - if (!strata::core::read_expert_profile(o.expert_profile, g.n_layers, g.n_expert, profile, pslots, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - // An explicit number truncates the ranked list ("what would 2,000 slots give" without rebuilding the - // file). `--expert-cache 0` used to take the count the profile was built for; the profile now ranks - // every pair (issue #46: a card that holds more than the old 8,000 used to stop there), so it means auto. - if (o.expert_cache == 0) o.expert_cache = -1; - // Multi-GPU: STRATA_PEER_HOT= gives the peer card a share f of the HOT pairs, so both cards - // compute routed experts every layer (the primary alone did ~25 of ~30 per layer-window). Of the first - // STRATA_PEER_HOT_AT (default 8700, ~ the primary's slots) ranks, every pair with floor((r+1)f) > floor(rf) - // moves to just after that point: the primary fills past them, the peer (which takes what the primary does - // not hold, in order) gets them first. - if (o.peer_device >= 1) { // default 0.45 (measured: 0.3-0.6 all better than 0; 0 = off, e.g. for the gate) - const char* ph = std::getenv("STRATA_PEER_HOT"); - const double f = ph ? std::atof(ph) : 0.45; - const char* pa = std::getenv("STRATA_PEER_HOT_AT"); - const size_t at = std::min(profile.size(), (size_t) (pa ? std::atoll(pa) : 8700)); - if (f > 0.0 && f < 1.0 && at > 0) { - std::vector> keep, moved; - for (size_t r = 0; r < at; ++r) { - const bool to_peer = (int64_t) ((double) (r + 1) * f) > (int64_t) ((double) r * f); - (to_peer ? moved : keep).push_back(profile[r]); - } - const size_t n_moved = moved.size(); - // the primary's share continues with the ranks after `at` until it is full; then the moved ones - std::vector> out; - out.reserve(profile.size()); - out.insert(out.end(), keep.begin(), keep.end()); - const size_t fill = std::min(profile.size(), at + n_moved); // what the primary still takes - out.insert(out.end(), profile.begin() + (long) at, profile.begin() + (long) fill); - out.insert(out.end(), moved.begin(), moved.end()); - out.insert(out.end(), profile.begin() + (long) fill, profile.end()); - profile.swap(out); - std::fprintf(stderr, "strata generate: STRATA_PEER_HOT %.2f: %zu of the first %zu ranked pairs moved " - "behind rank %zu (the peer's)\n", f, n_moved, at, fill); - } - } - std::fprintf(stderr, "strata generate: profile %s: %zu ranked pairs, built for %lld slots\n", - o.expert_profile.c_str(), profile.size(), (long long) pslots); - } - // #477: the whole ranking as loaded, the prior of --expert-profile-save's order (a layer split keeps only - // CUDA0's pairs in `profile` below). Empty without --expert-profile-save. - std::vector> profile_loaded; - if (!o.expert_profile_save.empty()) profile_loaded = profile; - // ---- layer split across GPUs: "auto" places the split points by a cost model of one decode window, measured on - // the 5080 + 3090 rig (bench/results/2026-09-29-layer-split): - // - every layer costs its GPU a time inversely proportional to SMs x clock (0.33 ms on an RTX 5080, 0.50 on a - // 3090: the per-layer round trip and kernels, not the bytes - both cards have ~950 GB/s); - // - an expert no cache holds costs ~190 ms per unit of routed mass: the CPU pool in decode and the PCIe stream - // in prompts (fitted: the sweep's best K, 26-28, is where one more layer on the faster card stops paying - // for the ~0.1% of the mass it pushes out of its cache); - // - which experts a cache holds: its layers' profiled pairs, hottest first, until its free VRAM (less the - // reserve, the prompt path's buffers and, on a later GPU, 1 GiB for its windows and the drafter) is used; - // the routed mass of rank r is taken as (r+1)^-1.2 (fits the sweep's hit rates: K=24/26/28 predicted - // 99.53/99.34/99.15%, measured 99.5/99.4/99.0%). - // Up to 3 GPUs every placement is tried; beyond, the layers are shared in proportion to speed. - // STRATA_SPLIT_MISS_MS tunes the miss cost (a slower CPU: higher). - // THE PROMPT PATH'S BUFFERS ARE BORROWED FROM THE CACHE, NOT WITHHELD BESIDE IT. With borrowing the cache - // is sized first and at full size, and the prompt path is laid out in the tail of it (`Prefill::relayout`), - // so it withholds no VRAM of its own and this reserve is zero. Only without borrowing - no profile to fill - // a cache from, or --no-prefill-borrow - do the buffers take a reserve, and then this estimate stands in - // for buffers that cannot be priced exactly yet because the sessions do not exist. `plan_lend` uses the - // exact `Prefill::bytes_needed` as soon as it can. - const bool pf_borrow = !o.no_prefill_borrow && !o.expert_profile.empty(); - // (#340: the estimate predates the streamed ring: from 1024-token chunks the prompt path also holds a ring of - // whole expert blobs, which a split without borrowing sizes at 96 (Prefill::set_ring_override below) and books - // here - without it a `--no-prefill-borrow` split filled the cards and the draft head no longer fit) - const int64_t split_ring_mib = - (multi_gpu && !pf_borrow && o.prefill_chunk >= 1024) - ? (int64_t) ((96ull * (uint64_t) strata::kernels::cpu::expert_layout().max_blob + (1ull << 20) - 1) >> 20) - : 0; - if (split_ring_mib > 0) strata::prefill::Prefill::set_ring_override(96); - const int64_t split_pf_mib = - (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 + split_ring_mib : 0; - // ---- WHAT A STAGE RESERVES, AND ON WHICH STAGE. The flat 1 GiB this used to withhold from EVERY stage - // after the first was booked "for its windows and the drafter", but the windows measure 75 MiB ("window up - // to 6 tokens, 74.1 MiB of device buffers", on every boot) and the drafter is loaded on ONE stage - the - // last one, which is also the only one that holds the head. On the two identical 8 GB cards that GiB was - // the entire difference between CUDA0's cache and CUDA1's: 814 slots against 188, 2026-09-30. Both of - // those allocations are already made before a stage's cache is sized, so what has to be held back here is - // the windows and - only on the stage that carries them - the drafter and the head. - const int64_t kWindowMib = 96; // the verify windows; 75 MiB measured, rounded up - const int64_t kDrafterMib = 1000; // the MTP drafter (839 MiB) + the head, on the last stage only - // #340: with the own prompt buffers chosen by the split's rule (not asked for with --no-prefill-borrow) the - // boundary is searched as the borrowing configuration would (no reserve): the reserve then only makes the caches - // smaller, which measured cost no decode (K=28 on 9070 XT + R9700: 58.4 tok/s own vs 58.5 borrowing), while a - // search with the reserve moved the boundary to K=32 and decode to 54.8. STRATA_SPLIT_OWN_PLACE=reserve: the - // search sees the reserve. - static const bool place_with_reserve = [] { - const char* v = std::getenv("STRATA_SPLIT_OWN_PLACE"); - return v != nullptr && std::string(v) == "reserve"; - }(); - 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 = 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; - const int64_t reserve = ((int64_t) o.vram_reserve_mib + pf + (later ? kWindowMib : 0) + - (drafter ? kDrafterMib : 0)) << 20; - return std::max((int64_t) fb - reserve, 0); - }; - if (multi_gpu && split_auto) { - const auto& lay = strata::kernels::cpu::expert_layout(); - const int ns = (int) stages.size() + 1; - std::vector cap((size_t) ns), used((size_t) ns); - std::vector layer_ms((size_t) ns); - for (int i = 0; i < ns; ++i) { - const int dev = i == 0 ? 0 : stages[(size_t) i - 1]->dev; - cap[(size_t) i] = stage_room(i == 0 ? -1 : dev, i > 0, i + 1 == ns, true); - int sms = 0, khz = 0; - cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev); - if (cudaDeviceGetAttribute(&khz, cudaDevAttrClockRate, dev) != cudaSuccess || khz <= 0) khz = 1800000; - cudaGetLastError(); - const double speed = std::max(1.0, (double) sms * (double) khz / 1e6); // SMs x GHz - layer_ms[(size_t) i] = 0.33 * (84.0 * 2.617) / speed; - std::fprintf(stderr, "strata generate: layer split auto: CUDA%d %d SMs at %.2f GHz -> %.2f ms per layer, " - "%.2f GiB free before its session carve\n", dev, sms, khz / 1e6, layer_ms[(size_t) i], - (double) cap[(size_t) i] / 1073741824.0); - } - const double miss_ms = std::getenv("STRATA_SPLIT_MISS_MS") ? std::atof(std::getenv("STRATA_SPLIT_MISS_MS")) : 190.0; - std::vector mass(profile.size()); - double total_mass = 0; - for (size_t r = 0; r < profile.size(); ++r) total_mass += (mass[r] = std::pow((double) r + 1.0, -1.2)); - auto cost = [&](int64_t l) -> int64_t { - return native_pack ? ((int64_t) lay.blob_bytes(l) + 255) / 256 * 256 : (int64_t) lay.max_blob; - }; - // the predicted window time (ms) of a placement, and the routed mass its caches hold - auto predict = [&](const std::vector& at, double& held_mass, int64_t& held) -> double { - // THE CARVE, PRICED: a placement gives stage i the layers [lb, le), and that range's session is a - // real cost on its device - subtracted here so the search knows what it leaves for experts. This - // is why the sessions are allocated after the search: `session_bytes` is pure arithmetic. - std::vector capr((size_t) ns); - for (int i = 0; i < ns; ++i) { - const int64_t lb = i == 0 ? 0 : at[(size_t) i - 1]; - const int64_t le = i + 1 < ns ? at[(size_t) i] : g.n_layers; - capr[(size_t) i] = cap[(size_t) i] - (int64_t) strata::core::session_bytes(g, o.max_context, K, lb, le); - } - std::fill(used.begin(), used.end(), 0); - held_mass = 0; - held = 0; - std::vector full((size_t) ns, false); - for (size_t r = 0; r < profile.size(); ++r) { - const int64_t l = profile[r].first; - int st = 0; - while (st + 1 < ns && l >= at[(size_t) st]) ++st; - if (full[(size_t) st]) continue; - if (used[(size_t) st] + cost(l) > capr[(size_t) st]) { full[(size_t) st] = true; continue; } // as the fill - used[(size_t) st] += cost(l); - held_mass += mass[r]; - ++held; - } - held_mass /= std::max(total_mass, 1e-9); - double ms = miss_ms * (1.0 - held_mass); - for (int i = 0; i < ns; ++i) { - const int64_t lb = i == 0 ? 0 : at[(size_t) i - 1], le = i + 1 < ns ? at[(size_t) i] : g.n_layers; - ms += (double) (le - lb) * layer_ms[(size_t) i]; - } - return ms; - }; - std::vector best, at((size_t) ns - 1); - double best_ms = 1e30, best_mass = 0; - int64_t best_held = 0; - auto consider = [&]() { - double hm = 0; - int64_t held = 0; - const double ms = predict(at, hm, held); - if (ms < best_ms) { best = at; best_ms = ms; best_mass = hm; best_held = held; } - }; - const int64_t L = g.n_layers; - if (ns == 2) { - for (int64_t k = 2; k < L; ++k) { at[0] = k; consider(); } - } else if (ns == 3) { - for (int64_t k1 = 2; k1 + 1 < L; ++k1) - for (int64_t k2 = k1 + 1; k2 < L; ++k2) { at[0] = k1; at[1] = k2; consider(); } - } else { - double total = 0; - for (const double c : layer_ms) total += 1.0 / c; - double acc = 0; - for (int i = 0; i + 1 < ns; ++i) { - acc += 1.0 / layer_ms[(size_t) i]; - at[(size_t) i] = std::clamp((int64_t) std::llround(acc / total * (double) L), - i == 0 ? 2 : at[(size_t) i - 1] + 1, L - (ns - 1 - i)); - } - consider(); - } - split_at = best; - std::string ks; - for (const int64_t k : split_at) ks += (ks.empty() ? "" : ",") + std::to_string(k); - std::fprintf(stderr, "strata generate: layer split auto: K=%s - predicted %.1f ms per decode window; the caches " - "hold %lld of %zu profiled pairs (~%.1f%% of the routed mass)\n", ks.c_str(), best_ms, - (long long) best_held, profile.size(), 100.0 * best_mass); - } - for (size_t i = 0; i < split_at.size(); ++i) - if (split_at[i] >= g.n_layers) { - std::fprintf(stderr, "strata generate: --layer-split: layer %lld is past the last (%lld)\n", - (long long) split_at[i], (long long) (g.n_layers - 1)); - return 2; - } - // the stage that runs a layer (0: CUDA0's) - auto stage_of = [&](int64_t l) -> int { - int st = 0; - while (st < (int) split_at.size() && l >= split_at[(size_t) st]) ++st; - return st; - }; - if (multi_gpu) { - std::vector> mine; - for (const auto& pr : profile) { - const int st = stage_of(pr.first); - (st == 0 ? mine : stages[(size_t) st - 1]->profile).push_back(pr); - } - profile.swap(mine); - for (size_t i = 0; i < stages.size(); ++i) { - stages[i]->lb = split_at[i]; - stages[i]->le = i + 1 < stages.size() ? split_at[i + 1] : g.n_layers; - } - } - - // ---- CUDA0's session, and the stages' sessions: sized to each device's own layer range (the carve). A - // stage that runs [lb, le) carves only those layers' GDN rows and QSA pools - before the carve every stage - // held all 48 layers' state whatever layers it ran, which is the same disease the chunked-QSA-prefill PR - // fixed in llama.cpp: allocation sized by the whole model instead of the device's own work. - { - const strata::core::OnDevice on0(0); - const int64_t hi0 = multi_gpu ? split_at[0] : -1; - if (cudaMalloc(&sbuf, strata::core::session_bytes(g, o.max_context, K, 0, hi0)) != cudaSuccess) { - std::fprintf(stderr, "strata generate: session state allocation failed\n"); - return 1; - } - if (strata::core::session_init(g, o.max_context, K, sbuf, ss, 0, hi0) == 0) { - std::fprintf(stderr, "strata generate: session_init failed\n"); - return 1; - } - if (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1) - std::fprintf(stderr, "strata generate: KV streaming: %lld of %lld cells per QSA layer in VRAM, the K/V in " - "%.2f GiB of pinned RAM\n", - (long long) (ss.qsa_states[ss.qsa_primary()].n_slots * 4), - (long long) o.max_context, (double) strata::core::qsa_kv_host_bytes() / 1073741824.0); - // the PLE block above built everything but the history, which session_init has just carved - ss.ple.hist = ss.ple_hist; - // (#167) generate mode starts from an empty sequence, and nothing else zeroes this state before the prompt - // path or the verifier reads it (--serve zeroes it per request when nothing is reused) - strata::core::session_zero(ss, g, nullptr, main_cs); - if (cudaDeviceSynchronize() != cudaSuccess) { - std::fprintf(stderr, "strata generate: zeroing the session state failed\n"); - return 1; - } - if (!o.ple_gguf.empty()) { - if (!ss.ple.ready()) { - std::fprintf(stderr, "strata generate: the PLE run is not ready after construction\n"); - return 1; - } - std::fprintf(stderr, "strata generate: PLE on, table %llu rows of %s\n", - (unsigned long long) ple_table.rows(), o.ple_gguf.c_str()); - } - } - for (size_t i = 0; i < stages.size(); ++i) { - GpuStage& st = *stages[i]; - const strata::core::OnDevice on(st.dev); - void* sbuf_s = nullptr; - if (cudaMalloc(&sbuf_s, strata::core::session_bytes(g, o.max_context, K, st.lb, st.le)) != cudaSuccess || - strata::core::session_init(g, o.max_context, K, sbuf_s, st.ss, st.lb, st.le) == 0) { - std::fprintf(stderr, "strata generate: layer split, CUDA%d: the session state failed\n", st.dev); - return 1; - } - const bool last = i + 1 == stages.size(); - const strata::core::WeightRef* wo_s = st.wt.find("output.weight"); - if (wo_s == nullptr || - (last && !o.native_head_gguf.empty() && !st.head.load(o.native_head_shards, g.n_embd, wo_s->ne1, err))) { - std::fprintf(stderr, "strata generate: layer split, CUDA%d head: %s%s\n", st.dev, - wo_s == nullptr ? "output.weight is missing" : err.c_str(), - wo_s == nullptr ? "" : vram_free_note().c_str()); - return 1; - } - size_t fb = 0, tb = 0; - 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); - } - - // --batch: every stage carves o.batch more sessions like its own (same layer range and context), one per - // slot of the batch windows. Before the expert cache is sized, so `--expert-cache auto` leaves them room. - // Recommend, never force: a count the engine cannot run is said and adjusted (or batching left off) - the - // engine still starts and serves one request at a time. - std::vector>> bslot_ss; - if (o.batch != 0) { - const int cap = strata::kernels::kVerifyMaxT; - const char* off = !o.serve ? "it needs --serve" : o.batch < 2 ? "it needs 2 or more slots" - : split_same ? "it needs each stage of a layer split on its own GPU" : nullptr; - if (off != nullptr) { - std::fprintf(stderr, "strata generate: WARNING: --batch %d is off: %s\n", o.batch, off); - o.batch = 0; - } else if (o.batch > cap) { - std::fprintf(stderr, "strata generate: WARNING: --batch %d: a batch window holds at most %d rows, so %d " - "slots\n", o.batch, cap, cap); - o.batch = cap; - } - } - if (o.batch > 0 && o.batch_groups > 1 && (stages.empty() || o.batch % o.batch_groups != 0)) { - std::fprintf(stderr, "strata generate: WARNING: --batch-groups %d needs a layer split and to divide --batch %d; " - "one group\n", o.batch_groups, o.batch); - o.batch_groups = 1; - } - if (o.batch > 0) { - bslot_ss.resize(1 + stages.size()); - int fit = o.batch; // the slots every stage could carve - uint64_t bytes0 = 0; - for (size_t k = 0; k < bslot_ss.size(); ++k) { - const int dev = k == 0 ? 0 : stages[k - 1]->dev; - const int64_t lo = k == 0 ? 0 : stages[k - 1]->lb; - const int64_t hi = k == 0 ? (multi_gpu ? split_at[0] : -1) : stages[k - 1]->le; - const strata::core::OnDevice on_k(dev); - const uint64_t bytes = strata::core::session_bytes(g, o.max_context, K, lo, hi); - if (k == 0) bytes0 = bytes; - for (int b = 0; b < fit; ++b) { - auto u = std::make_unique(); - void* buf = nullptr; - if (cudaMalloc(&buf, bytes) != cudaSuccess || strata::core::session_init(g, o.max_context, K, buf, *u, lo, hi) == 0) { - cudaGetLastError(); - if (buf != nullptr) cudaFree(buf); - size_t fb = 0, tb = 0; - 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"); - fit = b; - break; - } - strata::core::session_zero(*u, g, nullptr, nullptr); - bslot_ss[k].push_back(std::move(u)); - } - cudaDeviceSynchronize(); - size_t fb = 0, tb = 0; - 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); - } - for (auto& v : bslot_ss) if ((int) v.size() > fit) v.resize((size_t) fit); // the same count on every stage - if (fit < 2) { - std::fprintf(stderr, "strata generate: WARNING: --batch is off: not two slot sessions fit (a smaller " - "--max-context or KV streaming, --kv-resident, makes them smaller)\n"); - bslot_ss.clear(); - o.batch = 0; - } else { - o.batch = fit; - if (o.batch_groups > 1 && o.batch % o.batch_groups != 0) o.batch_groups = 1; - // the sessions' VRAM is the expert cache's: say what it costs (docs/BATCHING.md has the measured trade) - std::fprintf(stderr, "strata generate: --batch %d: the slot sessions take %.2f GiB of VRAM on CUDA0 that the " - "expert cache would otherwise hold\n", o.batch, - (double) bytes0 * o.batch / 1073741824.0); - } - } - - // Secure MTP's CUDA0 allocations before the large host arena is registered with both CUDA contexts. - // In particular WDDM can refuse the draft weights after mapping tens of GiB of host pages. - strata::core::MtpDrafter mtp; - if (!o.mtp.empty()) { - if (o.spec < 2) { - std::fprintf(stderr, "strata generate: --mtp is ignored without --spec T (T >= 2)\n"); - o.mtp.clear(); - } - if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size()); - // 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; } - mtp.set_ple_session(&ss); - } - // THE HEAD BEFORE THE CACHE, AND BEFORE THE ARENA. The expert cache takes what is free minus the reserve, so - // everything allocated after it comes out of the reserve. The native head (~0.5 GB with IQ3_S) was loaded after - // it and ate most of the 700 MiB: 128K IQ3_S ended with 30 MiB free, the driver paged, and a request stalled for - // good at its first verify window. Loaded first, the cache is sized around it. #620: and before the expert - // arena registers tens of GiB of host pages, like the drafter above - WDDM then refused the head's cudaMalloc on - // a 16 GB card with the desktop on the iGPU ("native head upload: out of memory" with GiBs free). - const strata::core::WeightRef* wo = wt.find("output.weight"); - if (wo == nullptr) { std::fprintf(stderr, "strata generate: output.weight is missing\n"); return 1; } - const int64_t n_vocab = wo->ne1; - strata::core::NativeHead native_head; - if (!o.native_head_gguf.empty() && !multi_gpu) { // a layer split's head is on its last stage - if (!native_head.load(o.native_head_shards, g.n_embd, n_vocab, err)) { - std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), vram_free_note().c_str()); - return 1; - } - std::fprintf(stderr, "strata generate: experimental native Q5_K head, %llu bytes\n", - (unsigned long long) native_head.weight_bytes()); - } - std::vector logits((size_t) n_vocab); - float* d_logits = nullptr; - if (cudaMalloc(&d_logits, (size_t) n_vocab * 4) != cudaSuccess) { - (void) cudaGetLastError(); - std::fprintf(stderr, "strata generate: the logits buffer failed%s\n", vram_free_note().c_str()); - return 1; - } - // Create the additional contexts after MTP has secured CUDA0 memory, but - // before the host arena maps its expert pages into their address spaces. - for (int r = 1; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0 && !early_remote) { - double free_gib = 0; - if (!strata::core::RemoteExperts::preflight(remote_dev[r], free_gib, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - std::fprintf(stderr, "strata generate: CUDA%d context ready, %.2f GiB free before expert arena registration\n", - remote_dev[r], free_gib); - } - - // ---- the CPU expert pool - // - // R2.1: the experts are loaded into a RESIDENT ARENA by default. The mmap path is kept behind - // `--mmap-experts` because it is the A/B arm, not because it is competitive. - // - // The reasoning is the review's C1 and it is now measured on both sides. `FileExpertSource` maps the 34 GB - // file, and mapped file pages are the first thing the OS reclaims; the engine's rate then depends on whether - // the standby list happens to hold `experts.bin`, which is why two consecutive runs of the SAME BINARY with - // the SAME FLAGS measured 71.97 and 34.78 ms/token in the pool (7.54 vs 12.18 tok/s). The arena is - // anonymous memory the engine owns, and the pool runs at 19.41 ms/token - 1.79x better than the warm mmap - // and 3.7x better than the cold one. - // - // IT IS NOT PINNED, and that is reported rather than hidden: `cudaHostRegister` on 31.64 GiB fails with - // "out of memory" (you cannot pin 34 of 63 GB) and the arena falls back to 4 KB anonymous pages. That is - // fine for the CPU pool - which is all that exists today - and NOT fine for Phase 3, whose cache fills and - // CPU/PCIe miss split need the GPU to DMA out of this arena. Read `note()` when that lands. - // - // The earlier "the arena does not fit" conclusion was WRONG and is worth recording: the failure was a stale - // CUDA error left set by the failed `cudaHostRegister` and read later by `gr_read`'s launch check. See the - // note in `pinned.cu`. - strata::core::FileExpertSource src; - { // the card, and whether this build has code for it (a binary built for other GPUs fails at its first kernel - // otherwise, after the whole expert arena has loaded) - before the arena starts loading - int dev = 0; - cudaDeviceProp p{}; - const bool named = cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess; - if (!named) cudaGetLastError(); - const char* name = named && p.name[0] ? p.name : "(an unnamed GPU)"; -#if defined(STRATA_USE_HIP) - std::fprintf(stderr, "strata generate: GPU %d: %s (%s)\n", dev, name, named ? p.gcnArchName : "?"); -#if defined(_WIN32) - // #468 #461: which HIP runtime was loaded - the bundled one beside the exe, or an AMD driver's System32 copy - if (HMODULE h = GetModuleHandleA("amdhip64_7.dll")) { - char path[MAX_PATH] = {}; - if (GetModuleFileNameA(h, path, MAX_PATH) > 0) - std::fprintf(stderr, "strata generate: HIP runtime %s\n", path); - } -#endif -#else - std::fprintf(stderr, "strata generate: GPU %d: %s, compute capability %d.%d%s\n", dev, name, - strata::cc_major_of(p.major), strata::cc_minor_of(p.minor), - strata::emulated_cc() ? " (STRATA_EMULATE_CC: a test mode, the card is emulated)" : ""); -#if !defined(STRATA_HIP_GFX906) // a CUDA toolkit mismatch; the gfx906 HIP build has no CUDART_VERSION - { // #542: a build whose libcudart is older than its headers (a CUDA 13 kit with a dangling libcudart.so that - // CMake resolved to the system's CUDA 12 one) reads cudaDeviceProp shifted - silently, and slowly - int rt = 0; - if (cudaRuntimeGetVersion(&rt) == cudaSuccess && rt / 1000 != CUDART_VERSION / 1000) - std::fprintf(stderr, "strata generate: WARNING: this engine was compiled with CUDA %d.%d headers but " - "loaded a CUDA %d.%d runtime (libcudart): GPU properties can read wrong and some " - "kernels go unused. Rebuild it against one toolkit (cmake -DCUDAToolkit_ROOT=, with its libcudart.so present) (#542)\n", - CUDART_VERSION / 1000, CUDART_VERSION % 1000 / 10, rt / 1000, rt % 1000 / 10); - } -#endif -#endif - const std::string e = strata::core::device_code_error(); - if (!e.empty()) { - std::fprintf(stderr, "strata generate: this engine has no code for %s (sm_%d%d): %s - rebuild it for this " - "card (setup does: START-HERE.bat --setup)\n", name, p.major, p.minor, e.c_str()); - return 1; - } - } - strata::core::ArenaExpertSource arena_src; - strata::core::ExpertSource* srcp = nullptr; - if (o.mmap_experts) { - // FileExpertSource maps the pack's experts.bin: a canonical pack has it; a native (IQ) pack has it when - // built with `tools/iq_pack.py --experts-bin` (the per-layer blob sizes of its layout, PR #121). The low-RAM - // mode: the experts come from the file through the OS cache instead of a pinned copy in RAM, for a PC whose - // GPU holds most of them but whose RAM cannot hold them all. - // CS-T: a native pack without experts.bin maps the model's GGUF shards instead (native_experts.txt's spans, - // checked against the files first) - no 30-77 GB copy of the experts on the disk - src.set_gguf(o.native_preset); - if (const char* v = std::getenv("STRATA_FETCH_THREADS"); v != nullptr && std::atoi(v) > 0) - src.set_fetch_threads(std::atoi(v)); - if (!src.open(o.pack, g.n_layers, g.n_expert, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - std::fprintf(stderr, "strata generate: experts via mmap (--mmap-experts; %s)\n", - src.gguf_mode() ? "the GGUF shards in place, no experts.bin" : "the A/B arm of R2.1"); - // #286: with a RAM budget the hottest experts live in it, and the rest are read from the drive unbuffered - // when the file cache could not keep them beside the budget anyway (a 32 GB PC) - the mapped reads' page - // faults are small requests on the critical path, and their pages take the RAM the budget was sized for - if (o.resident_budget > 0 || std::getenv("STRATA_UNBUFFERED_LOAD") != nullptr) { - std::string why; - const bool ub = src.set_unbuffered(o.resident_budget, why); - std::fprintf(stderr, "strata generate: the file tier reads %s (%s)\n", - ub ? "unbuffered" : "through the file cache", why.c_str()); - } - srcp = &src; - } else { - arena_src.set_gguf(o.native_preset); // plan v0.3 P6: a native pack may take its experts from shard 1 - // Under WDDM (Windows, WSL2), a multi-GPU run (a layer split, or remote experts) starts with at most 8 GiB of - // mapped host pages: pinning all of it into two contexts leaves WDDM refusing every later allocation - - // measured on the 5080 + 3090 rig: cudaMemGetInfo and the next cudaMalloc fail. Unregistered layers remain - // in the resident arena; their streamed experts go through the pinned staging ring. A Linux driver has no - // 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(); - 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"); - else if (pin_wddm_cap) - std::fprintf(stderr, "strata generate: multi-GPU under WDDM: at most 8 GiB of the expert arena is pinned " - "(STRATA_ARENA_PIN_GIB changes it)\n"); - if (!arena_src.open(o.pack, g.n_layers, g.n_expert, /*threads=*/6, err, pin_limit, - o.shared_expert_arena)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - if (!arena_src.ram_warning().empty()) // #633: said before the load's numbers, which it explains - std::fprintf(stderr, "strata generate: WARNING: %s\n", arena_src.ram_warning().c_str()); - std::fprintf(stderr, "strata generate: expert arena: %s\n", arena_src.note().c_str()); - std::fprintf(stderr, "strata generate: loaded %.2f GiB at %.2f GiB/s\n", - (double) strata::kernels::cpu::expert_layout().total / (1024.0 * 1024 * 1024), - arena_src.load_gib_per_second()); - // A rate under ~0.2 GiB/s is not the hardware. Task Scheduler / service contexts throttle this - // read+fill about 24x (measured 0.05 vs 1.42 GiB/s for the same binary, args and cache state; the - // scheduler's defaults - Below normal priority and a least-privilege token - were the only - // difference between the runs). Say so instead of letting the user blame the disk; see - // docs/DETAILS.md, "Running it at startup (Task Scheduler)". -#ifdef _WIN32 // a Windows launch context; elsewhere a load this slow is the disk - if (arena_src.load_gib_per_second() > 0.0 && arena_src.load_gib_per_second() < 0.2) { - std::fprintf(stderr, - "strata generate: hint: ~24x below what this hardware streams from a normal " - "launch. If Strata is started by Task Scheduler or a service, register the task " - "with Priority 4 (Normal) and 'Run with highest privileges' - the scheduler's " - "defaults (Below normal + a least-privilege token) throttle the load. See " - "docs/DETAILS.md ('Running it at startup').\n"); - } -#endif - srcp = &arena_src; - } - strata::kernels::cpu::ExpertPool pool(o.pool_workers, /*pin=*/true, /*host_works=*/!o.no_host_worker, o.pool_affinity); - if (pool.is_hybrid() && pool.affinity() != strata::kernels::cpu::PoolAffinity::All) { - const char* aff_str = pool.affinity() == strata::kernels::cpu::PoolAffinity::PCores ? "p-cores" : - pool.affinity() == strata::kernels::cpu::PoolAffinity::All ? "all" : "auto"; - std::fprintf(stderr, "strata generate: hybrid CPU detected (%d P-cores / %d threads, %d E-cores), pool workers: %d, affinity: %s\n", - pool.p_cores(), pool.p_threads(), pool.e_cores(), pool.workers(), aff_str); - } - if (o.no_ple_prefetch) strata::kernels::ple_prefetch_enable(false); - // ---- R4's slot storage. Allocated AFTER the weights and the session, so `cudaMemGetInfo` inside `open` - // sees the memory this process actually has left rather than the card's idle figure - and refuses with both - // numbers if the slots do not fit, instead of handing back a cache smaller than it was asked for. - mem_mark("the weights, the session and the drafter"); - strata::core::ExpertCache xcache; - // THE HEAD BEFORE THE CACHE: the native head and the logits are allocated above, before the expert arena (#620) - const bool auto_cache = o.expert_cache < 0; - 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; - 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 - // the predicate a local `borrow` was here, hoisted above so both cache-size branches read the same one) - const int64_t prefill_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0; - // the draft layer's head and logits are allocated when it binds, after this: 0.1.27's CJK subset made them - // ~110-180 MiB larger, and out of the reserve they left 16 GB cards below the stall line (#199) - const int64_t mtp_bind = (!o.mtp.empty() && native_head.loaded()) - ? (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) : 0; - const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind; - const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; - int64_t slots = ((int64_t) free_b - reserve) / blob; - if (!profile.empty()) slots = std::min(slots, (int64_t) profile.size()); - o.expert_cache = (int) std::max(slots, 0); - std::fprintf(stderr, "strata generate: expert cache auto: %.2f GiB free, %d MiB reserved (+%lld MiB for the " - "draft head) -> %d slots\n", - (double) free_b / 1073741824.0, o.vram_reserve_mib, (long long) (mtp_bind >> 20), o.expert_cache); - // #496: the verify window cannot start without a cache (#174), and a cache too small to lend the prompt path - // a 256-token chunk's buffers (plus the 128 slots a loan leaves; one slot without --prefill) makes it - // allocate its own on top - more than the reserve. When the default reserve leaves less than that (a 6 GB - // card), the reserve shrinks to what leaves exactly that cache, down to kSmallReserveMib: what is allocated - // after the cache - the prompt path's own part, the verify buffers, the draft head - comes out of the reserve, - // and below ~550 MiB a card ends with less than the 256 MiB the serve check calls LOW (IQ3_XXS, 32K, a 300 MiB - // reserve: 5 MiB left), so the cache gets no more than it needs, and the serve check says so plainly when it - // ends LOW (`reserve_adapted`). A reserve given on the command line is kept. No slot at all: the start - // stops, saying what is short and what makes room. A card the default reserve leaves that much is sized as - // before. - constexpr int kSmallReserveMib = 300; - const int64_t min_slots = (o.prefill_chunk > 0 && pf_borrow) - ? ((int64_t) strata::prefill::Prefill::bytes_needed(g, ss, 256) + blob - 1) / blob + 128 : 1; - if (o.expert_cache < min_slots && !o.vram_reserve_given && o.vram_reserve_mib > kSmallReserveMib) { - // the largest reserve (in MiB) that still leaves min_slots - const int64_t fit_mib = ((int64_t) free_b - mtp_bind - min_slots * blob) / (1 << 20) - prefill_mib; - if (fit_mib >= kSmallReserveMib) { - const int r = (int) std::min(fit_mib, o.vram_reserve_mib); - int64_t s2 = ((int64_t) free_b - ((((int64_t) r + prefill_mib) << 20) + mtp_bind)) / blob; - if (!profile.empty()) s2 = std::min(s2, (int64_t) profile.size()); - std::fprintf(stderr, "strata generate: expert cache auto: the %d MiB reserve leaves too few slots on " - "this card (a working cache needs %lld): a %d MiB reserve instead -> %lld slots\n", - o.vram_reserve_mib, (long long) min_slots, r, (long long) s2); - o.vram_reserve_mib = r; - o.expert_cache = (int) s2; - reserve_adapted = true; - } - } - if (o.expert_cache == 0) { - // what is short, and what makes room: the numbers a small card picks from - const int64_t at_reserve = o.vram_reserve_given ? o.vram_reserve_mib - : std::min(o.vram_reserve_mib, kSmallReserveMib); - const int64_t need_b = (((int64_t) at_reserve + prefill_mib) << 20) + mtp_bind + min_slots * blob; - const int64_t short_mib = std::max(1, (need_b - (int64_t) free_b + (1 << 20) - 1) >> 20); - const int64_t session_mib = - (int64_t) (strata::core::session_bytes(g, o.max_context, K, 0, g.n_layers) >> 20); - const std::string reserve_tip = - o.vram_reserve_given && o.vram_reserve_mib > kSmallReserveMib - ? ", a smaller --vram-reserve-mib (" + std::to_string(o.vram_reserve_mib) + " now; " + - std::to_string(kSmallReserveMib) + " is enough on a small card)" - : std::string(); - std::fprintf(stderr, "strata generate: no VRAM is left for the expert cache: it needs at least %lld slots " - "(%lld MiB), about %lld MiB more than this card has free. To make room: a smaller " - "--max-context (the session, mostly its KV cache, takes %lld MiB at %lld tokens), " - "--kv q4_0, the English draft subset (setup --draft-vocab en; the draft head takes " - "%lld MiB now)%s, images on the CPU, or close other programs that use the GPU\n", - (long long) min_slots, (long long) ((min_slots * blob) >> 20), (long long) short_mib, - (long long) session_mib, (long long) o.max_context, (long long) (mtp_bind >> 20), - reserve_tip.c_str()); - } - } else if (multi_gpu && o.expert_cache > 0) { - // an explicit cache size leaves room for the prompt path's buffers and the reserve, or the first prompt - // 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; - 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) free_b - reserve) / (int64_t) strata::kernels::cpu::expert_layout().max_blob, 0); - if (o.expert_cache > fit) { - // a WARNING that names the knob: the user asked for this size, and gets fewer slots - std::fprintf(stderr, "strata generate: WARNING: layer split: --expert-cache %d leaves no room for the " - "prompt path's buffers (%lld MiB) and the %d MiB reserve on CUDA0: %lld slots instead " - "(a smaller --vram-reserve-mib leaves more of them)\n", o.expert_cache, - (long long) prefill_mib, o.vram_reserve_mib, (long long) fit); - o.expert_cache = (int) fit; - } - } - // plan v0.3 P6: a native pack's blobs differ per layer, so with a profile its slots are sized per pair: the - // same VRAM holds ~30% more IQ3_XXS experts than slots of the largest blob would - // #369: not with --expert-cache-per-layer - its per-layer slot ranges ignore the profile rank a sized slot was cut - // for, so a layer's larger blob could land in a smaller slot: that mode keeps slots of the largest blob - std::vector sized_slots; - if (native_pack && o.expert_cache > 0 && !profile.empty() && !o.expert_cache_per_layer) { - size_t free_b = 0, total_b = 0; - 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; - size_t free_room = free_b > ((size_t) o.vram_reserve_mib << 20) ? free_b - ((size_t) o.vram_reserve_mib << 20) : 0; - const uint64_t cap = std::min(budget, (uint64_t) free_room); - for (const auto& pr : profile) { - const uint64_t b = (lay.blob_bytes(pr.first) + 255) / 256 * 256; - if (used + b > cap) break; - used += b; - sized_slots.push_back((int64_t) lay.blob_bytes(pr.first)); - } - o.expert_cache = (int) sized_slots.size(); - } - // #533: --vram-elastic: the cache in physical segments (the VRAM command resizes it between requests). One GPU, - // no helper caches, serve mode: anything else keeps the one cudaMalloc, said once. - if (o.vram_elastic) { - const char* why = !o.serve ? "it works between requests of --serve" - : multi_gpu ? "a layer split has a cache per GPU" - : std::any_of(o.expert_cache_remote.begin(), o.expert_cache_remote.end(), - [](int n) { return n > 0; }) ? "the helper caches on other GPUs" - : o.vram_segment_mib < 64 ? "--vram-segment-mib is below 64" : nullptr; -#if defined(STRATA_USE_HIP) - if (why == nullptr) why = "it is NVIDIA-only for now"; -#endif - if (why != nullptr) { - std::fprintf(stderr, "strata generate: --vram-elastic is off: %s\n", why); - o.vram_elastic = false; - } else { - xcache.set_segment_bytes(o.vram_segment_mib << 20); - } - } - if (o.expert_cache > 0) { - // keep the first `keep_bytes` of the cache (the profile's hottest experts first); false when nothing is left - auto shrink_to = [&](int64_t keep_bytes) -> bool { - if (keep_bytes <= 0) { o.expert_cache = 0; sized_slots.clear(); return false; } - if (!sized_slots.empty()) { - int64_t used = 0; - size_t keep = 0; - while (keep < sized_slots.size() && used + (sized_slots[keep] + 255) / 256 * 256 <= keep_bytes) - used += (sized_slots[keep++] + 255) / 256 * 256; - sized_slots.resize(keep); - o.expert_cache = (int) keep; - } else { - o.expert_cache = (int) (keep_bytes / (int64_t) strata::kernels::cpu::expert_layout().max_blob); - } - if (o.expert_cache <= 0) { o.expert_cache = 0; sized_slots.clear(); return false; } - return true; - }; - auto cache_bytes = [&]() -> int64_t { - if (sized_slots.empty()) return (int64_t) o.expert_cache * (int64_t) strata::kernels::cpu::expert_layout().max_blob; - int64_t b = 0; - for (const int64_t s : sized_slots) b += (s + 255) / 256 * 256; - return b; - }; - // With `--expert-cache auto` the reserve must still be free once the slots are WRITTEN: under WDDM an - // allocation is not resident until it is touched, and the free figure read before it can be ~1 GB too - // high. A cache sized from it filled the card to 0 MiB, the driver then paged, and a request that needed a - // page back while the verify graph spun on a host flag never finished. So the slots are zeroed and the - // free figure read again; while it is short of the reserve the cache is reopened smaller. - // STRATA_TEST_CACHE_FAIL=N: the first N opens fail as an out-of-commit cudaMalloc does (tests the retry) - int fake_fails = std::getenv("STRATA_TEST_CACHE_FAIL") ? std::atoi(std::getenv("STRATA_TEST_CACHE_FAIL")) : 0; - int failed = 0; - int zero_reads = 0; - for (int attempt = 0;; ++attempt) { - bool ok = false; - if (fake_fails > 0) { - --fake_fails; - err = "ExpertCache: cudaMalloc failed: out of memory (STRATA_TEST_CACHE_FAIL)"; - } else { - ok = sized_slots.empty() - ? xcache.open(o.expert_cache, g.n_layers, g.n_expert, (int64_t) strata::kernels::cpu::expert_layout().max_blob, err) - : xcache.open_sized(sized_slots, g.n_layers, g.n_expert, err); - } - if (!ok) { - // Issue #60: on Windows a device allocation is also charged to the system commit (RAM + page file), - // so with a small page file the cache's one big cudaMalloc fails while the VRAM is free. An auto - // cache then tries three quarters of the size, a few times, instead of stopping the engine. - char commit[96] = ""; -#if defined(_WIN32) - MEMORYSTATUSEX ms{}; - ms.dwLength = sizeof ms; - if (GlobalMemoryStatusEx(&ms)) - std::snprintf(commit, sizeof commit, " (Windows has %.1f GiB of commit left: RAM + page file)", - (double) ms.ullAvailPageFile / 1073741824.0); -#endif - if (auto_cache && failed < 8 && shrink_to(cache_bytes() / 4 * 3)) { - ++failed; - std::fprintf(stderr, "strata generate: %s%s; trying a smaller expert cache: %d slots\n", err.c_str(), - commit, o.expert_cache); - continue; - } - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); -#if defined(_WIN32) - std::fprintf(stderr, "strata generate: on Windows the graphics card's memory also needs room in the page " - "file: set it to \"System managed\" (System > About > Advanced system settings > " - "Performance > Advanced > Virtual memory), or lower --expert-cache\n"); -#endif - return 1; - } - if (!auto_cache || attempt - failed >= 6) break; - cudaMemset(xcache.device_slot(0), 0, (size_t) xcache.bytes()); - cudaDeviceSynchronize(); - size_t free_b = 0, total_b = 0; - 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 - // each (under WDDM the free figure read before the allocation runs ~0.7 GiB high), later ones a quarter - int64_t give = want - (int64_t) free_b + (64ll << 20); - if (free_b < ((size_t) 16 << 20)) - give = std::max(give, ++zero_reads <= 2 ? 1ll << 30 : xcache.bytes() / 4); - const int64_t keep_bytes = xcache.bytes() - give; - std::fprintf(stderr, "strata generate: only %lld MiB free once the slots are written (reserve %d MiB); " - "shrinking the expert cache\n", (long long) (free_b >> 20), o.vram_reserve_mib); - xcache.close(); - if (!shrink_to(keep_bytes)) break; - } - if (failed > 0 && o.expert_cache > 0) - std::fprintf(stderr, "strata generate: expert cache: %d slots (%.2f GiB) after %d smaller tries - a bigger " - "page file lets it use more of the free VRAM\n", - o.expert_cache, (double) xcache.bytes() / 1073741824.0, failed); - } - if (o.expert_cache > 0) { - std::fprintf(stderr, "strata generate: expert cache %lld slots, %.2f GiB of VRAM; policy is\n", - (long long) xcache.slots(), xcache.gib()); - mem_mark("opening the expert cache"); - xcache.set_per_layer_admission(o.expert_cache_per_layer); - // Round 328 warned here that the GPU hit path was wrong (tokens diverged from a cache-off run from - // token 0). That fault was fixed long since (native_expert_parity, expert_parity, the grouped kernels' - // tests), and the warning outlived it (issue #23). What remains is rounding: a GPU expert and the CPU's - // compute the same quantized expert with different float order, so a near-tie can flip. Measured teacher- - // forced on 2,557 tokens (bench/results/2026-09-27-cache-parity): 95-98% same top-1, and perplexity equal - // (on - off = -0.005 +- 0.005 nats). Neither output is more correct than the other. - std::fprintf(stderr, - "strata generate: the GPU computes the experts in the cache; it rounds differently from the CPU,\n" - " so a reply can differ slightly from a run without the cache (same quality:\n" - " bench/results/2026-09-27-cache-parity).\n"); - if (o.expert_cache_per_layer) { - int64_t lo = 0, hi = 0; - xcache.layer_slot_range(0, lo, hi); - std::fprintf(stderr, " R4.2g PER-LAYER: each layer owns %lld slots (%lld..%lld).\n", - (long long) (hi - lo), (long long) lo, (long long) (hi - 1)); - } else if (profile.empty()) { - std::fprintf(stderr, " compulsory-miss (fills with whatever the run routes first).\n"); - } else { - std::fprintf(stderr, " PROFILE, ranked by routing frequency, no eviction.\n"); - } - } - // ---- R4.2e: fill the tier from the profile. This is the only place the plan is applied, and it runs - // ONCE: with `slots` pairs and `slots` slots the cache is full when this returns, so the decode-time - // admission finds no room and every non-profiled expert stays a CPU miss. That is what makes the profile - // the policy rather than a hint. - int64_t prefilled = 0; - if (!profile.empty() && srcp != nullptr) { - // #369 (dag08): per layer, a full layer skips only its own pairs - each layer takes its hottest experts until - // its range is full (one full layer used to end the whole fill, leaving most layers empty) - const bool per_layer = xcache.per_layer_admission(); - const int64_t want = per_layer ? (int64_t) profile.size() - : std::min((int64_t) profile.size(), xcache.slots()); - // #286: an unbuffered file tier reads the pairs in batches of 64, the next batch while this one is copied - std::future ahead; - auto read_batch = [&](int64_t at) { src.prefetch_pairs(profile.data() + at, std::min(64, want - at)); }; - for (int64_t i = 0; i < want; ++i) { - if (!per_layer && srcp == &src && src.unbuffered() && i % 64 == 0) { - if (ahead.valid()) ahead.get(); - else read_batch(i); - if (i + 64 < want) ahead = std::async(std::launch::async, read_batch, i + 64); - } - const int32_t slot = xcache.admit(profile[(size_t) i].first, profile[(size_t) i].second); - if (slot == strata::core::kNotResident) { - if (per_layer) continue; - break; - } - const uint8_t* b = srcp->blob(profile[(size_t) i].first, profile[(size_t) i].second); - if (b == nullptr || !xcache.fill_slot_blocking(slot, b, err, - (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(profile[(size_t) i].first))) { - std::fprintf(stderr, "strata generate: the profile fill failed at pair %lld: %s\n", - (long long) i, err.c_str()); - return 1; - } - ++prefilled; - } - // **AND ONE SLOT IS READ BACK AND COMPARED.** A residency table that is right about indices and wrong - // about bytes produces a plausible token, which is this project's most expensive failure mode; the - // cache's own `verify_slot` is the check and it costs one 1.38 MB D2H at startup. - if (prefilled > 0 && !xcache.verify_slot(xcache.slot_of(profile[0].first, profile[0].second), - srcp->blob(profile[0].first, profile[0].second), err, - (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(profile[0].first))) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - mem_mark("the profile fill"); - std::fprintf(stderr, "strata generate: pre-filled %lld of %lld slots from the profile; slot 0 verified\n", - (long long) prefilled, (long long) (per_layer ? xcache.slots() : want)); - } - - for (auto& stp : stages) { - GpuStage& st = *stp; - const auto& lay = strata::kernels::cpu::expert_layout(); - // the drafter and the head are already allocated by now (they load above, before this), so what is left - // to hold back is the windows - and `free_b` has already lost the drafter. - const int64_t room = stage_room(st.dev, true, false); - const strata::core::OnDevice on(st.dev); - { - size_t fb = 0, tb = 0; - 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); - } - std::vector sized; - int64_t used = 0; - for (const auto& pr : st.profile) { - const int64_t b = native_pack ? ((int64_t) lay.blob_bytes(pr.first) + 255) / 256 * 256 : (int64_t) lay.max_blob; - if (used + b > room) break; - used += b; - sized.push_back((int64_t) lay.blob_bytes(pr.first)); - } - if (sized.empty() || - !(native_pack ? st.cache.open_sized(sized, g.n_layers, g.n_expert, err) - : st.cache.open((int64_t) sized.size(), g.n_layers, g.n_expert, (int64_t) lay.max_blob, err))) { - std::fprintf(stderr, "strata generate: layer split, CUDA%d expert cache: %s\n", st.dev, - sized.empty() ? "no room" : err.c_str()); - return 1; - } - int64_t filled = 0; - for (const auto& pr : st.profile) { - if (filled >= st.cache.slots()) break; - const int32_t slot = st.cache.admit(pr.first, pr.second); - if (slot == strata::core::kNotResident) break; - const uint8_t* b = srcp->blob(pr.first, pr.second); - if (b == nullptr || !st.cache.fill_slot_blocking(slot, b, err, (int64_t) lay.blob_bytes(pr.first))) { - std::fprintf(stderr, "strata generate: layer split, CUDA%d profile fill failed at pair %lld: %s\n", - st.dev, (long long) filled, err.c_str()); - return 1; - } - ++filled; - } - if (filled == 0 || !st.cache.verify_slot(st.cache.slot_of(st.profile[0].first, st.profile[0].second), - srcp->blob(st.profile[0].first, st.profile[0].second), err, - (int64_t) lay.blob_bytes(st.profile[0].first))) { - std::fprintf(stderr, "strata generate: layer split, CUDA%d expert cache: %s\n", st.dev, - filled == 0 ? "nothing filled" : err.c_str()); - return 1; - } - std::fprintf(stderr, "strata generate: layer split: CUDA%d runs layers %lld-%lld, expert cache %lld slots " - "(%.2f GiB), %lld of its %zu profiled pairs; slot 0 verified\n", - st.dev, (long long) st.lb, (long long) (st.le - 1), (long long) st.cache.slots(), st.cache.gib(), - (long long) filled, st.profile.size()); - } - if (multi_gpu) - std::fprintf(stderr, "strata generate: layer split: CUDA0 runs layers 0-%lld\n", (long long) (split_at[0] - 1)); - - std::array remote_experts; - std::unique_ptr remote_opt; - if (o.remote_expert_opt && o.expert_cache_remote[0] > 0) remote_opt = std::make_unique(); - const bool multi_remote = o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0; - if (o.expert_cache_remote[0] > 0) { - if (o.expert_cache <= 0 || profile.empty() || o.no_pool) { - std::fprintf(stderr, "strata generate: remote experts need --expert-profile, " - "a CUDA0 expert cache and the expert pool\n"); - return 2; - } - std::vector> ranked = profile; - if (!stages.empty()) { // a layer split: CUDA0's share of the profile, then the later stages' pairs no cache holds - for (auto& st : stages) - for (const auto& pr : st->profile) - if (st->cache.slot_of(pr.first, pr.second) < 0) ranked.push_back(pr); - } - if (multi_remote || std::any_of(o.expert_cache_remote_auto.begin(), o.expert_cache_remote_auto.end(), - [](bool automatic) { return automatic; })) { - // The shipped frequency profile names only 8000 of 24576 experts. Once exhausted, - // fill remaining VRAM from unranked pairs in expert-then-layer order: this spreads - // the tail across all layers instead of concentrating it on layer zero. - std::vector seen((size_t) g.n_layers * (size_t) g.n_expert, 0); - for (const auto& pair : ranked) - if (pair.first >= 0 && pair.first < g.n_layers && pair.second >= 0 && pair.second < g.n_expert) - seen[(size_t) pair.first * (size_t) g.n_expert + (size_t) pair.second] = 1; - for (int64_t e = 0; e < g.n_expert; ++e) - for (int64_t l = 0; l < g.n_layers; ++l) - if (!seen[(size_t) l * (size_t) g.n_expert + (size_t) e]) - ranked.emplace_back((int32_t) l, (int32_t) e); - std::fprintf(stderr, "strata generate: remote ranking: %zu profiled pairs, " - "%zu other pairs to fill CUDA1..3\n", profile.size(), ranked.size() - profile.size()); - } - std::array>, 3> by_device; - if (multi_remote) { - // Either stripe experts for parallel GPU work, or give each layer one - // secondary GPU to reduce switches and transfers over shared USB4. - std::vector assigned((size_t) g.n_layers * (size_t) g.n_expert, 0); - const int devices = 1 + (o.expert_cache_remote[1] > 0) + (o.expert_cache_remote[2] > 0); - int next = 0; - for (const auto& pair : ranked) { - if (pair.first < 0 || pair.first >= g.n_layers || pair.second < 0 || pair.second >= g.n_expert || - xcache.slot_of(pair.first, pair.second) >= 0) continue; - const size_t index = (size_t) pair.first * (size_t) g.n_expert + (size_t) pair.second; - if (assigned[index]) continue; - int target = -1; - if (o.expert_cache_remote_placement == "layer") { - target = pair.first % devices; - // Other layers' owners may still have room: keep scanning ranks. - if (by_device[(size_t) target].size() >= - (size_t) o.expert_cache_remote[(size_t) target]) continue; - } else { - for (int i = 0; i < devices; ++i) { - const int r = (next + i) % devices; - if (by_device[(size_t) r].size() < (size_t) o.expert_cache_remote[(size_t) r]) { - target = r; - break; - } - } - if (target < 0) break; - } - assigned[index] = 1; - by_device[(size_t) target].push_back(pair); - next = (target + 1) % devices; - } - std::fprintf(stderr, "strata generate: remote ranks %s across %d CUDA devices\n", - o.expert_cache_remote_placement == "layer" ? "grouped by layer" : "striped", devices); - } else { - by_device[0] = std::move(ranked); - } - std::vector claimed((size_t) g.n_layers * (size_t) g.n_expert, 0); - for (auto& st : stages) // a layer split: what a stage's cache holds is no helper's - for (const auto& pr : st->profile) - if (st->cache.slot_of(pr.first, pr.second) >= 0) - claimed[(size_t) pr.first * (size_t) g.n_expert + (size_t) pr.second] = 1; - for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) { - if (remote_opt) remote_opt->attach(remote_experts[(size_t) r]); - if (!remote_experts[(size_t) r].open(remote_dev[r], o.expert_cache_remote[(size_t) r], - g.n_layers, g.n_expert, by_device[(size_t) r], xcache, *srcp, claimed, err, - o.expert_cache_remote_auto[(size_t) r])) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - std::fprintf(stderr, "strata generate: CUDA%d: %lld additional experts, %.2f GiB; " - "results return through pinned host rows\n", remote_dev[r], - (long long) remote_experts[(size_t) r].resident(), remote_experts[(size_t) r].gib()); - } - } - - // ---- Multi-GPU: the second GPU's expert tier, filled with the ranked pairs the primary does not hold - strata::core::PeerExperts peer; - if (o.peer_device >= 1) { - if (profile.empty() || srcp == nullptr || o.expert_cache <= 0) { - std::fprintf(stderr, "strata generate: --peer-device needs --expert-profile and the expert cache\n"); - return 1; - } - const auto tp0 = Clock::now(); - if (!peer.open(o.peer_device, profile, xcache, *srcp, g.n_layers, g.n_expert, o.peer_reserve_mib, o.peer_slots, - err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - std::fprintf(stderr, "strata generate: peer GPU %d: %lld experts, %.2f GiB (filled in %.1f s); with the primary's " - "%lld that is %lld of %lld on the GPUs\n", o.peer_device, (long long) peer.resident(), peer.gib(), - std::chrono::duration(Clock::now() - tp0).count(), (long long) xcache.slots(), - (long long) (peer.resident() + xcache.slots()), (long long) (g.n_layers * g.n_expert)); - } - - 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; - drive.d.hit_cpu_order = o.expert_cache_cpu_order; - drive.d.split_rows = !o.no_split_rows; - drive.d.pool = &pool; - drive.d.src = srcp; - drive.d.n_expert = g.n_expert; - drive.d.jobs.resize((size_t) K); - // CS-T: routing-aware prefetch of the file tier (the GGUF in place): the next layer's router on this layer's MoE - // input predicts its experts and their pages are warmed meanwhile. It only warms pages; STRATA_LOOKAHEAD=0 is - // the A/B arm, STRATA_LOOKAHEAD_K the experts per token (default 10). - strata::core::RouterLookahead lookahead; - if (srcp == &src && src.warms() && [] { const char* v = std::getenv("STRATA_LOOKAHEAD"); return v == nullptr || std::atoi(v) != 0; }()) { - std::vector> routers((size_t) g.n_layers); - bool ok = true; - for (int64_t l = 0; l < g.n_layers && ok; ++l) { - const strata::core::WeightRef* w = wt.find("blk." + std::to_string(l) + ".ffn_gate_inp.weight"); - ok = w != nullptr && w->kind == strata::core::WeightKind::Bf16InF32 && - w->bytes == (uint64_t) (g.n_expert * g.n_embd) * 2; - if (!ok) break; - routers[(size_t) l].resize((size_t) (g.n_expert * g.n_embd)); - ok = cudaMemcpy(routers[(size_t) l].data(), w->data, (size_t) w->bytes, cudaMemcpyDeviceToHost) == cudaSuccess; - } - const char* kv = std::getenv("STRATA_LOOKAHEAD_K"); - if (ok && lookahead.start(std::move(routers), g.n_embd, g.n_expert, kv ? std::atoi(kv) : 10, &src, err)) { - drive.d.lookahead = &lookahead; - std::fprintf(stderr, "strata generate: routing-aware prefetch of the file tier on (the next layer's router)\n"); - } else { - (void) cudaGetLastError(); - std::fprintf(stderr, "strata generate: routing-aware prefetch off (%s)\n", - ok ? err.c_str() : "the routers are not BF16 in the arena"); - err.clear(); - } - } - // ---- R4.2c: THE HIT PATH. Every one of these is required for `hits_ready()`, which is all-or-nothing on - // purpose: a half-configured hit path would compute some experts twice and others not at all, and a token - // built on that is wrong rather than refused. - void* hit_scratch = nullptr; - int32_t* d_hit_slot = nullptr; - int32_t* d_hit_dst = nullptr; - uint8_t* d_hit_q8 = nullptr; - float* d_hit_q8_scale = nullptr; ///< R4.2h: the fp32 activation scales the CPU path also uses - float* d_hit_out = nullptr; - if (o.expert_cache > 0 && !o.no_pool) { - const uint64_t sb = strata::kernels::moe_hit_grouped_scratch_bytes(K, g.n_embd, strata::kernels::cpu::FF); - if (cudaMalloc(&hit_scratch, (size_t) sb) != cudaSuccess || - cudaMalloc((void**) &d_hit_slot, (size_t) K * sizeof(int32_t)) != cudaSuccess || - cudaMalloc((void**) &d_hit_dst, (size_t) K * sizeof(int32_t)) != cudaSuccess || - cudaMalloc((void**) &d_hit_q8, (size_t) (g.n_embd / 32) * 34) != cudaSuccess || - // R4.2h: the fp32 activation scales. Without this the GPU's hits use the block's fp16 `d` - // while the CPU's misses use `ActQ::scale`, which is fp32 - a 4.761e-04 relative disagreement on - // every chunk, and the reason enabling the cache changed the tokens. - cudaMalloc((void**) &d_hit_q8_scale, (size_t) (g.n_embd / 32) * sizeof(float)) != cudaSuccess || - cudaMalloc((void**) &d_hit_out, (size_t) K * g.n_embd * 4) != cudaSuccess) { - std::fprintf(stderr, "strata generate: the R4 hit path could not allocate its device buffers\n"); - return 1; - } - drive.d.cache = &xcache; - drive.d.cache_stream = main_cs; - drive.d.cache_base = (const uint8_t*) xcache.device_slot(0); - drive.d.cache_blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; - drive.d.cache_slot_off = xcache.slot_offsets(); - drive.d.hit_scratch = hit_scratch; - drive.d.parts_out = d_parts; - drive.d.hit_out = d_hit_out; - drive.d.parts_elems = K * g.n_embd; - drive.d.mixed = ss.block.mixed; - drive.d.x_q8_0_hit = d_hit_q8; - drive.d.x_q8_0_hit_scale = d_hit_q8_scale; - drive.d.d_slot = d_hit_slot; - drive.d.d_dst = d_hit_dst; - drive.d.h_slot.resize((size_t) K); - cudaEvent_t hit_done = nullptr; - if (cudaEventCreate(&hit_done) != cudaSuccess) { - std::fprintf(stderr, "strata generate: the hit path could not create its probe event\n"); - return 1; - } - drive.d.hit_done = (void*) hit_done; - drive.d.hit_poke = !o.no_hit_poke; - drive.d.h_dst.resize((size_t) K); - mem_mark("the R4 hit path"); - std::fprintf(stderr, "strata generate: R4 hit path ON - resident experts are computed on the GPU\n"); - } - // ---- P0.S8: the routing trace. Only meaningful with the pool running, because the ids arrive through - // the doorbell that the pool consumes - so `--no-pool` is refused rather than silently producing an empty - // file that would read as "the router selected nothing". - // ---- PER-STAGE TIMING. `--no-capture` only: an event recorded inside a stream capture is silently - // dropped, so a captured graph cannot carry these events and the numbers would be zeros that read as - // "every stage is free". Refusing is the fix. - if (o.stage_timing) { - if (!o.no_capture) { - std::fprintf(stderr, "strata generate: --stage-timing records CUDA events inside the layer path, " - "and an event record inside a stream capture is silently dropped. Pass " - "--no-capture as well.\n"); - return 2; - } - if (!strata::core::stage_timing_enable()) { - std::fprintf(stderr, "strata generate: stage_timing_enable failed\n"); - return 1; - } - strata::core::stage_timing_name(0, "gr_read (attn)"); - strata::core::stage_timing_name(1, "attention block"); - strata::core::stage_timing_name(2, "gr_write (attn)"); - strata::core::stage_timing_name(3, "gr_read (ffn)"); - strata::core::stage_timing_name(4, "moe_route"); - strata::core::stage_timing_name(5, "moe_finish"); - strata::core::stage_timing_name(6, "gr_write (ffn)"); - // The GDN block's internals. It is 36 of the 48 layers, 0.96 ms each, and its entire weight traffic - // is ~26 MB - so ~0.11 ms at the measured read rate. ~13 tiny latency-bound launches live in it and - // a single "attention block" number cannot say which one costs anything. - strata::core::stage_timing_name(8, " gdn: quantize x"); - strata::core::stage_timing_name(9, " gdn: qkv gemv"); - strata::core::stage_timing_name(10, " gdn: conv+silu"); - strata::core::stage_timing_name(11, " gdn: l2 norms"); - strata::core::stage_timing_name(12, " gdn: alpha/beta/gate"); - strata::core::stage_timing_name(13, " gdn: gdn_step"); - strata::core::stage_timing_name(14, " gdn: z + out_norm"); - strata::core::stage_timing_name(15, " gdn: out gemv"); - } - std::FILE* routing = nullptr; - if (!o.dump_routing.empty()) { - if (o.no_pool) { - std::fprintf(stderr, "strata generate: --dump-routing needs the expert pool; the routed ids reach " - "the host through the doorbell the pool reads. Drop --no-pool.\n"); - return 2; - } - routing = std::fopen(o.dump_routing.c_str(), "wb"); - if (routing == nullptr) { - std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_routing.c_str()); - return 1; - } - drive.routing = routing; - } - strata::core::PoolFn pool_fn = o.no_pool ? nullptr : &drive_pool; - // The hit hook rides the same switch as the pool: with no pool there is no `parts` staging to - // write into, and a hit path with nowhere to write is a wrong token rather than an error. - strata::core::HitFn hit_fn = - (o.no_pool || o.expert_cache <= 0) ? nullptr : &strata::core::expert_hit_run; - void* pool_user = o.no_pool ? nullptr : (void*) &drive; - std::fprintf(stderr, "strata generate: %d expert-pool workers%s%s\n", pool.workers(), - pool.host_works() ? " + the host thread" : "", - o.no_pool ? " (UNUSED: --no-pool)" : ""); - - // **THE MISALIGNMENT WARNING THAT STOOD HERE IS GONE, BECAUSE THE MISALIGNMENT IS FIXED.** - // - // It said the tokens were not the model's, and it was true: `session_loop` handed layer `l`'s expert - // outputs to layer `l+1`, which multiplied them by layer `l+1`'s router weights (LEDGER L100). The loop - // now runs a captured PAIR per layer - `pre[l]` ending with the router and the doorbell, then the CPU - // pool, then `post[l]` which combines those experts with THAT layer's weights - so layer `l`'s experts meet - // layer `l`'s routing. The generated ids changed the moment it landed, which is what a correctness fix - // looks like from the outside. - // - // The cost is real and is recorded rather than hidden: the window for the CPU pool is now whatever GPU - // work follows the ring inside `pre[l]`, which is the shared expert and nothing else - 0.038 ms against - // 0.514 ms of CPU work per layer. A per-layer CPU expert pool cannot be hidden behind a strictly serial - // residual chain; the CPU term is answered by Phase 3's VRAM expert cache, not by this pipeline. - - // ---- the graphs - strata::core::SessionGraphs gr; - if (!o.no_capture && !native_pack) { // plan v0.3 P6: a native pack runs verify windows only - // a layer split's CUDA0 session owns only [0, split_at[0]), so its graphs cover that range; the - // whole-model replay paths (`session_loop`, the plain generate loop) refuse rather than read another - // stage's state - a split runs its layers on the stages' verifiers (serve) or prefill stage chain - if (!strata::core::session_capture(wt, g, ss, d_parts, gr, err, /*split=*/o.gpu_stages, 0, - multi_gpu ? split_at[0] : -1)) { - std::fprintf(stderr, "strata generate: session_capture: %s\n", err.c_str()); - return 1; - } - } - - // **`--no-capture` AND THE EXPERTS ARE MUTUALLY EXCLUSIVE, AND SILENTLY SO.** - // - // The CPU expert pool is wired into `session_loop` - the host loop around the captured graphs - and - // `session_token` has no pool hook at all. So `--no-capture` did not merely change HOW the layers were - // launched: it ran the whole model with `parts` left at whatever the buffer held, which is ZERO, and the - // only symptom was `expert blobs 0` in a stats line nobody had to read. A run that silently omits the - // routed experts is not a slow measurement of this model, it is a measurement of a different model. - // - // Refusing is the fix. `--no-pool` is the explicit way to say "I want the GPU-only floor". - if (o.no_capture && !o.no_pool) { - std::fprintf(stderr, - "strata generate: --no-capture runs `session_token`, which has NO CPU expert pool hook, so " - "the routed experts would silently contribute nothing. Pass --no-pool as well if the " - "GPU-only floor is what you want.\n"); - return 2; - } - // The ladder is written by `session_loop`, and `session_token` does not touch the staging buffer at all - so - // accepting the flag there would produce a file of uninitialised memory, which reads as a wrong answer rather - // than as a mistake. `--no-capture` without `--no-pool` is already refused above, so this catches the pair. - if (o.no_capture && !o.dump_layers.empty()) { - std::fprintf(stderr, - "strata generate: --dump-layers is written by `session_loop`; `--no-capture` runs " - "`session_token` instead, which never fills the staging buffer. Drop one of the two.\n"); - return 2; - } - if (o.no_capture && !o.dump_halves.empty()) { - std::fprintf(stderr, - "strata generate: --dump-halves is CAPTURED into the layer graphs, so it needs the " - "captured path; `--no-capture` never records it. Drop one of the two.\n"); - return 2; - } - - mem_mark("the expert cache and the graphs"); - std::fprintf(stderr, "strata generate: session is up (engine %s)\n", STRATA_VERSION); - auto run_head = [&](void* stream) -> bool { - if (!native_head.loaded()) - return strata::core::lm_head(wt, g, ss.block, d_logits, stream, err); - return strata::core::lm_head_mix(wt, g, ss.block, stream, err) && - native_head.run(ss.block.mixed, d_logits, stream, err); - }; - float* d_emb = nullptr; - if (cudaMalloc(&d_emb, (size_t) g.n_embd * 4) != cudaSuccess) { - std::fprintf(stderr, "strata generate: the embedding buffer failed\n"); - return 1; - } - // **`sample_tokens` TAKES DEVICE POINTERS.** It is a kernel launch; `logits` and `out` are both read and - // written on the device. Passing `logits.data()` - the host vector - faults inside the kernel and the - // error surfaces at the NEXT synchronising call, which here was the next token's `embed_row`, reporting an - // illegal access on a weight plane. Nothing in the parameter names said device. - int* d_next = nullptr; - if (cudaMalloc(&d_next, sizeof(int)) != cudaSuccess) { - std::fprintf(stderr, "strata generate: the sampler output buffer failed\n"); - return 1; - } - - // **`R` IS BOTH THE INPUT AND THE OUTPUT, SO THE NEW TOKEN'S EMBEDDING HAS TO REPLACE THE OLD RESIDUAL.** - // At `pos == 0` that is `session_zero`, which is the reference's own initial condition - the embedding - // broadcast to all `hc` streams. After that `session_zero` would also wipe the recurrence, so the - // broadcast is done directly. Getting this wrong is invisible for exactly one token. - void* token_stream = o.stream_token ? main_cs : nullptr; - auto put_input = [&](int64_t tok, int64_t pos) -> bool { - if (!strata::core::embed_row(wt, g, tok, d_emb, token_stream, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return false; - } - if (pos == 0) { - strata::core::session_zero(ss, g, d_emb, token_stream); - } else { - for (int64_t c = 0; c < g.hc; ++c) - if (cudaMemcpyAsync(ss.R + (size_t) c * g.n_embd, d_emb, (size_t) g.n_embd * 4, - cudaMemcpyDeviceToDevice, (cudaStream_t) token_stream) != cudaSuccess) { - std::fprintf(stderr, "strata generate: the residual broadcast failed\n"); - return false; - } - } - return o.stream_token || cudaDeviceSynchronize() == cudaSuccess; - }; - - strata::kernels::SamplerParams sp; - sp.greedy = o.greedy; - sp.seed = o.seed; - sp.top_k = o.top_k; - sp.top_p = o.top_p; - sp.temperature = o.temperature; - // what this run actually samples with (the speculative loop below gets the same parameters); serve samples - // per request instead - if (!o.serve) { - if (sp.greedy || sp.temperature <= 0.0f) - std::fprintf(stderr, "strata generate: sampling greedy\n"); - else - std::fprintf(stderr, "strata generate: sampling temperature=%g top_k=%d top_p=%g seed=%llu\n", - (double) sp.temperature, sp.top_k > 0 && sp.top_k < 64 ? sp.top_k : 64, (double) sp.top_p, - (unsigned long long) sp.seed); - } - - std::FILE* dump = nullptr; - // The logits header is written WITH THE FIRST ROW, not at open: a native pack never reaches the - // per-token dump site, and a header promising rows that were never written is worse than no file. - int32_t hdr[2] = {0, 0}; - bool hdr_written = false; - const int64_t dump_positions = (int64_t) o.tokens.size() - 1 + o.max_new; - if (!o.dump_logits.empty()) { - if (dump_positions > INT32_MAX || n_vocab > INT32_MAX) { - std::fprintf(stderr, "strata generate: logits dump dimensions exceed int32\n"); - return 2; - } - dump = std::fopen(o.dump_logits.c_str(), "wb"); - if (dump == nullptr) { - std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_logits.c_str()); - return 1; - } - // **THE COUNT IS `n_prompt - 1 + max_new`, NOT `n_prompt + max_new`.** The loop writes one row per - // position from 0, and it stops once `produced` holds `max_new` tokens - and `produced` only starts - // receiving at position `n_prompt - 1`. So a 5-token prompt with `--max-new 6` writes 10 rows, and the - // header used to claim 11. A header that describes a different file from the one written is the same - // class of defect as a self-check that verifies the wrong invariant: anything reading the count instead - // of the size gets a wrong answer that looks authoritative. `tools/logits_identical.py` caught it by - // parsing the header and refusing the file. - const int32_t n_rows = (int32_t) strata::program::logits_selection::row_count(dump_positions, o.logits_stride); - hdr[0] = n_vocab; hdr[1] = n_rows; - } - - // ---- THE C1 ORACLE: ONE RESIDUAL SNAPSHOT PER LAYER PER POSITION, so the engine can be bisected against - // `llama-debug`'s `l_last-` node instead of against a single end-to-end perplexity. The buffer is - // PINNED because `session_loop` enqueues a device-to-host copy into it after every layer and the transfer - // would otherwise be staged through a pageable bounce buffer on the critical path. - std::FILE* layer_dump = nullptr; - float* layer_stage = nullptr; - const size_t layer_floats = (size_t) (g.n_layers + 1) * (size_t) g.hc * (size_t) g.n_embd; - if (!o.dump_layers.empty()) { - layer_dump = std::fopen(o.dump_layers.c_str(), "wb"); - if (layer_dump == nullptr) { - std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_layers.c_str()); - return 1; - } - if (cudaHostAlloc((void**) &layer_stage, layer_floats * sizeof(float), cudaHostAllocDefault) != - cudaSuccess) { - std::fprintf(stderr, "strata generate: cannot pin the layer-dump staging buffer\n"); - return 1; - } - } - - // ---- prefill is the DECODE PATH ONE TOKEN AT A TIME, which `phase-2-correct-engine.md:12-13` says is - // fine here: "process the prompt through the decode-style graphs in small batches; a 19K-token prompt will - // take minutes". A real batched prefill is P2.S6's other half and is not this. - // - // **THE LOOP IS `feed -> 48 layers -> head -> sample -> feed`, AND THE FIRST GENERATED TOKEN COMES FROM THE - // LAST *PROMPT* POSITION.** The first version sampled only on the decode positions, so `produced` was - // still empty when the first generated position asked for `produced.back()` - an out-of-bounds read on an - // empty vector. Teacher forcing below is what makes the distinction unnecessary to special-case: for every - // position before the last prompt one, the next input is the PROMPT's next token, and after that it is the - // sampled one. - std::vector produced; - double total_ms = 0; - double prefill_ms = 0; // positions 0 .. n_prompt-2: prompt tokens that only condition - const Clock::time_point t_start = Clock::now(); - double ttft_ms = 0; - const int64_t n_prompt = (int64_t) o.tokens.size(); - int64_t tok = o.tokens[0]; - - // ---- THE PURE-GPU MEASUREMENT. `session_replay` launches all 48 `pre` graphs back to back on one stream - // with NO host work between them - no doorbell poll, no pool, no parts copy - so what it times is the GPU - // executing the layer sequence and nothing else. It had been declared, defined and never called since the - // day it was written. - // - // **THIS IS THE MEASUREMENT THAT SAYS WHETHER THE ENGINE IS HOST-BOUND OR GPU-BOUND**, and the stage table - // cannot answer it: those events measure the interval between two marks on a stream, which includes every - // gap where the GPU sat idle waiting for the host to enqueue the next kernel. In `--no-capture` those gaps - // are the host's launch latency and they are proportional to the KERNEL COUNT rather than to any work, so - // the no-capture stage shares are shares of kernel count - which is why the attention block, with the most - // kernels, looks like 55% of the token there. - // ---- R0.9: THE PER-STAGE TABLE ON THE CAPTURED GRAPH. - if (o.gpu_stages) { - strata::core::doorbell_reset(db); - double mix = 0, ffn = 0, post = 0; - if (!strata::core::session_replay_stages(g, 0, 0, ss, gr, main_cs, mix, ffn, post, err)) { - // #610: a native (IQ) pack captures no per-layer graphs; the serve path times its window's stages - std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), - native_pack ? " - a native (IQ) pack has no per-layer graphs to replay. Its decode window's GPU " - "stages are printed per request by the serve path instead: STRATA_VERIFY_PROFILE=1 " - "STRATA_DECODE_TIMING=1 with --serve (docs/DETAILS.md, \"Where a decode window's " - "time goes\")" : ""); - return 1; - } - const int reps = 20; - double t_mix = 0, t_ffn = 0, t_post = 0; - for (int r = 0; r < reps; ++r) { - if (!strata::core::session_replay_stages(g, 0, 0, ss, gr, main_cs, mix, ffn, post, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - t_mix += mix; - t_ffn += ffn; - t_post += post; - } - const double tot = t_mix + t_ffn + t_post; - std::printf("\nper-stage GPU time on the CAPTURED graph, one token over %lld layers\n", - (long long) g.n_layers); - std::printf(" %-22s %9.3f ms/token %8.3f ms/layer %6.1f%%\n", "mixer (gr_read+attn+gr_write)", - t_mix / reps, t_mix / reps / (double) g.n_layers, 100.0 * t_mix / tot); - std::printf(" %-22s %9.3f ms/token %8.3f ms/layer %6.1f%%\n", "ffn front + router", - t_ffn / reps, t_ffn / reps / (double) g.n_layers, 100.0 * t_ffn / tot); - std::printf(" %-22s %9.3f ms/token %8.3f ms/layer %6.1f%%\n", "post (moe_finish+gr_write)", - t_post / reps, t_post / reps / (double) g.n_layers, 100.0 * t_post / tot); - std::printf(" %-22s %9.3f ms/token\n", "sum of the three", tot / reps); - - // ---- AND THE MIXER BY LAYER KIND, because 36 of the 48 are GDN and 12 are QSA and a total cannot - // separate them. Round 309's uncaptured table put GDN at 10.88 ms for 36 layers against QSA's 4.56 for - // 12, which would make the recurrence the largest single R3 target - and that table had `moe_finish` - // wrong by 4x, so the ratio is re-derived here from the captured graph rather than inherited. - { - // **ACCUMULATED OVER `reps`, NOT MEASURED ONCE AND THEN DIVIDED.** The first version called the - // per-layer replay a single time and printed `gdn / reps`, which reported GDN at 0.480 ms/token - // against a mixer total of 14.039 - a factor of exactly `reps`, and the tell was that - // 0.480 + 0.220 = 0.700 = 14.039 / 20. - std::vector acc((size_t) g.n_layers, 0.0), per; - double f2 = 0, p2 = 0; - for (int r = 0; r < reps; ++r) { - if (!strata::core::session_replay_stages_per_layer(g, 0, 0, ss, gr, main_cs, per, f2, p2, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - for (int64_t l = 0; l < g.n_layers; ++l) acc[(size_t) l] += per[(size_t) l]; - } - double gdn = 0, qsa = 0, worst = 0; - int64_t ng = 0, nq = 0, worst_l = 0; - for (int64_t l = 0; l < g.n_layers; ++l) { - const double v = acc[(size_t) l] / reps; - if (strata::core::is_qsa_layer(g, l)) { qsa += v; ++nq; } - else { gdn += v; ++ng; } - if (v > worst) { worst = v; worst_l = l; } - } - std::printf("\n the mixer by layer kind, averaged over %d runs\n", reps); - std::printf(" %-22s %9.3f ms/token %8.3f ms/layer (%lld layers)\n", "GDN layers", - gdn, ng ? gdn / (double) ng : 0.0, (long long) ng); - std::printf(" %-22s %9.3f ms/token %8.3f ms/layer (%lld layers)\n", "QSA layers", - qsa, nq ? qsa / (double) nq : 0.0, (long long) nq); - std::printf(" %-22s layer %lld at %.3f ms\n", "worst mixer layer", (long long) worst_l, worst); - std::printf(" %-22s %9.3f ms/token (must equal the mixer above)\n", "GDN + QSA", gdn + qsa); - } - - // ================================ R0.11: THE FIVE STAGES SEPARATELY ================================ - // - // Prefixes 1..5 are replayed per layer with the residual restored between them, and consecutive - // differences are the per-stage times. **THE CHECK IS THAT THE FIVE SUM TO THE THREE-GRAPH TOTAL** - - // the same independent-restatement test that caught round 320's divide-by-reps bug, and it is the only - // reason to believe a table built out of differences. - { - std::vector acc5(5, 0.0), per, s5; - for (int r = 0; r < reps; ++r) { - if (!strata::core::session_replay_stage_prefixes(g, 0, 0, ss, gr, main_cs, s5, per, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - for (int k = 0; k < 5; ++k) acc5[(size_t) k] += s5[(size_t) k]; - } - static const char* sn[5] = {"0 gr_read (attn)", "1 attention", "2 gr_write (attn)", - "3 gr_read (ffn)", "4 moe_route (router)"}; - const char* kind[5] = {"GR", "ATTN", "GR", "GR", "ROUTER"}; - double tot5 = 0, gr_ms = 0; - std::printf("\n the five stages separately, by differencing prefixes\n"); - std::printf(" %-24s %-8s %10s %10s %8s\n", "stage", "kind", "ms/token", "ms/layer", "share"); - for (int k = 0; k < 5; ++k) { - const double v = acc5[(size_t) k] / reps; - tot5 += v; - if (k != 1 && k != 4) gr_ms += v; - std::printf(" %-24s %-8s %10.3f %10.4f %7.1f%%\n", sn[k], kind[k], v, - v / (double) g.n_layers, 0.0); - } - for (int k = 0; k < 5; ++k) { - const double v = acc5[(size_t) k] / reps; - (void) v; - } - std::printf(" %-24s %-8s %10.3f\n", "sum of the five", "", tot5); - std::printf(" %-24s %-8s %10.3f <- R3.3's target is <= 3 ms for all four passes\n", - "GR passes (0,2,3)", "GR", gr_ms); - std::printf("\n the three-graph total above was %.3f ms/token; the five must account for it.\n", - tot / reps); - - // ================================ R3.5c: THE SAME TABLE, A DIFFERENT WAY ================================ - // - // The differencing table above mixes five graphs per layer, so stage 4's interval carries the launch - // of the FULL five-stage graph while stage 3's carries a four-stage one. This sweep launches ONE - // graph type per layer and nothing else, so that bias cannot exist. **If the two disagree, the - // difference IS the bias and this one is right** - and stage 4 is the router, so it is exactly the - // number that must not be wrong. - { - double sweep[6] = {0, 0, 0, 0, 0, 0}; - for (int k = 1; k <= 5; ++k) { - double acc = 0, one = 0; - for (int r = 0; r < reps; ++r) { - if (!strata::core::session_replay_stage_sweep(g, 0, 0, ss, gr, main_cs, k, one, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - acc += one; - } - sweep[k] = acc / reps; - } - std::printf("\n the same five stages, by SWEEPING each prefix back to back (no graph switching)\n"); - std::printf(" %-24s %10s %10s %12s\n", "stage", "prefix sweep", "difference", "bias"); - static const char* sn2[5] = {"0 gr_read (attn)", "1 attention", "2 gr_write (attn)", - "3 gr_read (ffn)", "4 moe_route (router)"}; - for (int k = 0; k < 5; ++k) { - const double sw = sweep[k + 1] - sweep[k]; - const double df = acc5[(size_t) k] / reps; - std::printf(" %-24s %10.3f %10.3f %11.1f%%\n", sn2[k], sw, df, - sw != 0.0 ? 100.0 * (df / sw - 1.0) : 0.0); - } - std::printf(" %-24s %10.3f (full pre, 48 layers)\n", "prefix 5 total", sweep[5]); - } - } - std::printf("\n compare `--gpu-only-full`, which replays the same work as TWO graphs per layer. The\n"); - std::printf(" three sum slightly above it because each launch carries the driver's gap.\n"); - strata::core::session_graphs_free(gr); - strata::core::doorbell_free(db); - cudaFree(d_next); - return 0; - } - - if (o.graph_only) { - strata::core::doorbell_reset(db); - // one warm pass so the first launch does not pay for page mapping - if (!strata::core::session_replay(g, 0, 0, ss, gr, main_cs, err)) { - std::fprintf(stderr, "strata generate: session_replay warm: %s\n", err.c_str()); - return 1; - } - if (cudaDeviceSynchronize() != cudaSuccess) { - std::fprintf(stderr, "strata generate: session_replay warm faulted\n"); - return 1; - } - const int reps = 20; - const Clock::time_point t0 = Clock::now(); - for (int r = 0; r < reps; ++r) { - if (!strata::core::session_replay(g, 0, 0, ss, gr, main_cs, err)) { - std::fprintf(stderr, "strata generate: session_replay: %s\n", err.c_str()); - return 1; - } - } - if (cudaDeviceSynchronize() != cudaSuccess) { - std::fprintf(stderr, "strata generate: session_replay faulted: %s\n", cudaGetErrorString(cudaGetLastError())); - return 1; - } - const double ms = std::chrono::duration(Clock::now() - t0).count() / (double) reps; - std::printf("pre graphs only %8.2f ms per token over %lld layers -> %.2f tok/s of GPU work\n", ms, - (long long) g.n_layers, ms > 0 ? 1000.0 / ms : 0.0); - std::printf(" %8.3f ms per layer\n", ms / (double) g.n_layers); - return 0; - } - - // ---- R0.3: THE TRUE PER-TOKEN GPU FLOOR. - // - // `--graph-only` above launches ONLY `gr.execs[l]`, the `pre` graphs. It omits the 48 `post` graphs - the - // shared expert, the combine and the second `gr_write` - and the LM head. Everything this project published - // as "39.8 ms pure GPU" came from that loop while being described as the whole GPU, which also made the - // "host's share = 49.4 - 39.8 = 9.6 ms" figure wrong by however much the missing work costs. See - // Memory/ERRORS.md A4/A5. - // - // This flag is what "pure GPU" has to mean, and it replaces that number everywhere. No pool runs, so - // `parts` keeps whatever the buffer holds and the timing is GPU work alone. - if (o.gpu_only_full) { - strata::core::doorbell_reset(db); - const int reps = 20; - double ms_layers = 0, ms_head = 0; - for (int r = -1; r < reps; ++r) { // r == -1 is the warm pass, not counted - const Clock::time_point t0 = Clock::now(); - if (!strata::core::session_replay_full(g, 0, 0, ss, gr, main_cs, err)) { - std::fprintf(stderr, "strata generate: session_replay_full: %s\n", err.c_str()); - return 1; - } - // The sync is INSIDE the interval on purpose: it is the wait for the GPU, so t1 - t0 is GPU time. - if (cudaStreamSynchronize((cudaStream_t) main_cs) != cudaSuccess) { - std::fprintf(stderr, "strata generate: gpu-only-full layers faulted: %s\n", - cudaGetErrorString(cudaGetLastError())); - return 1; - } - const Clock::time_point t1 = Clock::now(); - if (!run_head(main_cs)) { - std::fprintf(stderr, "strata generate: gpu-only-full lm_head: %s\n", err.c_str()); - return 1; - } - if (cudaStreamSynchronize((cudaStream_t) main_cs) != cudaSuccess) { - std::fprintf(stderr, "strata generate: gpu-only-full head faulted: %s\n", - cudaGetErrorString(cudaGetLastError())); - return 1; - } - const Clock::time_point t2 = Clock::now(); - if (r < 0) continue; - ms_layers += std::chrono::duration(t1 - t0).count(); - ms_head += std::chrono::duration(t2 - t1).count(); - } - ms_layers /= (double) reps; - ms_head /= (double) reps; - const double ms = ms_layers + ms_head; - std::printf("GPU floor pre+post+head %7.2f ms per token -> %.2f tok/s of GPU work\n", ms, - ms > 0 ? 1000.0 / ms : 0.0); - std::printf(" %8.3f ms layers (%lld x pre+post)\n", ms_layers, (long long) g.n_layers); - std::printf(" %8.3f ms per layer\n", ms_layers / (double) g.n_layers); - std::printf(" %8.3f ms LM head\n", ms_head); - return 0; - } - - // ---- **THE TOKEN PATH ALLOCATES NOTHING (P2.T10, review finding H3).** - // - // `session_loop` used to allocate its pinned staging buffer, its probe event and its host pin ON EVERY - // TOKEN, and `cudaFreeHost` at the end of each call implicitly synchronises the device - so every token - // finished with a device-wide sync nobody asked for. The scratch is created once here and reused; it also - // owns the host pin for the whole session rather than taking and releasing it per token. - strata::core::SessionLoopScratch loop_scratch; - struct ScratchFree { - strata::core::SessionLoopScratch* p; - ~ScratchFree() { if (p != nullptr) p->free(); } - } scratch_free{&loop_scratch}; - // Initialised unconditionally, including under --no-pool: the loop validates the scratch it is handed, so - // passing a default-constructed one is an error rather than a fallback. (It was, and the guard caught it - - // which is the point of the guard.) One allocation at setup either way. - if (!loop_scratch.init((size_t) K * g.n_embd * 4, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - // Plan v0.3 P3: the whole token as ONE graph whenever nothing needs a host step between the ring and post[l] - // (the VRAM expert tier and the per-layer dumps do). `--no-token-graph` keeps two graphs per layer. - strata::core::TokenGraph tgraph; - struct TokenGraphFree { - strata::core::TokenGraph* p; - ~TokenGraphFree() { strata::core::token_graph_free(*p); } - } tgraph_free{&tgraph}; - // Plan v0.3 P4: with a PROFILE-filled cache the residency is static, so the hit decision moves onto the - // device and the token graph keeps it. (A cache filled on demand still needs the per-layer host path.) - std::vector host_res; - int32_t* d_res = nullptr; - int32_t* d_hit_count = nullptr; - strata::core::TokenHits thits; - const bool graph_hits = hit_fn != nullptr && !profile.empty() && !o.no_pool; - if (graph_hits && !o.no_capture && !o.no_token_graph && layer_dump == nullptr && half_dump == nullptr) { - host_res.assign((size_t) (g.n_layers * g.n_expert), strata::core::kNotResident); - int64_t resident = 0; - for (int64_t l = 0; l < g.n_layers; ++l) - for (int64_t e = 0; e < g.n_expert; ++e) { - const int st = multi_gpu ? stage_of(l) : 0; - const int32_t slot = st > 0 ? stages[(size_t) st - 1]->cache.slot_of(l, e) : xcache.slot_of(l, e); - host_res[(size_t) (l * g.n_expert + e)] = slot; - if (slot != strata::core::kNotResident) ++resident; - } - if (cudaMalloc((void**) &d_res, host_res.size() * sizeof(int32_t)) != cudaSuccess || - cudaMalloc((void**) &d_hit_count, sizeof(int32_t)) != cudaSuccess || - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice) != cudaSuccess) { - std::fprintf(stderr, "strata generate: the device residency table could not be staged\n"); - return 1; - } - thits.d_res = d_res; - thits.n_expert = g.n_expert; - // a file-backed arena (STRATA_ARENA_MMAP): the experts no GPU holds are the ones the CPU pool and the - // prompt path will read - start reading them now instead of faulting them in 4 KB at a time mid-request - // ... and the ones a GPU holds are handed back first (STRATA_ARENA_RELEASE=0 keeps them): the fill read the - // whole arena, and left mapped and referenced it crowds every other allocation into swap - { - static const bool keep = std::getenv("STRATA_ARENA_RELEASE") && std::getenv("STRATA_ARENA_RELEASE")[0] == '0'; - rss_probe("before the release"); - uint64_t released = 0; - if (!keep) - for (size_t i = 0; i < host_res.size(); ++i) - if (host_res[i] != strata::core::kNotResident) - released += srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert); - if (released > 0) - std::fprintf(stderr, "strata generate: expert arena: %.2f GiB of VRAM-held experts handed back to the OS\n", - (double) released / (1024.0 * 1024.0 * 1024.0)); - rss_probe("after the release"); - int64_t pf = 0; - for (size_t i = 0; i < host_res.size(); ++i) - if (host_res[i] == strata::core::kNotResident) { - srcp->prefetch((int64_t) i / g.n_expert, (int64_t) i % g.n_expert); - ++pf; - } - (void) pf; - rss_probe("after the prefetch hints"); - } - for (auto& st : stages) { // layer split across GPUs: the same table on every device - const strata::core::OnDevice on(st->dev); - if (cudaMalloc((void**) &st->d_res, host_res.size() * sizeof(int32_t)) != cudaSuccess || - cudaMemcpy(st->d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice) != - cudaSuccess) { - std::fprintf(stderr, "strata generate: layer split: CUDA%d residency table failed\n", st->dev); - return 1; - } - } - thits.cache_base = drive.d.cache_base; - thits.blob = drive.d.cache_blob; - thits.d_slot = drive.d.d_slot; - thits.d_dst = drive.d.d_dst; - thits.d_count = d_hit_count; - thits.x_q8 = drive.d.x_q8_0_hit; - thits.x_scale = drive.d.x_q8_0_hit_scale; - thits.scratch = drive.d.hit_scratch; - thits.hit_out = drive.d.hit_out; - drive.d.host_res = host_res.data(); - std::fprintf(stderr, "strata generate: token graph hit path: %lld resident experts, decided on the device\n", - (long long) resident); - } - if (!o.no_capture && !o.no_token_graph && layer_dump == nullptr && half_dump == nullptr && - (hit_fn == nullptr || thits.on()) && !native_pack && !multi_gpu) { // a split's token graph cannot span stages - if (!strata::core::session_capture_token(wt, g, ss, d_parts, loop_scratch.y_miss, loop_scratch.parts_bytes, - tgraph, err, thits.on() ? &thits : nullptr)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - std::fprintf(stderr, "strata generate: token graph captured (48 layers, one launch per token)\n"); - } - - // ================================ WHERE THE HOST TERM GOES, PER TOKEN ================================ - // - // **`--gpu-only-full` MEASURES THE 48 LAYER GRAPHS AND THE LM HEAD AND NOTHING ELSE.** It never enters - // this loop, so it does not run `ple_stage_token`, `embed_row`, the whole-vocabulary logits readback, the - // NaN scan or the sampler - and `--no-pool --stats` against that floor was being read as "the per-layer - // round trip costs 12.4 ms" when an unknown part of it is per TOKEN, not per layer. That is the same error - // the review catalogued as A4/A5, one level down: a difference between two measurements attributed to a - // mechanism that neither of them isolates. - // - // Six accumulators, because the six have different fixes. Reported in `--stats` as ms/token. **The - // boundary after the layer loop is the one that matters**: without it the head's interval swallows all 48 - // layers and the report reads as "head = 50 ms", which is not a thing that can happen to 1.4 ms of GPU - // work. That is not hypothetical - it is what the first version of this printed. - double ms_ple = 0, ms_embed = 0, ms_layers = 0, ms_head = 0, ms_readback = 0, ms_sample = 0; - int64_t phase_tokens = 0; - - // ================================ plan v0.3 P8: THE PERSISTENT ENGINE (--serve) ================================ - // - // The weights, the expert arena and the VRAM tier load once; then requests arrive on stdin, one per line, - // - // GEN - // - // and each generated token is written to stdout as `T ` as soon as its verify window is done, followed by - // - // DONE - // ... (see the DONE line below; #471) - // - // Before that, `RESUME ` (n prompt tokens are not read again), `PP ` - // after every prompt chunk, and `REUSED ` once the prompt is read. (`ERR ` instead when a request - // cannot run; `STOP` ends the running request at its next step; `QUIT` ends the process.) A request continues - // from the live session or the longest conversation checkpoint its prompt starts with (see ConvCheckpoint), - // otherwise from an empty sequence (`session_zero`); the rest of the prompt goes through the batched prompt path - // and its last token through the first verify window - the path all three model files share. Decoding is greedy. - // The expert-cache slots (from the end of the cache) that hold the prompt path's buffers for a chunk, and the - // bytes from the first of them to the end. - // the share of expert bytes the arena could pin (sizes the prompt path's streamed ring and its lend cap) - if (srcp != nullptr && o.prefill_chunk > 0) { - uint64_t pinned = 0, total = 0; - const auto& lay = strata::kernels::cpu::expert_layout(); - for (int64_t l = 0; l < g.n_layers; ++l) - for (int64_t e = 0; e < g.n_expert; ++e) { - const uint64_t b = lay.blob_bytes(l); - total += b; - if (srcp->pinned(l, e)) pinned += b; - } - strata::prefill::Prefill::set_pinned_share(total ? (double) pinned / (double) total : 1.0); - } - // bytes -> slots for CUDA0's cache: exact when it knows its per-slot offsets (a native pack's blobs differ - // per layer), otherwise max_blob each. - auto slots_from_bytes = [&](uint64_t need) -> int64_t { - const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; - int64_t k = (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob); - if (xcache.slot_offsets() != nullptr) { // sized slots: take slots from the end until they hold `need` - k = 0; - while (k < xcache.slots() && - (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[xcache.slots() - k]) < need) ++k; - } - return k; - }; - // ...and its inverse, for the ring's room: the bytes the cache's last `k` slots hold. k can arrive <= 0: the - // caller's lend budget is `min(slots - 128, pct * slots / 100)` and goes negative on a cache smaller than 128 - // slots, where `slots - k` would index slot_offsets() past its end. Such a cache lends nothing, so say so. - auto bytes_from_slots = [&](int64_t k) -> uint64_t { - if (k <= 0) return 0; - if (xcache.slot_offsets() != nullptr) - return (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[xcache.slots() - k]); - return (uint64_t) k * (uint64_t) strata::kernels::cpu::expert_layout().max_blob; - }; - auto lend_slots = [&](int64_t c) -> int64_t { - return slots_from_bytes(strata::prefill::Prefill::bytes_needed(g, ss, c)); - }; - // `lend_bytes` went with the single-cache serve loan: a participant's loan is priced by `part_bytes` from its - // OWN cache, and the only other user of the old helper was the serve path's own relayout. - auto request_chunk = [](int64_t tokens, int64_t max_chunk) -> int64_t { - if (tokens <= 0 || max_chunk <= 0) return 0; - const int64_t rounded = tokens > std::numeric_limits::max() - 255 - ? tokens - : ((tokens + 255) / 256) * 256; - return std::min(max_chunk, rounded); - }; - // The prompt path's chunk and the slots it borrows for its buffers: the requested chunk halved until it fits, - // or with --prefill auto the largest chunk whose buffers take at most kAutoLendPct % of the slots (a - // lent slot's expert is streamed during the prompt and refilled after it; measured on a 12 GB card, 32K Q2_0 - // prompt: 4096 791 tok/s, 6144 878, 8192 973 with 69% of the slots lent). A request lends only what its own - // prompt needs (Prefill::relayout), so a big chunk costs short prompts nothing. 0 = none fits. - // at 8192-token chunks nearly every expert streams anyway, so a lent slot costs little: 90% when the - // copies are DMA from pinned RAM (Q2_0 8192 + a 384-slot ring: 1283 tok/s), 85% when host copies are the - // limit (lending more only streams more through them). STRATA_PREFILL_LEND_PCT overrides (tuning). - // Hoisted out of plan_lend: the serve path's per-stage loans obey the same cap, one participant at a time. - const int64_t kAutoLendPct = [] { - const char* v = std::getenv("STRATA_PREFILL_LEND_PCT"); - return v ? (int64_t) std::atoi(v) - : (int64_t) (strata::prefill::Prefill::pinned_share() >= 0.9 ? 90 : 85); - }(); - // The largest chunk --prefill auto may pick: the operator's ceiling (--prefill auto:N) and never past the - // context, but a bare `auto` always reaches 8192. 32768 and 16384 stay opt-in (#282): a 32K prompt with - // IQ2_XS (RTX 5090, 64K context) read at 5,624 tok/s in 8192-token chunks and 6,465 in one 32768 chunk (40K - // -> 18K experts streamed; an NVFP4 pack at 262K: 3,535 -> 5,201). - const int64_t auto_ceiling = std::max(8192, std::min(o.prefill_auto_max, o.max_context)); - // The auto scan used to walk a fixed list of sizes - 32768, 16384, 8192, 6144, ... - and take the first that - // fit. That list is coarse exactly where a rig needs it: this one affords ~8,700 tokens and was handed 8192, - // and 8704 is not on it. `bytes_needed` is a sum of (T x positive constant) terms plus a max of such sums, - // so it rises monotonically with T, and so does every test the scan applies - which makes the largest size - // that fits a bisection on the 256-token grid the prompt path already works on (`request_chunk` rounds up to - // it). log2(32768/256) = 7 probes, against the list's 10, at one `bytes_needed` per probe. - auto biggest_chunk = [](int64_t ceiling, auto&& ok) -> int64_t { - if (ceiling < 256) return 0; - int64_t lo = 1, hi = ceiling / 256, best = 0; // n = T / 256, and ok() is monotone in n - while (lo <= hi) { - const int64_t mid = lo + (hi - lo) / 2; - if (ok(mid * 256)) { best = mid * 256; lo = mid + 1; } else hi = mid - 1; - } - return best; - }; - auto plan_lend = [&](int64_t& chunk) -> int64_t { - auto slots_for = lend_slots; - // 0.1.39's list with its ring (also the size up to which a prompt keeps that ring under #583) - auto old_rule = [&]() -> int64_t { - strata::prefill::Prefill::set_ring_budget(0, 0); - static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256}; - for (const int64_t c : kAutoChunks) { - // above 8192: only when asked for, and only when a prompt of the context can use it - if (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue; - const int64_t k = slots_for(c); - if (k + 128 <= xcache.slots() && k * 100 <= kAutoLendPct * xcache.slots()) return c; - } - return 0; - }; - if (o.prefill_auto && !strata::prefill::Prefill::ring_bytes_enabled()) { // STRATA_RING_BYTES=0: 0.1.39's list - const int64_t c = old_rule(); - if (c > 0) { chunk = c; return slots_for(c); } - return 0; - } - if (o.prefill_auto) { // the default since 0.1.39b (#583) - // The chunk and the ring are one budget, and the ring is the better buy. Measured on this 4-way - // IQ3_S rig (2x RTX 3060 + 2x RTX 5060, CUDA3 lending at its 90% cap) on a 120K prompt: 8960 tokens - // with the 17-slot ring that leaves reads at 963 tok/s, 8192/130 at 1,008, 7168 with the ring full at - // its 199-slot byte budget at 1,000, and 5632/199 at 915. A ring slot is worth ~0.53 tok/s there and - // a chunk token ~0.05, so the 69 slots between a full ring and 8192's 130 are worth more than the - // 512 chunk tokens they cost - and once the ring IS full, shrinking the chunk further buys nothing. - // So: the largest chunk that still leaves the ring full. Only a rig where no chunk at all can afford - // one falls back to the old rule, which takes the largest chunk whose ring clears kRingMin (the - // value at or below which ring_slots() returns STAGE and streaming is off). - constexpr int64_t kRingMin = 16; - const int64_t small = old_rule(); // 0.1.39's chunk (and its ring for the prompts that fit it) - const int64_t ring_max = strata::prefill::Prefill::ring_cap_for(small); - const int64_t budget = std::min(xcache.slots() - 128, kAutoLendPct * xcache.slots() / 100); - // The room is a BYTE budget. A ring slot is max_blob bytes (`carve` lays out one whole blob each), - // while these cache slots hold their own layer's blob, which is smaller than max_blob unless the cache - // happens to hold the pack's biggest layer - on the 4-way IQ3_S rig that is 2.15 MiB a slot against a - // 2.54 MiB max_blob. Counting the room in slots priced the ring at 0.85x what it costs, `fits` then - // rejected the whole chunk instead of shrinking the ring, and the scan stopped a step short: measured - // against chunk 6144/ring 199, 8192 was refused where the same bytes afford a ~87-slot ring. - const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; - const uint64_t avail = bytes_from_slots(budget); - auto room_of = [&](int64_t t) -> int64_t { - const uint64_t nonring = strata::prefill::Prefill::bytes_needed_no_ring(g, ss, t); - return std::min((int64_t) ((avail - std::min(avail, nonring)) / (uint64_t) blob), ring_max); - }; - // `room_of` is capped at ring_max, so "the ring is full" is exactly room == ring_max, and both that - // test and the ones below it only get harder as t grows - the bisection stays valid. - auto scan = [&](int64_t floor) -> int64_t { - return biggest_chunk(auto_ceiling, [&](int64_t t) -> bool { - const int64_t room = room_of(t); - if (room < floor) return false; - strata::prefill::Prefill::set_ring_budget((int) room, 0); - // ring_slots() now returns `room` - unless STRATA_PREFILL_RING overrides it, in which case the - // chunk has to fit THAT ring, which is the pre-fix rule and the A/B arm - const int64_t k = slots_for(t); - return k + 128 <= xcache.slots() && k * 100 <= kAutoLendPct * xcache.slots(); - }); - }; - int64_t c = scan(ring_max); - if (c == 0 && ring_max < strata::prefill::Prefill::ring_default_slots()) c = scan(kRingMin); - // a prompt that fits 0.1.39's chunk keeps 0.1.39's ring (one chunk: the smaller ring only slowed it) - if (small >= c) { // the scan bought nothing: 0.1.39's choice - strata::prefill::Prefill::set_ring_budget(0, 0); - if (small > 0) { chunk = small; return slots_for(small); } - return 0; - } - strata::prefill::Prefill::set_ring_budget((int) room_of(c), small); - chunk = c; - return slots_for(c); - } - for (int64_t c = chunk; c >= 256; c /= 2) { - const int64_t k = slots_for(c); - if (k + 128 <= xcache.slots()) { chunk = c; return k; } - } - return 0; - }; - // ---- the resident RAM mode (--resident-experts / --resident-cpu-experts): the experts the GPU cache does not - // hold are copied from experts.bin into RAM once, so no decode or prompt step reads the file (the plain mmap - // mode reads them through the OS file cache, which a small-RAM PC keeps giving back to the SSD). Built here, - // after the prompt path's lend plan is known: the slots it may lend (the cache's last ones) have their experts - // streamed during a prompt and copied back after it, so those are kept in RAM too as far as RAM allows. The - // bytes are the file's bytes and the placement is the same, so the answers are the plain mmap mode's; the - // share-of-pinned figure above (which sizes the prompt path) is left as the mmap mode's for the same reason. - if (o.resident_cpu_experts) { - int64_t lend_from = -1; - if (o.prefill_chunk > 0 && !o.no_prefill_borrow && d_res != nullptr && xcache.slots() > 0) { - int64_t chunk = o.prefill_chunk; - const int64_t k = plan_lend(chunk); - if (k > 0) lend_from = xcache.slots() - k; - } - bool resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, {}, lend_from, o.resident_headroom, - o.resident_budget, &profile); - std::string whole_err; - if (!resident_ok && o.resident_soft) { - // #467: the whole complement does not fit - keep what does, the hottest by the profile, through the #403 - // budget path (sized by the RAM alone) instead of none: the misses outside it read the same file bytes - // the mmap fallback reads, so the answers are unchanged. Nothing pinned: the old fallback below. - whole_err = err; - resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, {}, -1, o.resident_headroom, - strata::core::FileExpertSource::kResidentWhatFits, &profile); - if (resident_ok) - std::fprintf(stderr, "strata generate: WARNING: the whole resident RAM mode does not fit (%s); %.2f " - "GiB of the experts the GPU does not hold, the hottest by the expert profile, are " - "kept in RAM and the rest are read from the model folder through the OS file " - "cache\n", - whole_err.c_str(), (double) src.resident_bytes() / 1073741824.0); - else - err = whole_err + "; " + err; - } - if (resident_ok) { - if (o.adapt_every > 0 && o.adapt_swaps > 0 && - !src.reserve_exchanges(std::min(o.adapt_swaps, 96), err)) { - std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str()); - return 1; - } - std::fprintf(stderr, "strata generate: resident RAM mode: %.2f GiB of experts in RAM (%s), %lld in the GPU " - "cache; adaptive swaps %s\n", - (double) src.resident_bytes() / 1073741824.0, - src.complement_pinned() ? "page-locked" : src.locked_bytes() > 0 ? "locked" : "pageable", - (long long) xcache.resident(), - o.adapt_every > 0 && o.adapt_swaps > 0 ? "exchange them with the GPU cache (no file reads)" - : "off"); - } else if (o.resident_soft) { - std::fprintf(stderr, "strata generate: WARNING: the resident RAM mode does not fit (%s); the experts the " - "GPU does not hold are read from the model folder through the OS file cache " - "(--mmap-experts), which is slower when the RAM cannot keep them\n", err.c_str()); - } else if (o.resident_budget > 0) { - // #403: a RAM budget that cannot be kept is not a reason to stop - the experts it would have held are - // read from the files like the ones outside it (pin_cache_complement leaves nothing half-built) - std::fprintf(stderr, "strata generate: WARNING: the RAM budget (--resident-budget-gib) cannot be kept (%s); " - "every expert the GPU does not hold is read from the model files through the OS file " - "cache (--mmap-experts), which is slower\n", err.c_str()); - } else { - std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str()); - return 1; - } - // #577: the unbuffered choice above was made before the RAM copy existed, from the budget asked for; now the - // copy is built, decide again from the RAM it really holds and the expert bytes outside it (on a 96 GB PC - // the file cache keeps those, and every refill after a prompt read the drive instead). Windows only: the - // unbuffered reads exist there alone -#if defined(_WIN32) - if (o.mmap_experts && o.resident_budget > 0) { - std::string why; - const bool was = src.unbuffered(); - const bool ub = src.recheck_unbuffered(why); - std::fprintf(stderr, "strata generate: the file tier reads %s%s (%s)\n", - ub ? "unbuffered" : "through the file cache", ub == was ? "" : " (changed)", why.c_str()); - } -#endif - } - if (o.serve) { - if (o.spec < 2 || o.mtp.empty() || o.prefill_chunk <= 0 || - (graph_hits && (thits.d_res == nullptr || host_res.empty()))) { - std::fprintf(stderr, "strata serve: needs --spec T, --mtp DIR and --prefill CHUNK (and a fillable " - "--expert-cache; the graphed hit path additionally needs --expert-profile P)\n"); - return 2; - } - strata::prefill::Prefill sp; - void* borrow = nullptr; - uint64_t borrow_bytes = 0; - int32_t lend_first = -1; // the first slot the prompt path may borrow (its largest chunk) - // ---- WHO BORROWS, AND FROM WHOSE CACHE. One entry per prompt path: CUDA0's (layers [0, split_at[0]), - // which is the whole model without a split) borrowing the tail of CUDA0's cache, then one per stage - // borrowing the tail of ITS OWN cache. A loan is sized by the exact `Prefill::bytes_needed` for the - // chunk, is laid out by `Prefill::relayout`, and is refilled before any window reads - so outside the - // prompt the whole cache is expert cache. THIS IS THE POINT OF THE STRUCT: the loan used to exist only - // for CUDA0, and `no_prefill_borrow` made every stage instead withhold a chunk-sized reserve from its - // cache for the entire session, which is what cost the 4-way its context (see the note at the top of the - // layer-split block). A stage may only lend the rows for ITS OWN layers: `host_res` is one table whose - // slot values are indices into whichever cache owns the layer, so a loan that marked rows by slot number - // alone would hand CUDA0 a slot belonging to another stage's cache. - struct PfPart { - strata::core::ExpertCache* cache = nullptr; - const strata::core::SessionState* ses = nullptr; - strata::prefill::Prefill* sp = nullptr; - int dev = -1; // -1: leave the device alone (CUDA0) - int64_t lb = 0, le = 0; // the layers whose rows this cache holds - the only rows it may lend - int32_t first = -1; // the first slot it may lend, for the chunk that was chosen - int32_t first_now = -1; // where its buffers are laid out now - int64_t lent_chunk = 0; - std::vector> lent; - }; - // bytes -> slots for one cache: exact when it knows its per-slot offsets (a native pack's blobs differ - // per layer), otherwise max_blob each. - auto cache_slots_for = [&](const strata::core::ExpertCache& xc, uint64_t need) -> int64_t { - if (xc.slot_offsets() != nullptr) { // sized slots: from the end until they hold `need` - int64_t k = 0; - while (k < xc.slots() && - (uint64_t) (xc.bytes() - (int64_t) xc.slot_offsets()[xc.slots() - k]) < need) ++k; - return k; - } - const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; - return (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob); - }; - auto part_slots = [&](const PfPart& p, int64_t c) -> int64_t { - return cache_slots_for(*p.cache, strata::prefill::Prefill::bytes_needed(g, *p.ses, c)); - }; - auto part_bytes = [&](const PfPart& p, int32_t first) -> uint64_t { - strata::core::ExpertCache& xc = *p.cache; - return xc.slot_offsets() ? (uint64_t) (xc.bytes() - (int64_t) xc.slot_offsets()[first]) - : (uint64_t) (xc.slots() - first) * - (uint64_t) strata::kernels::cpu::expert_layout().max_blob; - }; - // #340: a layer split whose caches already hold most experts streams few of them through the prompt path, so - // the 384-slot ring (sized for a card that streams nearly every expert of a chunk) only makes every stage's - // loan bigger: 96 slots (0.1.30's ring here) when >= 75% of the (layer, expert) pairs are resident. One GPU - // keeps the pinned-share rule. STRATA_SPLIT_RING=N: N slots on a split; 0: the pinned-share rule. - if (multi_gpu && !host_res.empty()) { - int64_t res_n = 0; - for (const int32_t r : host_res) res_n += r >= 0; - const double res_share = (double) res_n / (double) host_res.size(); - const char* v = std::getenv("STRATA_SPLIT_RING"); - const int ring = v ? std::atoi(v) : (res_share >= 0.75 ? 96 : 0); - if (ring > 0) { - strata::prefill::Prefill::set_ring_override(ring); - std::fprintf(stderr, "strata serve: layer split: %.0f%% of the experts resident, the prompt path's " - "streamed ring %d slots\n", 100.0 * res_share, ring); - } - } - std::vector pf_parts; - // a cache too small to lend the prompt path its buffers would make it allocate them on top - on a card - // whose cache already filled its reserve, that is the over-subscription the auto sizing avoids - so the - // chunk is the largest one EVERY participant can lend (a smaller chunk only reads slower) - if (pf_borrow && d_res != nullptr) { - pf_parts.push_back({&xcache, &ss, &sp, -1, 0, multi_gpu ? split_at[0] : g.n_layers, -1, -1, 0, {}}); - for (auto& st : stages) - pf_parts.push_back({&st->cache, &st->ss, &st->sp, st->dev, st->lb, st->le, -1, -1, 0, {}}); - // The two tests plan_lend makes for CUDA0 alone, one participant at a time: a loan must leave the - // 128-slot floor. The percentage cap is an AUTO-chunk rule and only the auto scan applies it - an - // explicit --prefill is the operator's number, and a loan of it only has to fit. With one participant - // (no split) this reduces to plan_lend exactly, so the single-GPU loan is unchanged from main. - auto fits_one = [&](const PfPart& p, int64_t c, bool cap) -> bool { - const int64_t k = part_slots(p, c); - if (k <= 0 || k + 128 > p.cache->slots()) return false; - return !(cap && k * 100 > kAutoLendPct * p.cache->slots()); - }; - // `only`: CUDA0's cache alone (#448: what one GPU would choose, for the log below); null: every one - auto fits = [&](int64_t c, bool cap, const PfPart* only = nullptr) -> bool { - if (only != nullptr) return fits_one(*only, c, cap); - for (const PfPart& p : pf_parts) - if (!fits_one(p, c, cap)) return false; - return true; - }; - // The chunk and the ring are one budget. The ring used to be a fixed 384 slots taken off the top - // before the chunk was considered: 506 MiB on a Q2_0 pack, where it was tuned, but 1,912 MiB on - // Q8_0, more than half an 8 GB card's cache - which is what kept that card at a 1024-token chunk. - // Size the chunk first and hand the ring what the smallest participant leaves over, up to the ring's - // byte budget - but hand it ALL of it, as in plan_lend: the ring is the better buy per byte (the - // measurements are there), so the chunk to take is the largest one that still leaves the ring full, - // not the largest one that leaves it anything at all. kRingMin is the fallback floor for a rig where - // no chunk can afford a full ring; ring_slots() returns STAGE at or below it, which turns streaming - // off. - constexpr int64_t kRingMin = 16; - // The room is a BYTE budget, as in plan_lend: a ring slot is max_blob bytes, but a cache slot holds - // its own layer's blob, which on this rig averages 0.85 of it. In slots the ring looked 18% cheaper - // than it is, and a chunk whose ring only fitted after that discount was refused outright - the scan - // stopped one step short while the chunk it did take had room to spare for the cap-sized ring. - const int64_t kBlob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; - auto ring_room = [&](int64_t c, const PfPart* only, int64_t cap) -> int64_t { - int64_t room = cap; - for (const PfPart& p : pf_parts) { - if (only != nullptr && &p != only) continue; - // clamped at 0: a cache under 128 slots has a negative lend budget, and `slots - budget` is - // then `slots`, which is off_[slots] - the end of the prefix sum, so that cache lends 0 bytes - // rather than reading one entry past its offsets - const int64_t budget = std::max(0, std::min(p.cache->slots() - 128, - kAutoLendPct * p.cache->slots() / 100)); - const uint64_t avail = part_bytes(p, (int32_t) (p.cache->slots() - budget)); - const uint64_t nonring = strata::prefill::Prefill::bytes_needed_no_ring(g, *p.ses, c); - room = std::min(room, (int64_t) ((avail - std::min(avail, nonring)) / (uint64_t) kBlob)); - } - return room; - }; - // The largest chunk on the 256-token grid that `only` - or, with null, every stage - can lend with the - // ring still at its full byte budget (ring_room is capped at ring_max, so that is room == ring_max), - // under the operator's ceiling (auto_ceiling keeps a bare `auto` at 8192, #282). Failing that, the - // largest chunk whose ring clears kRingMin. - // 0.1.39's list with its ring: the chunk it would pick, and the size up to which a prompt keeps that ring - auto old_pick = [&](const PfPart* only) -> int64_t { - strata::prefill::Prefill::set_ring_budget(0, 0); - static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256}; - for (const int64_t c : kAutoChunks) { - if (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue; // #282, as plan_lend - if (fits(c, true, only)) return c; - } - return 0; - }; - auto scan = [&](const PfPart* only) -> int64_t { - if (!o.prefill_auto) { // an explicit --prefill is the operator's number, and a loan of it only has to fit - for (int64_t c = o.prefill_chunk; c >= 256; c /= 2) - if (fits(c, false, only)) return c; - return 0; - } - if (!strata::prefill::Prefill::ring_bytes_enabled()) return old_pick(only); // STRATA_RING_BYTES=0 - const int64_t small = old_pick(only); - const int64_t cap = strata::prefill::Prefill::ring_cap_for(small); - auto probe = [&](int64_t floor) -> int64_t { - return biggest_chunk(auto_ceiling, [&](int64_t t) -> bool { - const int64_t room = ring_room(t, only, cap); - if (room < floor) return false; - strata::prefill::Prefill::set_ring_budget((int) room, 0); - // ring_slots() now returns `room` - unless STRATA_PREFILL_RING overrides it, in which - // case the chunk has to fit THAT ring, which is the pre-fix rule and the A/B arm - return fits(t, true, only); - }); - }; - int64_t c = probe(cap); - if (c == 0 && cap < strata::prefill::Prefill::ring_default_slots()) c = probe(kRingMin); - return std::max(c, small); // never a smaller chunk than 0.1.39's - }; - const int64_t chunk = scan(nullptr); - // #448: a small card in a layer split caps every stage's chunk (an RTX 3080's 512-slot cache held a - // 32 GB card's split to 512 tokens: prompts 6.2x slower, decode the same). Named when it bites, so the - // regression is one log line: each stage that cannot fund the chunk CUDA0 alone would read in. - const int64_t alone = pf_parts.size() > 1 ? scan(&pf_parts[0]) : chunk; - // both scans left the ring override on their own last trial: put it back on the chunk that won, which - // is what `init` lays out and what the INFO line reports - if (chunk > 0 && o.prefill_auto && strata::prefill::Prefill::ring_bytes_enabled()) { - // a prompt that fits 0.1.39's chunk keeps 0.1.39's ring (one chunk: the smaller ring only slowed - // it); the byte-budget ring is for the chunks past it - const int64_t small = old_pick(nullptr); - strata::prefill::Prefill::set_ring_budget( - small >= chunk ? 0 : (int) ring_room(chunk, nullptr, strata::prefill::Prefill::ring_cap_for(small)), - small); - } - if (chunk > 0 && alone > chunk) { - for (size_t i = 1; i < pf_parts.size(); ++i) { - const PfPart& p = pf_parts[i]; - if (fits_one(p, alone, o.prefill_auto)) continue; - const int dev = p.dev < 0 ? 0 : p.dev; - cudaDeviceProp prop{}; - if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess) { - (void) cudaGetLastError(); - prop.name[0] = 0; - } - const std::string pct = - o.prefill_auto ? ", and lend at most " + std::to_string(kAutoLendPct) + "%" : ""; - std::fprintf(stderr, "strata serve: WARNING: prompt chunk %lld tokens, not %lld: CUDA%d (%s) " - "has %lld expert-cache slots, and a %lld-token chunk borrows %lld of them " - "(it must keep 128%s) - prompts read slower than on CUDA0 alone (#448)\n", - (long long) chunk, (long long) alone, dev, prop.name, - (long long) p.cache->slots(), (long long) alone, - (long long) part_slots(p, alone), pct.c_str()); - // the helper tiers start at CUDA1 without a split (and are enabled in order) - std::fprintf(stderr, "strata serve: a card this small can serve as a helper expert cache " - "instead of a split stage: without --layer-split, with %s " - "(docs/SECOND_GPU.md)\n", - dev == 1 ? "--expert-cache-device1 N" : "--expert-cache-device1..3 N, in order"); - } - } - if (chunk > 0) { - if (o.prefill_auto) - // the RESOLVED ring, not the room offered: ring_slots() clamps to [16, RING_MAX] and a chunk - // under stream_all_min() gets STAGE, and STRATA_PREFILL_RING overrides both. This is what - // `init` lays out, and what the INFO line reports to the Monitor tab. - std::fprintf(stderr, "strata serve: prompt chunk auto: %lld tokens, a %lld-slot ring\n", - (long long) chunk, - (long long) strata::prefill::Prefill::ring_slots_for(chunk)); - else if (chunk != o.prefill_chunk) - std::fprintf(stderr, "strata serve: prompt chunk %lld -> %lld tokens so its buffers fit in " - "every expert cache\n", (long long) o.prefill_chunk, (long long) chunk); - o.prefill_chunk = chunk; - for (PfPart& p : pf_parts) { - p.first = (int32_t) (p.cache->slots() - part_slots(p, chunk)); - p.first_now = p.first; - } - // #340: a split stage whose card still has room for the chunk's buffers (its cache already holds - // every expert of its layers, so auto stopped short of its VRAM) keeps them as its own instead of - // borrowing cache slots: nothing of it is lent, streamed during the prompt or refilled after it. - // Room = the buffers + 1.5 GiB (the verify windows, the draft head, hipBLAS/cuBLAS workspaces made - // after this). Layer splits only - one GPU keeps its loan exactly as before. - // STRATA_SPLIT_OWN_BUFFERS=0: every stage borrows (0.1.30/0.1.31). - static const bool own_ok = [] { - const char* v = std::getenv("STRATA_SPLIT_OWN_BUFFERS"); - return v == nullptr || v[0] != '0'; - }(); - if (pf_parts.size() > 1 && own_ok) { - for (PfPart& p : pf_parts) { - const strata::core::OnDevice on(p.dev); - size_t fb = 0, tb = 0; - 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 " - "%.2f GiB free): no loan\n", p.dev < 0 ? 0 : p.dev, - (double) need / 1073741824.0, (double) fb / 1073741824.0); - p.first = -1; - p.first_now = -1; - } - } - } - lend_first = pf_parts[0].first; - borrow = lend_first >= 0 ? xcache.device_slot(lend_first) : nullptr; - borrow_bytes = lend_first >= 0 ? part_bytes(pf_parts[0], lend_first) : 0; - } else if (o.prefill_auto) { - o.prefill_chunk = 1024; // nothing lendable: small buffers of its own - } else if (pf_parts.size() > 1) { - // An explicit chunk no stage can lend in full. main falls back to the prompt path's own buffers - // here and so do we, rather than refusing to start - but say what every stage has, because a split - // stage that has to allocate these on top of a cache that already filled its VRAM will not fit, - // and `init` would otherwise report only that the buffers do not fit. - std::fprintf(stderr, "strata serve: no stage can lend the prompt path its %lld-token buffers, so " - "each stage allocates its own:\n", (long long) o.prefill_chunk); - for (const PfPart& p : pf_parts) - std::fprintf(stderr, "strata serve: CUDA%d has %lld slots, and a %lld-token chunk needs " - "the last %lld of them\n", p.dev < 0 ? 0 : p.dev, - (long long) p.cache->slots(), (long long) o.prefill_chunk, - (long long) part_slots(p, o.prefill_chunk)); - } - } else if (o.prefill_auto && d_res == nullptr) { - o.prefill_chunk = 1024; // #85: no expert cache at all (a full 8 GB card): small buffers of its own - } - bool any_loan = borrow != nullptr; - for (size_t i = 1; i < pf_parts.size(); ++i) any_loan = any_loan || pf_parts[i].first >= 0; - if (any_loan) { - if (borrow != nullptr) - std::fprintf(stderr, "strata serve: the prompt path borrows %lld CUDA0 cache slots (%.2f GiB)\n", - (long long) (xcache.slots() - lend_first), (double) borrow_bytes / 1073741824.0); - for (size_t i = 1; i < pf_parts.size(); ++i) // one loan per stage, from that stage's own cache - if (pf_parts[i].first >= 0) std::fprintf(stderr, "strata serve: CUDA%d prompt path borrows %lld of its %lld slots (%.2f GiB)\n", - pf_parts[i].dev, (long long) (pf_parts[i].cache->slots() - pf_parts[i].first), - (long long) pf_parts[i].cache->slots(), - (double) part_bytes(pf_parts[i], pf_parts[i].first) / 1073741824.0); - } else { - std::fprintf(stderr, "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)\n"); - } - rss_probe("the prompt path set up"); - // layer split across GPUs: a prompt path per stage, each handing its chunk's rows to the next. - // THE CHUNK STEPS DOWN INSTEAD OF EXITING. A split's stage caches are sized after the arena is registered, and - // the prompt path's own buffers (no loan) are not priced into them: with the whole arena pinned (#253) a - // `--prefill auto` split could stop at start with "device buffers for a chunk of 2048 tokens do not fit". A - // chunk that does not fit is tried again one size smaller, down to 512 tokens (a smaller chunk only reads slower). - auto init_prompt_paths = [&]() -> int { // 0: ready; 1: failed (err set); 2: failed with "do not fit" - for (size_t i = 0; i < stages.size(); ++i) { - GpuStage& st = *stages[i]; - st.sp.set_stage(st.lb, i + 1 < stages.size() ? st.le : -1, i + 1 < stages.size() ? &stages[i + 1]->sp : nullptr); - const strata::core::OnDevice on(st.dev); - void* sb = nullptr; // this stage's own loan, out of its own cache - uint64_t sbb = 0; - // `first < 0`: no loan was taken (nothing was lendable), so this stage allocates its own buffers - if (i + 1 < pf_parts.size() && pf_parts[i + 1].first >= 0) { - sb = st.cache.device_slot(pf_parts[i + 1].first); - sbb = part_bytes(pf_parts[i + 1], pf_parts[i + 1].first); - } - if (!st.sp.init(st.wt, g, st.ss, srcp, &st.cache, host_res.data(), o.prefill_chunk, (void*) st.stream, - err, sb, sbb)) { - err = "layer split, CUDA" + std::to_string(st.dev) + " prompt path: " + err; - return err.find("do not fit") != std::string::npos ? 2 : 1; - } - } - if (multi_gpu) sp.set_stage(0, split_at[0], &stages[0]->sp); - if (!sp.init(wt, g, ss, srcp, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes)) - return err.find("do not fit") != std::string::npos ? 2 : 1; - return 0; - }; - static constexpr int64_t kStepChunks[] = {6144, 4096, 3072, 2048, 1536, 1024, 512}; - { - // First by arithmetic: a prompt path without a loan allocates its buffers, so the chunk must leave - // headroom on that device (a chunk that fits to the last MiB left hipBLAS nothing: its GEMMs then - // failed to launch on gfx1201 and the prompt hung). `bytes_needed` is the same count `init` makes. - const int64_t kHeadroom = 512ll << 20; - auto own_fits = [&](int64_t c, int& dev_out, int64_t& need_out, int64_t& free_out) -> bool { - for (size_t i = 0; i <= stages.size(); ++i) { - const bool loan = i == 0 ? borrow != nullptr : (i < pf_parts.size() && pf_parts[i].first >= 0); - if (loan) continue; - const int dev = i == 0 ? -1 : stages[i - 1]->dev; - const strata::core::OnDevice on(dev); - size_t fb = 0, tb = 0; - 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; - return false; - } - } - return true; - }; - int dev = 0; - int64_t need = 0, fb = 0; - if (!own_fits(o.prefill_chunk, dev, need, fb)) { - int64_t c = 0; - for (const int64_t s : kStepChunks) { - int d2 = 0; - int64_t n2 = 0, f2 = 0; - if (s < o.prefill_chunk && own_fits(s, d2, n2, f2)) { c = s; break; } - } - if (c > 0) { - std::fprintf(stderr, "strata serve: a %lld-token chunk's prompt buffers need %lld MiB on CUDA%d, " - "%lld MiB free: %lld-token chunks\n", (long long) o.prefill_chunk, - (long long) (need >> 20), dev, (long long) (fb >> 20), (long long) c); - o.prefill_chunk = c; - } - } - } - for (;;) { - const int r = init_prompt_paths(); - if (r == 0) break; - int64_t next = 0; - for (const int64_t c : kStepChunks) - if (c < o.prefill_chunk) { next = c; break; } - if (r == 2 && next > 0) { - std::fprintf(stderr, "strata serve: %s: trying a %lld-token chunk\n", err.c_str(), (long long) next); - // start the prompt paths over (a failed init may hold buffers), and consume the failed allocation's - // error: it is sticky, and the next launch check would report "out of memory" for a kernel - for (auto& stp : stages) { - const strata::core::OnDevice on(stp->dev); - stp->sp.reset(); - (void) cudaGetLastError(); - } - sp.reset(); - (void) cudaGetLastError(); - o.prefill_chunk = next; - if (any_loan) { // smaller loans for the smaller chunk - for (PfPart& p : pf_parts) - if (p.first >= 0) { - p.first = (int32_t) (p.cache->slots() - part_slots(p, next)); - p.first_now = p.first; - } - lend_first = pf_parts[0].first; - borrow = lend_first >= 0 ? xcache.device_slot(lend_first) : nullptr; - borrow_bytes = lend_first >= 0 ? part_bytes(pf_parts[0], lend_first) : 0; - } - err.clear(); - continue; - } - std::fprintf(stderr, "strata serve: %s\n", err.c_str()); - if (err.find("fit") != std::string::npos) // #85: say what frees VRAM - std::fprintf(stderr, "strata serve: the GPU has too little free VRAM for the prompt path: turn images " - "off (setup: --vision no), close other programs using the GPU, use a shorter " - "context, or read prompts in smaller chunks (--prefill 512)\n"); - return 1; - } - if (peer.valid() && o.peer_prefill_rows != 0) { - const int64_t rows = o.peer_prefill_rows > 0 ? o.peer_prefill_rows : o.prefill_chunk * K / 2; - if (!sp.set_peer(&peer, rows, err)) { - std::fprintf(stderr, "strata serve: %s - the prompt path stays on the primary GPU\n", err.c_str()); - err.clear(); - } - } - // a layer split: a one-chunk prompt runs the stages one after the other, so each stage's prompt path gets the - // next stage's GPU (the last one the first's) to stream and compute a share of its experts meanwhile - if (multi_gpu && !stages.empty()) { - std::vector> paths{{&sp, 0}}; - for (const auto& st : stages) paths.emplace_back(&st->sp, st->dev); - for (size_t i = 0; i < paths.size(); ++i) { - const strata::core::OnDevice on(paths[i].second); - if (!paths[i].first->set_stage_helper(paths[(i + 1) % paths.size()].first, err)) { - std::fprintf(stderr, "strata serve: %s - stage %zu reads its prompts alone\n", err.c_str(), i); - err.clear(); - } - } - } - mem_mark("the head and the prompt path"); - // #340: STRATA_SPLIT_SMALL_OWN=S (tokens): on a layer split, every stage that borrows keeps the slots for an - // S-token chunk's buffers for the whole session (0.1.29's own buffers, carved from the tail of its cache): - // a request of at most S prompt tokens then lends, streams and refills nothing, a longer one lends (and - // refills) only the slots above them. Their experts stay non-resident (the CPU / PCIe path computes them). - // STRATA_SPLIT_SMALL_MAX=M: a request of at most M prompt tokens reads in S-token chunks on those stages - // (several chunks, still nothing lent) instead of borrowing for a bigger one. - int64_t split_small = 0, split_small_max = 0; - if (multi_gpu && !pf_parts.empty() && !host_res.empty()) { - const char* v = std::getenv("STRATA_SPLIT_SMALL_OWN"); - const int64_t S = v ? request_chunk(std::atoll(v), o.prefill_chunk) : 0; - const char* vm = std::getenv("STRATA_SPLIT_SMALL_MAX"); - split_small = S; - split_small_max = S > 0 ? std::max(S, vm ? std::atoll(vm) : S) : 0; - int64_t evicted = 0; - for (PfPart& p : pf_parts) { - if (S <= 0 || p.first < 0) continue; - const int32_t first_s = std::max(p.first, (int32_t) (p.cache->slots() - part_slots(p, S))); - int64_t n = 0; - for (int64_t l = p.lb; l < p.le; ++l) - for (int64_t ex = 0; ex < g.n_expert; ++ex) { - int32_t& r = host_res[(size_t) (l * g.n_expert + ex)]; - if (r >= first_s) { r = strata::core::kNotResident; ++n; } - } - evicted += n; - std::fprintf(stderr, "strata serve: CUDA%d keeps %lld slots for %lld-token prompts (%lld experts " - "no longer resident)\n", p.dev < 0 ? 0 : p.dev, - (long long) (p.cache->slots() - first_s), (long long) S, (long long) n); - } - if (evicted > 0) { - if (d_res != nullptr) - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); - for (auto& st : stages) { - const strata::core::OnDevice on(st->dev); - cudaMemcpy(st->d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); - } - } - } - // the penalty-history buffer: one row per verify-window row (`penalty_rows`), each the last - // `penalty_last_n` tokens that row's pick follows, -1 padded in front. Allocated once at the cap for - // the widest window; a request without penalties gets a null buffer and takes the byte-for-byte - // neutral path (no upload, no buffer handed to the sampler). - constexpr int kPenaltyWindowCap = 4096; - constexpr size_t kHistSlots = (size_t) kPenaltyWindowCap * (size_t) strata::kernels::kVerifyMaxT; - int32_t* d_hist = nullptr; - std::vector hist_stage(kHistSlots, -1); - const int hist_dev = last_st ? last_st->dev : -1; // with the head: the last stage's device - if (const strata::core::OnDevice on_h(hist_dev); cudaMalloc(&d_hist, kHistSlots * sizeof(int32_t)) != cudaSuccess) { - std::fprintf(stderr, "strata serve: the penalty-history allocation failed\n"); - return 1; - } - strata::core::Verifier ver; - strata::core::VerifyHits vh; - vh.d_res = thits.d_res; - vh.h_res = host_res.empty() ? nullptr : host_res.data(); - vh.cache_base = thits.cache_base; - vh.blob = thits.blob; - vh.slot_off = xcache.slot_offsets(); // E-6: the device plan's pointers - vh.n_slots = xcache.slots(); - // Layer split: `ver` runs layers [0, K1) and hands its residual to the next stage's verifier, and so on; the - // last runs the head. The hand-offs are mapped pinned memory, portable: a stage on another GPU reads it. - // (--split-device 0: the second stage on this GPU, sharing its weights, session and cache - the A/B.) - strata::core::Verifier ver_same; - SplitDrive split_drive; - auto stage_ver = [&](int st) -> strata::core::Verifier& { - return st == 0 ? ver : split_same ? ver_same : stages[(size_t) st - 1]->ver; - }; - auto pcie_num_of = [](double f) { return std::max(0, std::min(256, (int) (f * 256.0 + 0.5))); }; - const int n_stages = split_devs.empty() ? 1 : (int) split_at.size() + 1; - if (n_stages > 1) { - const size_t hb = (size_t) strata::kernels::kVerifyMaxT * - (size_t) strata::core::Verifier::handoff_floats(g) * sizeof(float); - std::vector hand((size_t) n_stages - 1, nullptr); - for (float*& h : hand) { - float* hh = nullptr; - if (cudaHostAlloc((void**) &hh, hb, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess || - cudaHostGetDevicePointer((void**) &h, hh, 0) != cudaSuccess) { - std::fprintf(stderr, "strata serve: the layer-split hand-off allocation failed\n"); - return 1; - } - std::memset(hh, 0, hb); - } - split_drive.base = &drive; - split_drive.n = n_stages; - for (int st = 0; st < n_stages; ++st) { - stage_ver(st).set_stage(st == 0 ? 0 : split_at[(size_t) st - 1], st + 1 < n_stages ? split_at[(size_t) st] : -1, - st == 0 ? nullptr : hand[(size_t) st - 1], st + 1 < n_stages ? hand[(size_t) st] : nullptr); - split_drive.end[st] = st + 1 < n_stages ? split_at[(size_t) st] : g.n_layers; - split_drive.cache_base[st] = drive.d.cache_base; - split_drive.cache_slot_off[st] = drive.d.cache_slot_off; - split_drive.pcie_num[st] = pcie_num_of(o.pcie_frac); - } - for (int st = 1; st < n_stages; ++st) { - bool ok_s = false; - if (split_same) { - ok_s = ver_same.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, std::max(o.spec, o.batch), err); - } else { - GpuStage& gs = *stages[(size_t) st - 1]; - const strata::core::OnDevice on(gs.dev); - strata::core::VerifyHits vs; - vs.d_res = gs.d_res; - vs.h_res = host_res.empty() ? nullptr : host_res.data(); - vs.cache_base = gs.cache.device_slot(0); - vs.blob = thits.blob; - vs.slot_off = gs.cache.slot_offsets(); - vs.n_slots = gs.cache.slots(); - gs.ver.set_remote_expert_opt(remote_opt.get()); - ok_s = gs.ver.init(gs.wt, g, gs.ss, vs, gs.head.loaded() ? &gs.head : nullptr, std::max(o.spec, o.batch), err); - split_drive.cache_base[st] = gs.cache.device_slot(0); - split_drive.cache_slot_off[st] = gs.cache.slot_offsets(); - split_drive.pcie_num[st] = pcie_num_of(gs.pcie_frac); - } - if (!ok_s) { - std::fprintf(stderr, "strata serve: layer split, stage %d: %s\n", st + 1, err.c_str()); - return 1; - } - } - for (int st = 0; st + 1 < n_stages; ++st) stage_ver(st).set_next(&stage_ver(st + 1), &split_drive); - std::string plan_s = "0-" + std::to_string(split_at[0] - 1) + " (CUDA0)"; - for (int st = 1; st < n_stages; ++st) - plan_s += ", " + std::to_string(split_at[(size_t) st - 1]) + "-" + std::to_string(split_drive.end[st] - 1) + - " (CUDA" + std::to_string(split_same ? 0 : stages[(size_t) st - 1]->dev) + ")"; - std::fprintf(stderr, "strata serve: layer split: layers %s, one hand-off per window\n", plan_s.c_str()); - } - ver.set_remote_expert_opt(remote_opt.get()); - if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, std::max(o.spec, o.batch), err) || - !mtp.bind(last_st ? last_st->wt : wt, last_st ? &last_st->head : &native_head, ver.final_R_all(), err)) { - std::fprintf(stderr, "strata serve: %s\n", err.c_str()); - return 1; - } - // each stage's verifier gets its stage's slot sessions - if (o.batch > 0) { - for (size_t k = 0; k < bslot_ss.size(); ++k) { - std::vector ptrs; - for (auto& u : bslot_ss[k]) ptrs.push_back(u.get()); - strata::core::Verifier& vk = k == 0 ? ver : stages[k - 1]->ver; - const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev); - if (!vk.init_slots(ptrs, err)) { - std::fprintf(stderr, "strata serve: --batch, stage %zu: %s\n", k + 1, err.c_str()); - return 1; - } - } - } - for (int st = 0; st < n_stages && n_stages > 1; ++st) { - split_drive.plan[st] = stage_ver(st).plan_sink(); - if (st > 0) { - stage_ver(st).set_split(o.spec_split); - stage_ver(st).set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2); - } - } - // the pool the verify windows call: with a layer split, the wrapper that routes each layer to its stage - const strata::core::PoolMultiFn win_pool_fn = n_stages > 1 ? &drive_pool_split : &drive_pool_multi; - void* const win_pool_user = n_stages > 1 ? (void*) &split_drive : (void*) &drive; - mem_mark("the verifier and the drafter's binding"); - ver.set_split(o.spec_split); - // auto: the copy kernel for every pack. DMA (the native packs' default until 0.1.13) has the host call - // cudaMemcpyAsync + cudaLaunchHostFunc inside a verify window while the GPU spins on the flag they raise; - // issue #31's thread dumps show the host stuck in that cudaMemcpyAsync on a driver lock for good. The copy - // kernel needs no host CUDA call there, and costs ~1-3% decode on IQ3_S (45.3 -> 44.8 tok/s, 8 requests). - ver.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2); - std::vector cur; - // ---- the conversation cache (see ConvCheckpoint). `live` is what the session holds right now: the tokens - // it has consumed, so a request that starts with exactly them continues without any copy. `checks` are the - // saved points; every one of them is a prefix of `live` (the loop drops the rest), so they form a chain - - // the radix cache's tree collapsed onto the one branch of history whose cells the session holds. The - // chain's root is the deepest point every request so far shared (the end of the system prompt, in - // practice); the retention policy pins it and rotates the rest LRU (conv_cache.hpp), so a NEW chat that - // shares that prefix mounts through it instead of reading it again. - std::vector live; - std::vector live_imgs, req_imgs; - bool live_ok = false; - std::vector checks; - uint64_t check_clock = 0; // the checkpoints' LRU clock; creation and every use advance it - bool cvec_cached = true; // the control vector's state the live session and the checkpoints were read with - strata::core::ConversationCache conversations( - o.prompt_cache > 0 ? (size_t) o.conversation_cache_mib * 1024 * 1024 : 0, - (size_t) o.conversation_cache_slots); - // Save only on a switch/rewind, not on each continuing request. No graph - // addresses change: all parked images live in ordinary host vectors. - auto park_current = [&](size_t held) -> bool { - if (!conversations.enabled() || !live_ok || live.empty()) return true; - // #342: before make_room evicts oldest-first, the copies of this conversation a turn back go (they hold - // nothing the outgoing chain does not, apart from the tail this conversation rewrote) - if (const size_t dropped = conversations.drop_superseded(live, live_imgs, checks, cvec_cached)) - std::fprintf(stderr, "strata serve: conversation cache: dropped %zu superseded cop%s of this " - "conversation; parked=%zu\n", dropped, dropped == 1 ? "y" : "ies", conversations.size()); - // A layer split parks one image per stage: the first stage's (with the draft layer's K/V) and one per - // later stage (without it - the draft ring is saved once). The checkpoints are MOVED apart into their - // stage parts for the capture and put back together whichever way this ends (no running state copied). - const size_t n_st = stages.size(); - // the draft layer's K/V lives on the last stage's GPU (the drafter is loaded there): with a split it is - // saved with that stage's image, under its device; stage 0's image holds none - const strata::core::QsaState* draft0 = n_st > 0 ? nullptr : &mtp.kv_state(); - auto draft_of = [&](size_t k) -> const strata::core::QsaState* { return k + 1 == n_st ? &mtp.kv_state() : nullptr; }; - strata::core::ConversationCheckpointSplit cs; - if (n_st > 0) cs = strata::core::conversation_checkpoints_split(std::move(checks), n_st); - struct MergeBack { - strata::core::ConversationCheckpointSplit& cs; std::vector& checks; bool on; - ~MergeBack() { if (on && !strata::core::conversation_checkpoints_merge(std::move(cs), checks)) checks.clear(); } - } merge_back{cs, checks, n_st > 0}; - const strata::core::ConversationView view{live, live_imgs, n_st > 0 ? cs.stage0 : checks, cvec_cached}; - auto reuse = conversations.take_reuse(); - std::vector stage_reuse = std::move(reuse.stages); - stage_reuse.resize(n_st); - reuse.stages.clear(); - // the later stages' estimates, each with its own retained K/V when it still fits - size_t stage_estimate = 0, stage_retained = 0; - for (size_t k = 0; k < n_st; ++k) { - auto& st = stages[k]; - const strata::core::OnDevice on(st->dev); - const strata::core::ConversationView view_k{live, live_imgs, cs.parts[k], cvec_cached}; - size_t b = 0; - if (!strata::core::conversation_snapshot_bytes(view_k, st->ss, g, draft_of(k), b, err)) { - std::fprintf(stderr, "strata serve: conversation cache: skip parking (stage CUDA%d: %s)\n", - st->dev, err.c_str()); - err.clear(); - return true; - } - if (!stage_reuse[k].kv.empty()) { - size_t r = 0; - if (strata::core::conversation_snapshot_capture_bytes(stage_reuse[k], view_k, st->ss, g, draft_of(k), - r, err)) { - b = r; - stage_retained += stage_reuse[k].bytes(); - } else { - stage_reuse[k] = {}; - err.clear(); - } - } - stage_estimate += b; - } - size_t estimate = 0; - if (!strata::core::conversation_snapshot_bytes(view, ss, g, draft0, estimate, err)) { - std::fprintf(stderr, "strata serve: conversation cache: skip parking (%s)\n", err.c_str()); - err.clear(); // A recoverable miss must not poison the batched draft prefill's error channel. - return true; - } - const size_t fresh_estimate = estimate; - if (!reuse.kv.empty() && !strata::core::conversation_snapshot_capture_bytes( - reuse, view, ss, g, draft0, estimate, err)) { - reuse = {}; - estimate = fresh_estimate; - err.clear(); - } - estimate += stage_estimate; - // A park carrying its own retained K/V replaces memory the cache - // already held, so capacity is make_room's call - it runs next either - // way, and put()'s accounting still bounds the budget. The with-reuse - // estimate must stay uncapped: it counts the retained buffers' - // capacity and directories, and put() charges that same true size - - // a capped figure would under-evict and overfill the budget. - if (!conversations.make_room(estimate, held)) { - std::fprintf(stderr, "strata serve: conversation cache: skip parking (snapshot %zu MiB exceeds available budget)\n", - estimate >> 20); - return true; - } - const auto t0 = Clock::now(); - try { - const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib * 1024 * 1024; - const size_t retained = reuse.bytes() + stage_retained; - const size_t additional = estimate > retained ? estimate - retained : 0; - if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), - additional, floor)) { - std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor, or telemetry unavailable)\n", - additional >> 20, (long long) o.conversation_cache_min_free_mib); - return true; - } - strata::core::SavedConversation image; - size_t reused_bytes = 0; - if (!strata::core::conversation_snapshot_save(image, view, ss, g, draft0, err, - std::move(reuse), &reused_bytes)) return false; - for (size_t k = 0; k < n_st; ++k) { // the later stages (the last one with the draft layer's K/V) - auto& st = stages[k]; - const strata::core::OnDevice on(st->dev); - if (cudaDeviceSynchronize() != cudaSuccess) { err = "stage sync failed"; return false; } - const strata::core::ConversationView view_k{live, live_imgs, cs.parts[k], cvec_cached}; - strata::core::SavedConversation part; - if (!strata::core::conversation_snapshot_save(part, view_k, st->ss, g, draft_of(k), err, - std::move(stage_reuse[k]), &reused_bytes)) - return false; - image.stage_images.push_back(std::move(part)); - } - if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), 0, floor)) { - std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM floor after capture, or telemetry unavailable)\n"); - return true; - } - const size_t snapshot_bytes = image.bytes(); - const bool stored = conversations.put(std::move(image), held); - std::fprintf(stderr, "strata serve: conversation cache: %s %zu tokens in %.1f ms; parked=%zu bytes=%zu evictions=%zu snapshot_bytes=%zu reused_kv_bytes=%zu\n", - stored ? "parked" : "skipped", live.size(), - std::chrono::duration(Clock::now() - t0).count(), - conversations.size(), conversations.bytes(), conversations.evictions(), snapshot_bytes, reused_bytes); - } catch (const std::bad_alloc&) { - // The active state has not been touched. Continue with normal - // prompt processing rather than killing a serving process. - std::fprintf(stderr, "strata serve: conversation cache: allocation failed; skip parking\n"); - } - return true; - }; - int64_t pp_total = 0, pp_from = 0, pp_next_check = 0; - // #471: the position the prompt pass has read up to (a chunk's or a window's end): what a request cancelled - // mid-read reports as read, instead of the whole prompt - int64_t pp_reached = 0; - Clock::time_point pp_t0 = Clock::now(); - auto imgs_below = [&](const std::vector& all, int64_t L) { - std::vector v; - for (const ImgKey& k : all) if (k.start < L) v.push_back(k); - return v; - }; - // a checkpoint of the state after `cur[0, L)`; false only when the copy itself failed - // A layer split's mid-prompt checkpoints: when the last stage reports a chunk, the earlier ones already read - // the next, so each stage saves its own part when IT reaches a checkpoint position (the same rule as below: - // every `prompt_cache_every` tokens from where the request resumed), and the last stage puts them together. - std::mutex part_mu; - std::map> part_at; // position -> one part per stage - std::vector part_next(stages.size() + 1, INT64_MAX); - // a checkpoint of the state after `cur[0, L)`; false only when the copy itself failed. `parts`: the stages' - // states saved at L (a split's mid-prompt checkpoint); without, they are read now (everything is at L) - // #613: why the last checkpoint_at failed - a failed device sync is the GPU itself (a hang Windows then resets), - // not the checkpoint, and the error says so - std::string ckpt_why; - auto gpu_sync_ok = [&]() -> bool { - const cudaError_t e = cudaDeviceSynchronize(); - if (e == cudaSuccess) return true; - ckpt_why = std::string(": the GPU stopped responding before it (") + cudaGetErrorString(e) + - ") - a GPU hang; on Windows the driver is then reset"; - return false; - }; - auto checkpoint_at = [&](int64_t L, std::vector* parts = nullptr) -> bool { - ckpt_why.clear(); - if (o.prompt_cache <= 0 || L < 1) return true; - for (ConvCheckpoint& c : checks) - if ((int64_t) c.ids.size() == L) { c.used = ++check_clock; return true; } - ConvCheckpoint c; - c.ids.assign(cur.begin(), cur.begin() + L); - c.imgs = imgs_below(req_imgs, L); - if (parts != nullptr) { - if (parts->size() != stages.size() + 1) return false; - c.gdn = std::move((*parts)[0].gdn); - c.ple = std::move((*parts)[0].ple); - c.tails = std::move((*parts)[0].tails); - c.dead = std::move((*parts)[0].dead); - c.block_pos = std::move((*parts)[0].block_pos); - for (size_t i = 1; i < parts->size(); ++i) c.stage_parts.push_back(std::move((*parts)[i])); - } else { - if (!gpu_sync_ok() || !checkpoint_save(c, ss, g)) return false; - for (auto& st : stages) { // a layer split's later stages: their sessions' part - const strata::core::OnDevice on(st->dev); - ConvCheckpoint part; - part.ids = c.ids; - if (!gpu_sync_ok() || !checkpoint_save(part, st->ss, g)) return false; - c.stage_parts.push_back(std::move(part)); - } - } - c.used = ++check_clock; - checks.push_back(std::move(c)); - while ((int) checks.size() > o.prompt_cache) { - std::vector stamps; - stamps.reserve(checks.size()); - for (const ConvCheckpoint& k : checks) stamps.push_back(k.used); - const size_t victim = strata::program::conv_cache::eviction_victim(stamps.data(), stamps.size(), - o.prompt_cache); - checks.erase(checks.begin() + (std::ptrdiff_t) victim); - } - return true; - }; - sp.on_chunk = [&](const float* R_rows, int64_t T, int64_t p0, std::string& e) -> bool { - std::vector nxt((size_t) T); - for (int64_t t = 0; t < T; ++t) nxt[(size_t) t] = (int32_t) cur[(size_t) (p0 + t + 1)]; - // E-9: batched through the prompt path when it can (one GPU: a layer split's drafter is on the last stage) - const bool batched = !multi_gpu && sp.draft_kv(mtp, R_rows, nxt.data(), T, p0, e); - if (!e.empty() || (!batched && !mtp.prefill(R_rows, nxt.data(), T, p0, e))) return false; - if (std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr) - std::fprintf(stderr, "strata serve: DRAFT_PREFILL path=%s mode=%d cells=%lld\n", - batched ? "batched" : "token", mtp.kv_state().kv_mode, (long long) T); - // progress for the server window: PP - const int64_t done = p0 + T; - pp_reached = done; - const double ms = std::chrono::duration(Clock::now() - pp_t0).count(); - std::printf("PP %lld %lld %.0f %.1f\n", (long long) done, (long long) pp_total, ms, - ms > 0.0 ? 1000.0 * (double) (done - pp_from) / ms : 0.0); - strata::core::progress_at("reading the prompt (batched), done up to token", done); - strata::core::progress_beat(); - std::fflush(stdout); - if (o.prompt_cache_every > 0 && done >= pp_next_check) { - bool saved = false; - if (multi_gpu) { // the stages' parts, saved when each of them read this chunk - std::vector parts; - { - std::lock_guard lk(part_mu); - auto it = part_at.find(done); - if (it != part_at.end()) parts = std::move(it->second); - part_at.erase(part_at.begin(), part_at.upper_bound(done)); - } - bool complete = parts.size() == stages.size() + 1; - for (const ConvCheckpoint& k : parts) complete = complete && !k.gdn.empty(); - saved = !complete || checkpoint_at(done, &parts); // an incomplete set: no checkpoint here - } else { - saved = checkpoint_at(done); - } - if (!saved) { e = "saving a conversation checkpoint failed" + ckpt_why; return false; } - pp_next_check = done + o.prompt_cache_every; - } - return true; - }; - if (multi_gpu) { // the batched prompt is reported by its last stage (the drafter's rows are there) - stages.back()->sp.on_chunk = std::move(sp.on_chunk); - sp.on_chunk = nullptr; - for (size_t i = 0; i <= stages.size(); ++i) { - strata::prefill::Prefill& stage_sp = i == 0 ? sp : stages[i - 1]->sp; - strata::core::SessionState& stage_ss = i == 0 ? ss : stages[i - 1]->ss; - stage_sp.on_stage_chunk = [&, i](int64_t done, std::string& e) -> bool { - if (o.prompt_cache <= 0 || o.prompt_cache_every <= 0 || done < part_next[i]) return true; - part_next[i] = done + o.prompt_cache_every; - ConvCheckpoint part; // this stage's state at `done` (its stream is synchronized) - part.ids.assign(cur.begin(), cur.begin() + done); - if (!checkpoint_save(part, stage_ss, g)) { e = "saving a checkpoint part failed"; return false; } - std::lock_guard lk(part_mu); - auto& v = part_at[done]; - v.resize(stages.size() + 1); - v[i] = std::move(part); - return true; - }; - } - } - drive.d.plan = ver.plan_sink(); - drive.d.pcie_num = std::max(0, std::min(256, (int) (o.pcie_frac * 256.0 + 0.5))); - const bool all_experts_resident = !host_res.empty() && - std::all_of(host_res.begin(), host_res.end(), [](int32_t r) { return r >= 0; }); - if (o.adapt_every > 0 && o.adapt_swaps > 0 && !all_experts_resident) - drive.d.usage.assign((size_t) (g.n_layers * g.n_expert), 0.0f); - // #477 --expert-profile-save: what the adaptive tier learned, kept across restarts (opt-in; off: `heat` stays - // empty and nothing below runs). It needs the adaptive tier's counts and the residency table. - std::vector heat; - if (!o.expert_profile_save.empty() && !all_experts_resident) { - if (drive.d.usage.empty() || host_res.empty()) - std::fprintf(stderr, "strata serve: --expert-profile-save needs the adaptive tier (--adapt-every and " - "--adapt-swaps above 0) and --expert-profile: nothing will be saved\n"); - else - heat.assign(drive.d.usage.size(), 0.0); - } - Clock::time_point profile_saved_at = Clock::now(); - cudaStream_t adapt_stream = nullptr; - if (cudaStreamCreateWithFlags(&adapt_stream, cudaStreamNonBlocking) != cudaSuccess) { - std::fprintf(stderr, "strata serve: cannot create the refill stream\n"); - return 1; - } - // plan v0.3 P6: swaps in flight - (residency index, slot) admitted when adapt_ev has completed - std::vector> pending; - std::vector pin_live; // the swaps' locked arena pages (pin_blob), unlocked once they have landed - cudaEvent_t adapt_ev = nullptr; - cudaEventCreateWithFlags(&adapt_ev, cudaEventDisableTiming); - // a layer split's later stages keep a copy of the residency table on their devices, and swap on their own - auto res_upload = [&]() { - if (d_res != nullptr) - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); - for (auto& st : stages) { - const strata::core::OnDevice on(st->dev); - cudaMemcpy(st->d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); - } - }; - auto apply_pending = [&](bool wait) { - if (peer.valid()) peer.apply_pending(wait); - if (pending.empty()) return; - if (wait) cudaEventSynchronize(adapt_ev); - else if (cudaEventQuery(adapt_ev) != cudaSuccess) return; - for (auto& st : stages) - if (st->adapt_live) { - if (wait) cudaEventSynchronize(st->adapt_ev); - else if (cudaEventQuery(st->adapt_ev) != cudaSuccess) return; - } - for (auto& st : stages) st->adapt_live = false; - unpin_blobs(pin_live); - src.commit_exchanges(); // the resident RAM mode: the evicted experts take their places in RAM - for (const auto& [i, slot] : pending) { - host_res[(size_t) i] = slot; - srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert); // in VRAM now: RAM not needed - } - pending.clear(); - res_upload(); - }; - // the VRAM tier follows the conversation (the same rule as the speculative loop below) - auto adapt = [&]() -> bool { - if (!pending.empty()) return true; // the previous swaps are still in flight - if (remote_opt && !remote_opt->adapt(drive.d.usage, host_res, pending, o.adapt_swaps, *srcp)) return false; - struct Swap { float gain; int32_t layer, in, out; }; - std::vector swaps; - std::vector> cand, vict; - for (int64_t l = 0; l < g.n_layers; ++l) { - cand.clear(); - vict.clear(); - const float* u = drive.d.usage.data() + l * g.n_expert; - const int32_t* r = host_res.data() + l * g.n_expert; - for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) { - if (r[e] < 0) { if (u[e] >= 2.0f && !(peer.valid() && peer.has(l, e)) && !(remote_opt && remote_opt->owns(l, e))) cand.emplace_back(u[e], e); } - else vict.emplace_back(u[e], e); - } - if (cand.empty() || vict.empty()) continue; - std::sort(cand.begin(), cand.end(), [](auto& a, auto& b) { return a.first > b.first; }); - const size_t nc = std::min(cand.size(), vict.size()); - std::partial_sort(vict.begin(), vict.begin() + (ptrdiff_t) nc, vict.end(), - [](auto& a, auto& b) { return a.first < b.first; }); - for (size_t i = 0; i < nc; ++i) { - if (cand[i].first < vict[i].first + 1.5f) break; - swaps.push_back({cand[i].first - vict[i].first, (int32_t) l, cand[i].second, vict[i].second}); - } - } - std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; }); - if ((int) swaps.size() > o.adapt_swaps) swaps.resize((size_t) o.adapt_swaps); - if (!resident_stage_swaps(src, xcache, host_res, g.n_expert, swaps, adapt_stream)) return false; - if (pin_blobs_on()) { // lock the batch's source pages (a file-backed arena on AMD; see pin_blobs) - std::vector> spans; - for (const Swap& s : swaps) - if (const uint8_t* b = srcp->blob(s.layer, s.in)) - spans.emplace_back((uintptr_t) b, - (uintptr_t) b + strata::kernels::cpu::expert_layout().blob_bytes(s.layer)); - pin_blobs(std::move(spans), pin_live); - } - bool main_live = false; - for (const Swap& s : swaps) { - const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out; - const int32_t slot = host_res[out]; - const uint8_t* b = srcp->blob(s.layer, s.in); - const int stn = multi_gpu ? stage_of(s.layer) : 0; // the swap stays in the layer's own cache - GpuStage* gs = stn > 0 ? stages[(size_t) stn - 1].get() : nullptr; - const strata::core::OnDevice on(gs ? gs->dev : -1); - if (slot < 0 || b == nullptr || - cudaMemcpyAsync(gs ? gs->cache.device_slot(slot) : xcache.device_slot(slot), b, - (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer), - cudaMemcpyHostToDevice, gs ? gs->adapt_stream : adapt_stream) != cudaSuccess) { - std::fprintf(stderr, "strata serve: adaptive swap copy failed (layer %d, slot %d, pinned %d): %s\n", - (int) s.layer, (int) slot, pin_live.empty() ? 0 : 1, cudaGetErrorString(cudaGetLastError())); - return false; - } - if (gs) gs->adapt_live = true; - else main_live = true; - host_res[out] = strata::core::kNotResident; // evicted now: the CPU computes it meanwhile - srcp->prefetch(s.layer, s.out); // a file-backed arena released its pages: read them back ahead - pending.emplace_back((int32_t) in, slot); // resident once the copy has landed - } - if (!swaps.empty()) cudaEventRecord(adapt_ev, adapt_stream); - (void) main_live; - for (auto& st : stages) - if (st->adapt_live) { - const strata::core::OnDevice on(st->dev); - cudaEventRecord(st->adapt_ev, st->adapt_stream); - } - // #477: the routing counted since the start (each count adds up to 1 / (1 - --adapt-decay) over its - // decays: the sum is proportional to the routing itself) - only with --expert-profile-save, else `heat` - // is empty - for (size_t i = 0; i < heat.size(); ++i) heat[i] += (double) drive.d.usage[i]; - if (peer.valid()) { // multi-GPU: the peer takes the next most-routed CPU misses - std::vector r0 = host_res; - for (const auto& [i, slot] : pending) r0[(size_t) i] = slot; // swapped into the primary already - std::string perr; - if (!peer.adapt(drive.d.usage.data(), r0.data(), - o.peer_adapt_swaps >= 0 ? o.peer_adapt_swaps : o.adapt_swaps, perr)) { - std::fprintf(stderr, "strata serve: %s\n", perr.c_str()); - return false; - } - } - for (float& v : drive.d.usage) v *= o.adapt_decay; - return true; - }; - // #477: write the learned profile (between requests and at QUIT: a prompt's lent slots are back by then). - // A swap still in flight counts as done - its expert is resident once the copy lands. `why`: for the log. - auto save_profile = [&](const char* why) { - if (heat.empty()) return; - std::vector resident(host_res.size(), 0); - for (size_t i = 0; i < host_res.size(); ++i) resident[i] = host_res[i] >= 0; - for (const auto& p : pending) resident[(size_t) p.first] = 1; - std::string e; - const auto ranked = strata::core::rank_learned_profile(g.n_layers, g.n_expert, resident, heat, - profile_loaded); - if (strata::core::write_expert_profile(o.expert_profile_save, g.n_layers, g.n_expert, ranked, e)) - std::fprintf(stderr, "strata serve: expert profile saved to %s (%s)\n", o.expert_profile_save.c_str(), - why); - else - std::fprintf(stderr, "strata serve: the expert profile was not saved: %s\n", e.c_str()); - profile_saved_at = Clock::now(); - }; - // stdin is read on its own thread, so a STOP line reaches a request that is still running (the client went - // away, or pressed Esc): the flag is checked between prompt chunks and between verify windows. - std::atomic stop_req{false}; - std::mutex in_mu; - std::condition_variable in_cv; - std::deque in_lines; - bool in_eof = false; - std::thread([&] { - // read(2) on the descriptor, not std::cin: glibc's exit() flushes every stdio stream and waits for - // stdin's lock, which getline holds while it waits for input - an engine ending on an error (every - // std::exit) would hang in exit() on Linux, and the server would wait for it forever - std::string l, buf; - char chunk[4096]; - auto getline_fd = [&](std::string& out) -> bool { - for (;;) { - const size_t nlpos = buf.find('\n'); - if (nlpos != std::string::npos) { - out.assign(buf, 0, nlpos); - buf.erase(0, nlpos + 1); - return true; - } -#if defined(_WIN32) - const int n = _read(0, chunk, (unsigned) sizeof chunk); -#else - const ssize_t n = ::read(0, chunk, sizeof chunk); - if (n < 0 && errno == EINTR) continue; -#endif - if (n <= 0) { - if (buf.empty()) return false; - out.swap(buf); - buf.clear(); - return true; - } - buf.append(chunk, (size_t) n); - } - }; - while (getline_fd(l)) { - if (!l.empty() && l.back() == '\r') l.pop_back(); - if (l == "STOP") { stop_req.store(true); continue; } - std::lock_guard lk(in_mu); - in_lines.push_back(l); - in_cv.notify_one(); - } - std::lock_guard lk(in_mu); - in_eof = true; - in_cv.notify_one(); - }).detach(); - auto next_line = [&](std::string& out) -> bool { - std::unique_lock lk(in_mu); - in_cv.wait(lk, [&] { return !in_lines.empty() || in_eof; }); - if (in_lines.empty()) return false; - out = std::move(in_lines.front()); - in_lines.pop_front(); - return true; - }; - sp.should_stop = [&] { return stop_req.load(); }; - // STRATA_TRACE=1: one stderr line per step of a request (the log shows where a request stops) - const bool trace = std::getenv("STRATA_TRACE") != nullptr; - auto tr = [&](const char* what, long long a = -1, long long b = -1) { - if (!trace) return; - std::fprintf(stderr, "strata trace: %s %lld %lld\n", what, a, b); - std::fflush(stderr); - }; - { - // 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; - 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); - if (free_mib >= 256) { - std::fprintf(stderr, "strata serve: %lld MiB of VRAM free with everything loaded\n", (long long) free_mib); - rss_probe("serving"); - } else if (reserve_adapted) { - // #496: the reserve was already lowered to make the cache fit - a bigger one would leave it no room - std::fprintf(stderr, "strata serve: WARNING: %lld MiB of VRAM free with everything loaded - this card " - "only just fits the model (the VRAM reserve was lowered to %d MiB so the expert " - "cache fits): requests may stall. Close other programs that use the GPU, or lower " - "--max-context\n", (long long) free_mib, o.vram_reserve_mib); - } else { - std::fprintf(stderr, "strata serve: %lld MiB of VRAM free with everything loaded - LOW: requests may stall;" - " add --vram-reserve-mib %lld to the config's args (or lower --max-context)\n", - (long long) free_mib, (long long) (o.vram_reserve_mib + 512 - free_mib)); - } - } - // 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; - 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 - // disjoint by construction (remote_experts.cpp skips any pair a stage already claimed), so they add. - const int64_t slots_primary = (int64_t) xcache.slots(); - const int64_t mib_primary = (int64_t) (xcache.bytes() >> 20); - int64_t slots_all = slots_primary, mib_all = mib_primary; - for (const auto& st : stages) { - slots_all += (int64_t) st->cache.slots(); - mib_all += (int64_t) (st->cache.bytes() >> 20); - } - for (int r = 0; r < 3; ++r) - if (o.expert_cache_remote[(size_t) r] > 0) { - slots_all += remote_experts[(size_t) r].resident(); - mib_all += (int64_t) (remote_experts[(size_t) r].gib() * 1024.0); - } - std::printf("INFO context=%lld kv=%s kv_resident=%lld expert_slots=%lld expert_cache_mib=%lld " - "expert_slots_primary=%lld expert_cache_primary_mib=%lld spec=%d " - "mtp_max=%d lookup=%d vram_free_mib=%lld cvec=%s arena_mib=%lld pool_workers=%d pcie_frac=%.2f " - "spec_min_p=%.2f conversation_cache_mib=%lld conversation_cache_slots=%d " - "conversation_cache_min_free_mib=%lld tail_role_token=%lld vram_elastic=%d%s engine=" STRATA_VERSION "\n", - (long long) o.max_context, o.kv.c_str(), - (long long) (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1 - ? ss.qsa_states[ss.qsa_primary()].n_slots * 4 : 0), - (long long) slots_all, (long long) mib_all, - (long long) slots_primary, (long long) mib_primary, - o.spec, o.mtp_max_t, - o.suffix_draft, (long long) (free_b >> 20), cvec_summary.c_str(), - (long long) ((o.mmap_experts ? src.resident_bytes() : strata::kernels::cpu::expert_layout().total) >> 20), - pool.workers(), o.pcie_frac, - o.spec_min_p, (long long) o.conversation_cache_mib, o.conversation_cache_slots, - (long long) o.conversation_cache_min_free_mib, (long long) o.tail_role_token, xcache.segmented() ? 1 : 0, - o.batch > 0 ? (" batch_slots=" + std::to_string(o.batch) + - " slot_cache=" + std::to_string(o.prompt_cache > 0 ? 1 : 0)).c_str() : ""); - } - // issue #29: a request whose heartbeat (tokens, prompt chunks, verify windows) stops for this long is stuck on - // a flag nobody will raise - end the engine with where it was, so the server starts it again instead of the - // GPU spinning forever. STRATA_WATCHDOG_S=0 turns it off. Issue #31: before it does, it reports what every - // part was doing (stall_report), so one occurrence says where the wait is. - { - const char* ws = std::getenv("STRATA_WATCHDOG_S"); - const int limit = ws ? std::atoi(ws) : 60; // one step (a prompt layer, a verify window) takes seconds - if (limit > 0) - std::thread([limit] { - strata::core::Progress& p = strata::core::progress(); - uint64_t last = p.beats.load(), ticks_at = p.ticks.load(); - auto since = std::chrono::steady_clock::now(); - for (;;) { - std::this_thread::sleep_for(std::chrono::seconds(1)); - const auto now = std::chrono::steady_clock::now(); - const uint64_t b = p.beats.load(); - if (!p.busy.load() || b != last) { last = b; ticks_at = p.ticks.load(); since = now; continue; } - if (now - since < std::chrono::seconds(limit)) continue; - std::fprintf(stderr, "strata serve: no progress for %d s during a request (%s) - stopping " - "the engine so the server starts it again (issue #29)\n", - limit, stage_text().c_str()); - stall_report(stderr, p.ticks.load() - ticks_at); - strata::core::release_gpu_waits(stderr); // #267: no spin kernel outlives the process - std::fflush(stderr); - std::abort(); - } - }).detach(); - } - std::printf("READY %lld stop\n", (long long) o.max_context); // "stop": this engine honours STOP - std::fflush(stdout); - std::string line; - int64_t rounds = 0; - const int S = o.spec; - const int S_mtp = o.mtp_max_t > 0 ? std::min(o.mtp_max_t, S) : S; // the MTP's windows; suffixes go up to S - if (S_mtp < S) mtp.set_max_drafts(S_mtp - 1); - strata::spec::SuffixDrafter sfx(std::max(1, o.suffix_draft), 64, (size_t) o.max_context + 4096); - strata::spec::DraftPolicy policy(S); // MTP or lookup window, learned over the whole process - // The vision path (--vision): GENI carries images. The file is one - // or more strata-vision records (int32 'SVE1', n, nx, ny, n_embd, then n x n_embd floats) in prompt order; - // each image's rows go to its run of <|image_pad|> tokens, whose M-RoPE positions are mtmd's: t = p, - // h = p + y, w = p + x, and the text after the image continues at p + max(nx, ny). - constexpr int64_t kImagePad = 248056; // qwen4exp.ple.image_token_id: the PLE hash reads it for image cells - bool mrope_identity = true; - std::vector img_rows; - std::vector row_ptr; - // ---- #533: VRAM , between requests, only with --vram-elastic. It shrinks the expert cache - // until that much VRAM is free for other programs (a game, a CAD session), or grows it back towards its full - // size when more than that is free. Never on its own: only this command (the server's POST /v1/vram) moves - // it. A shrink gives back the cache's LAST segments: the experts in their slots become CPU misses, as any - // expert outside the cache is (no output changes beyond what a smaller cache decodes), the prompt path's - // loan moves down to the end of what is left (a smaller chunk when it no longer fits). A grow maps them - // again and puts each slot's expert back (or, when the adaptive tier already brought that one back, the - // most-routed missing expert of the same layer); the adaptive tier carries on from there. - std::vector> vram_evicted; // (residency index, slot) the shrinks took - const int64_t chunk_full = o.prefill_chunk; // the loan's chunk with the whole cache - auto relend = [&]() { // the prompt path's loan: the end of the slots left, its chunk as large as fits - if (pf_parts.empty() || pf_parts[0].first < 0) return; - PfPart& p = pf_parts[0]; - const int64_t live = xcache.slots(); - auto fits = [&](int64_t c) { - const int64_t k = part_slots(p, c); - return k > 0 && k + 128 <= live && !(o.prefill_auto && k * 100 > kAutoLendPct * live); - }; - int64_t c = chunk_full; - while (c > 256 && !fits(c)) c = std::max(256, c / 2 / 256 * 256); - o.prefill_chunk = c; - p.first = (int32_t) std::max(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(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; - const bool bare = cmd.find_first_not_of(' ', 4) == std::string::npos; - const long long reserve = bare ? (long long) o.vram_reserve_mib : std::strtoll(cmd.c_str() + 4, &end, 10); - if (!bare && (end == cmd.c_str() + 4 || reserve < 0)) { e = "expected: VRAM [reserve_mib]"; return false; } - if (!xcache.segmented()) { - e = "VRAM needs an engine started with --vram-elastic (one NVIDIA GPU, --serve)"; - return false; - } - if (src.complement_ready()) { - e = "VRAM: not with the resident low-RAM mode (the cache holds experts RAM does not)"; - return false; - } - if (peer.valid()) { e = "VRAM: not with --peer-device"; return false; } - for (const PfPart& p : pf_parts) - if (!p.lent.empty()) { e = "VRAM: a prompt's loan is still out"; return false; } - if (!ver.wait_commit(e)) return false; - apply_pending(true); // the adaptive tier's swaps in flight land first - if (cudaDeviceSynchronize() != cudaSuccess) { - e = std::string("VRAM: ") + cudaGetErrorString(cudaGetLastError()); - return false; - } - const auto t0 = Clock::now(); - size_t free_b = 0, total_b = 0; - 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 - const int64_t floor_slots = std::min(xcache.full_slots(), - 128 + (pf_parts.empty() || pf_parts[0].first < 0 ? 0 : part_slots(pf_parts[0], 256))); - std::string note; - if ((int64_t) free_b < want_free) { - const int64_t floor_b = xcache.bytes_of(floor_slots); - int64_t keep = mapped - (want_free - (int64_t) free_b); - if (keep < floor_b) { - keep = floor_b; - note = " (the cache keeps its smallest size: the prompt path's buffers)"; - } - if (!xcache.shrink(keep, e)) return false; - const int64_t live = xcache.slots(); - for (size_t i = 0; i < host_res.size(); ++i) - if (host_res[i] >= live) { - vram_evicted.emplace_back((int32_t) i, host_res[i]); - host_res[i] = strata::core::kNotResident; - } - res_upload(); - } else if (mapped < xcache.full_bytes()) { - std::string gerr; - if (!xcache.grow(mapped + ((int64_t) free_b - want_free), gerr)) note = " (" + gerr + ")"; - const int64_t live = xcache.slots(); - std::string ferr; - std::vector> keep_out; - for (const auto& [i, slot] : vram_evicted) { - if (slot >= live) { keep_out.emplace_back(i, slot); continue; } - const int64_t layer = i / g.n_expert; - int64_t pick = i; - if (host_res[(size_t) i] >= 0) { // back already (the adaptive tier): the layer's most-routed miss - pick = -1; - float best = -1.0f; - for (int64_t ex = 0; ex < g.n_expert; ++ex) { - const size_t j = (size_t) (layer * g.n_expert + ex); - if (host_res[j] >= 0) continue; - const float u = drive.d.usage.empty() ? 0.0f : drive.d.usage[j]; - if (u > best) { best = u; pick = (int64_t) j; } - } - } - if (pick < 0) continue; - const uint8_t* b = srcp->blob(layer, pick % g.n_expert); - if (b == nullptr || !xcache.fill_slot_queued(slot, b, ferr, - (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(layer))) { - e = "VRAM: refilling the cache failed: " + ferr; - return false; - } - host_res[(size_t) pick] = slot; - } - vram_evicted.swap(keep_out); - if (!xcache.sync_queued(ferr)) { e = "VRAM: " + ferr; return false; } - res_upload(); - } - relend(); - 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(), - (double) xcache.mapped_bytes() / 1073741824.0, (double) xcache.full_bytes() / 1073741824.0, - (long long) (free_b >> 20), (long long) o.prefill_chunk, - std::chrono::duration(Clock::now() - t0).count(), note.c_str()); - std::printf("VRAM reserve_mib=%lld expert_slots=%lld expert_slots_full=%lld expert_cache_mib=%lld " - "expert_cache_full_mib=%lld vram_free_mib=%lld prompt_chunk=%lld\n", reserve, - (long long) xcache.slots(), (long long) xcache.full_slots(), - (long long) (xcache.mapped_bytes() >> 20), (long long) (xcache.full_bytes() >> 20), - (long long) (free_b >> 20), (long long) o.prefill_chunk); - return true; - }; - // ---- --batch: the slots of the batch windows - struct BSlot { - bool active = false, stop = false; - int32_t x = 0; ///< the token the next window feeds (not yet in the slot's state) - int64_t p = 0; ///< its position - int64_t produced = 0, max_new = 0; - Clock::time_point t0; - // the slot's own conversation cache: the tokens its sessions hold (the prompt, then every token a window - // fed). Kept when the request ends (`cached`), so the next turn of that conversation continues from it - // instead of reading its history again (see `slot_source` in the request path). - std::vector ids; - bool cached = false; ///< idle, and its sessions still hold `ids` - bool cvec = true; ///< the control vector setting `ids` were read with - bool img = false; ///< the conversation has pictures (never reused from the slot) - // the checkpoint its prompt read took at the last turn boundary (the history before the new turn's - // header): a client's next turn renders the history again WITHOUT this reply's thinking, so it matches - // the slot's tokens only up to there - the slot's K/V up to it plus this state continue from it - std::vector checks; - // a prompt read that gave way to a waiting request (BYIELD): `ids` is the part read so far, and the same - // request continues from it (the read goes on with the same chunks; `from0`: it had started at token 0) - bool partial = false, partial_from0 = false; - }; - std::vector bs((size_t) std::max(o.batch, 0)); - // timing of the batch windows since the slots were last all idle (one stderr line then) - double bt_run = 0, bt_commit = 0, bt_emit = 0; - double bt_wait0 = 0, bt_pool0 = 0; - int64_t bt_miss0 = 0, bt_hits0 = 0, bt_pcie0 = 0; - int64_t bt_windows = 0, bt_rows = 0, bt_tokens = 0; - Clock::time_point bt_start = Clock::now(); - int admit_slot = -1; ///< the slot the request being read will continue in (BGEN) - long long admit_max_new = 0; - auto batch_on = [&] { for (const BSlot& b : bs) if (b.active) return true; return false; }; - auto try_next_line = [&](std::string& out) -> bool { - std::lock_guard lk(in_mu); - if (in_lines.empty()) return false; - out = std::move(in_lines.front()); - in_lines.pop_front(); - return true; - }; - // the session a request just left behind (its prompt) -> slot b's sessions, on every stage - auto copy_to_slot = [&](int b, const std::vector& ids, std::string& e) -> bool { - const int64_t upto = (int64_t) ids.size(); - for (size_t k = 0; k < bslot_ss.size(); ++k) { - strata::core::SessionState& from = k == 0 ? ss : stages[k - 1]->ss; - strata::core::SessionState& to = *bslot_ss[k][(size_t) b]; - const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev); - if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch admission: device sync failed"; return false; } - strata::core::ConversationCheckpoint ck; - ck.ids = ids; - if (!strata::core::conversation_checkpoint_save(ck, from, g, e) || - !strata::core::conversation_checkpoint_restore(ck, to, g, e)) - return false; - for (int64_t j = 0; j < from.qsa_alloc; ++j) { - strata::core::ConversationKv img; - if (!strata::core::conversation_kv_save(img, from.qsa_states[from.qsa_ord0 + j], g, upto, true, e)) - return false; - if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch admission: device sync failed"; return false; } - if (!strata::core::conversation_kv_restore(img, to.qsa_states[to.qsa_ord0 + j], g, upto, true, e)) - return false; - } - if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch admission: device sync failed"; return false; } - } - return true; - }; - // slot b's sessions -> the main ones (the reverse of copy_to_slot): a request that continues the - // conversation an idle slot holds reads on from there. Every stage, the same calls. - // `at`: one of the slot's checkpoints - only the K/V up to it is copied and its state restored instead - auto copy_from_slot = [&](int b, const ConvCheckpoint* at, std::string& e) -> bool { - const int64_t upto = at != nullptr ? (int64_t) at->ids.size() : (int64_t) bs[(size_t) b].ids.size(); - if (at != nullptr && at->stage_parts.size() != stages.size()) { e = "a checkpoint without its stage parts"; return false; } - for (size_t k = 0; k < bslot_ss.size(); ++k) { - strata::core::SessionState& from = *bslot_ss[k][(size_t) b]; - strata::core::SessionState& to = k == 0 ? ss : stages[k - 1]->ss; - const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev); - if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch slot restore: device sync failed"; return false; } - if (at != nullptr) { - if (!strata::core::conversation_checkpoint_restore(k == 0 ? *at : at->stage_parts[k - 1], to, g, e)) - return false; - } else { - strata::core::ConversationCheckpoint ck; - ck.ids = bs[(size_t) b].ids; - if (!strata::core::conversation_checkpoint_save(ck, from, g, e) || - !strata::core::conversation_checkpoint_restore(ck, to, g, e)) - return false; - } - for (int64_t j = 0; j < from.qsa_alloc; ++j) { - strata::core::ConversationKv img; - if (!strata::core::conversation_kv_save(img, from.qsa_states[from.qsa_ord0 + j], g, upto, true, e)) - return false; - if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch slot restore: device sync failed"; return false; } - if (!strata::core::conversation_kv_restore(img, to.qsa_states[to.qsa_ord0 + j], g, upto, true, e)) - return false; - } - if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch slot restore: device sync failed"; return false; } - } - return true; - }; - // one batch window over the active slots only (row t is the t-th active slot): an idle slot is not touched, - // so it keeps the conversation it holds - auto batch_step = [&]() -> bool { - int S = 0; - int rows[strata::kernels::kVerifyMaxT] = {}; - int32_t tok[strata::kernels::kVerifyMaxT] = {}, outb[strata::kernels::kVerifyMaxT] = {}; - int64_t pos[strata::kernels::kVerifyMaxT] = {}; - for (int b = 0; b < (int) bs.size() && S < strata::kernels::kVerifyMaxT; ++b) - if (bs[(size_t) b].active) { - rows[S] = b; - tok[S] = bs[(size_t) b].x; - pos[S] = bs[(size_t) b].p; - ++S; - } - if (S == 0) return true; - const bool was_busy = strata::core::progress().busy.load(); - strata::core::progress().busy.store(true); - drive.d.layers = 0; - drive.d.experts = 0; - drive.d.failed = false; - apply_pending(false); - if (bt_windows == 0) { - bt_start = Clock::now(); - bt_wait0 = ver.ms_wait; bt_pool0 = ver.ms_pool; - bt_miss0 = drive.d.multi_misses; bt_hits0 = drive.d.cache_hits; bt_pcie0 = drive.d.pcie_experts; - } - const Clock::time_point w0 = Clock::now(); - if (!ver.run_slot_rows(rows, S, tok, pos, win_pool_fn, win_pool_user, outb, err) || drive.d.failed) { - std::printf("ERR %s\n", drive.d.failed && drive.d.fail ? drive.d.fail : err.c_str()); - return false; - } - const Clock::time_point w1 = Clock::now(); - if (!ver.commit_slots(err)) { - std::printf("ERR %s\n", err.c_str()); - return false; - } - const Clock::time_point w2 = Clock::now(); - auto msd = [](Clock::time_point a0, Clock::time_point b0) { return std::chrono::duration(b0 - a0).count(); }; - bt_run += msd(w0, w1); - bt_commit += msd(w1, w2); - ++bt_windows; - bt_rows += S; - for (int t = 0; t < S; ++t) { - const int b = rows[t]; - BSlot& sl = bs[(size_t) b]; - const int32_t y = outb[t]; - sl.ids.push_back(sl.x); // the window fed it: the slot's sessions hold it now - std::printf("BT %d %d\n", b, (int) y); - ++sl.produced; - const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end(); - const char* fin = eos ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length" - : sl.p + 2 > o.max_context ? "length" : nullptr; - if (fin != nullptr) { - const double ms = std::chrono::duration(Clock::now() - sl.t0).count(); - std::printf("BDONE %d %lld %s %.1f\n", b, (long long) sl.produced, fin, ms); - sl.active = false; - sl.cached = o.prompt_cache > 0 && !sl.img; // its sessions hold sl.ids for the next turn - } else { - sl.x = y; - sl.p += 1; - } - } - std::fflush(stdout); - bt_emit += msd(w2, Clock::now()); - strata::core::progress().busy.store(was_busy); - if (!batch_on() && bt_windows > 0) { - const double w = (double) bt_windows, wall = msd(bt_start, Clock::now()); - const double L = (double) g.n_layers; - std::fprintf(stderr, "strata batch: %lld windows, avg %.2f rows, %.2f ms/window = run %.2f (CUDA0 GPU-reach " - "wait %.2f + CPU experts %.2f) + commit %.2f + emit %.2f; per layer-window: CPU experts " - "%.2f, VRAM hits %.2f, PCIe %.2f; %.1f rows/s over %.0f ms of wall time (admissions " - "included)\n", - (long long) bt_windows, bt_rows / w, (bt_run + bt_commit + bt_emit) / w, bt_run / w, - (ver.ms_wait - bt_wait0) / w, (ver.ms_pool - bt_pool0) / w, bt_commit / w, bt_emit / w, - (drive.d.multi_misses - bt_miss0) / (w * L), (drive.d.cache_hits - bt_hits0) / (w * L), - (drive.d.pcie_experts - bt_pcie0) / (w * L), 1000.0 * bt_rows / std::max(wall, 1e-9), wall); - for (size_t k = 0; k <= stages.size(); ++k) { - const std::string pr = (k == 0 ? ver : stages[k - 1]->ver).profile_report(); - if (!pr.empty()) std::fprintf(stderr, "strata batch GPU stages, stage %zu (ms/window):%s\n", k + 1, pr.c_str()); - } - bt_run = bt_commit = bt_emit = 0; - bt_windows = bt_rows = bt_tokens = 0; - } - return true; - }; - // ---- --batch-groups: the slot groups pipelined through the stages (--batch-groups G > 1 with a layer split) - const int n_pipe = (int) stages.size() + 1; - const bool piped = o.batch > 0 && o.batch_groups > 1 && n_pipe > 1; - const int GS = piped ? o.batch / o.batch_groups : o.batch; - struct PGroup { - bool inflight = false; - int stage = 0; ///< the stage it runs on or waits for - int32_t tok[strata::kernels::kVerifyMaxT] = {}; - int64_t pos[strata::kernels::kVerifyMaxT] = {}; - int64_t since = 0; ///< tick it started waiting (fairness) - }; - std::vector pg((size_t) (piped ? o.batch_groups : 0)); - std::vector stage_group((size_t) n_pipe, -1); - int64_t pipe_tick = 0, rr = 0; - auto stage_verifier = [&](int k) -> strata::core::Verifier& { return k == 0 ? ver : stages[(size_t) k - 1]->ver; }; - auto pipe_inflight = [&] { for (const PGroup& x : pg) if (x.inflight) return true; return false; }; - auto group_active = [&](int gi) { - for (int t = 0; t < GS; ++t) if (bs[(size_t) (gi * GS + t)].active) return true; - return false; - }; - // one turn: serve every running stage, hand finished groups on, start what can start - auto pump = [&](bool may_start) -> bool { - ++pipe_tick; - if (bt_windows == 0 && !pipe_inflight()) { - bt_start = Clock::now(); - bt_wait0 = ver.ms_wait; bt_pool0 = ver.ms_pool; - bt_miss0 = drive.d.multi_misses; bt_hits0 = drive.d.cache_hits; bt_pcie0 = drive.d.pcie_experts; - } - for (int k = 0; k < n_pipe; ++k) { - const int gi = stage_group[(size_t) k]; - if (gi < 0) continue; - strata::core::Verifier& vk = stage_verifier(k); - const int r = vk.batch_poll(win_pool_fn, win_pool_user, err); - if (r < 0) { std::printf("ERR %s\n", err.c_str()); return false; } - if (r == 0) continue; - stage_group[(size_t) k] = -1; - PGroup& G = pg[(size_t) gi]; - if (k + 1 < n_pipe) { G.stage = k + 1; G.since = pipe_tick; continue; } - // the last stage: the group's picks - const int32_t* outb = vk.batch_out(); - for (int t = 0; t < GS; ++t) { - BSlot& sl = bs[(size_t) (gi * GS + t)]; - if (!sl.active) continue; - const int32_t y = outb[t]; - std::printf("BT %d %d\n", gi * GS + t, (int) y); - ++sl.produced; - ++bt_rows; - const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end(); - const char* fin = eos ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length" - : sl.p + 2 > o.max_context ? "length" : nullptr; - sl.ids.push_back(sl.x); - if (fin != nullptr) { - const double ms = std::chrono::duration(Clock::now() - sl.t0).count(); - std::printf("BDONE %d %lld %s %.1f\n", gi * GS + t, (long long) sl.produced, fin, ms); - sl.active = false; - sl.cached = false; // the pipeline's pad rows: a pipelined slot is not reused as a cache - } else { - sl.x = y; - sl.p += 1; - } - } - std::fflush(stdout); - ++bt_windows; - G.inflight = false; - } - // start waiting groups on free stages, the longest waiting first; a new step on stage 0 round-robin - for (int k = n_pipe - 1; k >= 0; --k) { - if (stage_group[(size_t) k] >= 0) continue; - int pick = -1; - if (k > 0) { - for (int gi = 0; gi < (int) pg.size(); ++gi) - if (pg[(size_t) gi].inflight && pg[(size_t) gi].stage == k && - (pick < 0 || pg[(size_t) gi].since < pg[(size_t) pick].since)) - pick = gi; - if (pick < 0) continue; - } else { - if (!may_start) continue; - for (int j = 0; j < (int) pg.size() && pick < 0; ++j) { - const int gi = (int) ((rr + j) % (int64_t) pg.size()); - if (!pg[(size_t) gi].inflight && group_active(gi)) pick = gi; - } - if (pick < 0) continue; - rr = pick + 1; - PGroup& G = pg[(size_t) pick]; - for (int t = 0; t < GS; ++t) { - BSlot& sl = bs[(size_t) (pick * GS + t)]; - G.tok[t] = sl.active ? sl.x : 0; - G.pos[t] = sl.active ? sl.p : 0; - if (!sl.active) sl.cached = false; // its pad row writes its state - } - G.inflight = true; - G.stage = 0; - drive.d.failed = false; - apply_pending(false); - } - PGroup& G = pg[(size_t) pick]; - strata::core::progress().busy.store(true); - if (!stage_verifier(k).batch_launch(pick * GS, GS, G.tok, G.pos, err)) { - std::printf("ERR %s\n", err.c_str()); - return false; - } - stage_group[(size_t) k] = pick; - } - if (drive.d.failed) { std::printf("ERR %s\n", drive.d.fail ? drive.d.fail : "the expert pool failed"); return false; } - if (!pipe_inflight() && !batch_on() && bt_windows > 0) { // all idle: the timing line, as batch_step - const double w = (double) bt_windows, wall = std::chrono::duration(Clock::now() - bt_start).count(); - std::fprintf(stderr, "strata batch (pipelined, %d groups of %d): %lld group-steps, %lld rows in %.0f ms = " - "%.1f rows/s (admissions included)\n", o.batch_groups, GS, (long long) bt_windows, - (long long) bt_rows, wall, 1000.0 * bt_rows / std::max(wall, 1e-9)); - for (int k = 0; k < n_pipe; ++k) { - const std::string pr = stage_verifier(k).profile_report(); - if (!pr.empty()) std::fprintf(stderr, "strata batch GPU stages, stage %d (ms/window):%s\n", k + 1, pr.c_str()); - } - bt_windows = bt_rows = 0; - strata::core::progress().busy.store(false); - } - return true; - }; - auto pipe_drain = [&]() -> bool { - while (pipe_inflight()) - if (!pump(false)) return false; - return true; - }; - for (;;) { - if (batch_on() || (piped && pipe_inflight())) { - if (!try_next_line(line)) { - if (!(piped ? pump(true) : batch_step())) return 1; - continue; - } - // a request reads its prompt through every stage: the groups in flight finish first - if (piped && line.rfind("BSTOP ", 0) != 0 && !pipe_drain()) return 1; - } else if (!next_line(line)) { - break; - } - // --batch: BSTOP ends that slot at its next batch window; BGEN ... reads the - // request's prompt and first token as a GEN 1, then continues it in that slot - if (line.rfind("BSTOP ", 0) == 0) { - const int b = std::atoi(line.c_str() + 6); - if (b >= 0 && b < (int) bs.size()) bs[(size_t) b].stop = true; - 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"; - else vram_command(line, verr); - if (!verr.empty()) std::printf("ERR %s\n", verr.c_str()); - std::fflush(stdout); - continue; - } - admit_slot = -1; - if (line.rfind("BGEN ", 0) == 0 || line.rfind("BGENI ", 0) == 0) { - const bool bimg = line.rfind("BGENI ", 0) == 0; - char* e1 = nullptr; - const long b = std::strtol(line.c_str() + (bimg ? 6 : 5), &e1, 10); - char* e2 = nullptr; - const long long mn = std::strtoll(e1, &e2, 10); - if (bs.empty() || b < 0 || b >= (long) bs.size() || bs[(size_t) b].active || mn < 1 || e2 == e1) { - std::printf("ERR BGEN: no such free slot (--batch %d) or a bad max_new\n", o.batch); - std::fflush(stdout); - continue; - } - admit_slot = (int) b; - admit_max_new = mn; - line = std::string(bimg ? "GENI 1" : "GEN 1") + e2; - } - // #477: every --expert-profile-save-every minutes, before the next request (at QUIT: after the loop) - if (!heat.empty() && line != "QUIT" && o.expert_profile_save_min > 0 && - Clock::now() - profile_saved_at >= std::chrono::duration(o.expert_profile_save_min * 60.0)) - save_profile("periodic"); - if (line == "QUIT") break; - // the watchdog watches a request from here until this iteration ends, whichever way it ends - struct BusyScope { - BusyScope() { strata::core::progress().busy.store(true); strata::core::progress_at("request"); } - ~BusyScope() { strata::core::progress().busy.store(false); strata::core::progress_at("idle"); } - } busy_scope; - stop_req.store(false); // a STOP that arrived between requests is stale - err.clear(); - const bool geni = line.rfind("GENI ", 0) == 0; - if (!geni && line.rfind("GEN ", 0) != 0) { - std::printf("ERR expected: GEN or GENI \n"); - continue; - } - char* endp = nullptr; - const long long max_new = std::strtoll(line.c_str() + (geni ? 5 : 4), &endp, 10); - // optional sampling keys between max_new and the ids: temperature=F, top_p=F, top_k=N, min_p=F, - // penalty_last_n=N, penalty_repeat=F, penalty_freq=F, penalty_present=F, seed=N (text requests - // only). Absent keys keep today's behavior: greedy, no penalties. - float req_temperature = 0.0f, req_top_p = 1.0f; - int req_top_k = 20; // the sampler's own default; the sampled path REQUIRES top_k in 1..64 - unsigned long long req_seed = 0; - float req_min_p = 0.0f, req_penalty_repeat = 1.0f, req_penalty_freq = 0.0f, req_penalty_present = 0.0f; - int req_penalty_last_n = 0; - int req_cvec = 1; // cvec=0|1: a loaded control vector for this request (on when absent) - // tuning keys (setup's calibration measures settings without restarting the engine): the PCIe share of - // the missed experts and the draft-probability floor, for this request only - double req_pcie_frac = o.pcie_frac, req_spec_min_p = o.spec_min_p; - if (endp != nullptr) { // GENI takes the same keys (#75: image requests were always greedy); its - // embedding file path is the first token without an = - for (;;) { - while (*endp == ' ') ++endp; - const char* start = endp; - while (*endp != '\0' && *endp != ' ') ++endp; - if (endp == start) break; - const std::string tok(start, (size_t) (endp - start)); - const size_t eq = tok.find('='); - if (eq == std::string::npos) { endp = const_cast(start); break; } - const std::string key = tok.substr(0, eq); - const float fv = std::strtof(tok.c_str() + eq + 1, nullptr); - if (key == "cvec") req_cvec = std::atoi(tok.c_str() + eq + 1); - else if (key == "temperature") req_temperature = fv; - else if (key == "top_p") req_top_p = fv; - else if (key == "top_k") req_top_k = std::atoi(tok.c_str() + eq + 1); - else if (key == "min_p") req_min_p = fv; - else if (key == "penalty_last_n") req_penalty_last_n = std::atoi(tok.c_str() + eq + 1); - else if (key == "penalty_repeat") req_penalty_repeat = fv; - else if (key == "penalty_freq") req_penalty_freq = fv; - else if (key == "penalty_present") req_penalty_present = fv; - else if (key == "seed") req_seed = std::strtoull(tok.c_str() + eq + 1, nullptr, 10); - else if (key == "pcie_frac") req_pcie_frac = std::clamp((double) fv, 0.0, 1.0); - else if (key == "spec_min_p") req_spec_min_p = std::clamp((double) fv, 0.0, 1.0); - // unknown keys are skipped: the ids start at the first token without '=' - } - } - std::string emb_path; - if (geni && endp != nullptr) { - while (*endp == ' ') ++endp; - char* gap = std::strchr(endp, ' '); - if (gap != nullptr) { emb_path.assign(endp, (size_t) (gap - endp)); endp = gap; } - } - std::vector ids; - std::string pe; - if (max_new < 1 || endp == nullptr || (geni && emb_path.empty()) || !parse_i64_list(endp, ids, pe)) { - std::printf("ERR bad request: %s\n", pe.empty() ? "max_new" : pe.c_str()); - continue; - } - const int64_t n = (int64_t) ids.size(); - req_imgs.clear(); - if (geni && !o.vision) { std::printf("ERR this engine was started without --vision\n"); continue; } - if (geni || !mrope_identity) { - // positions for every cell this request can reach; the identity again for a text request - std::string ve; - row_ptr.assign((size_t) n, nullptr); - const int64_t cells = (int64_t) mrope_host.size() / 3; - auto put = [&](int64_t c, int64_t t, int64_t h, int64_t w) { - mrope_host[(size_t) c * 3] = (int32_t) t; - mrope_host[(size_t) c * 3 + 1] = (int32_t) h; - mrope_host[(size_t) c * 3 + 2] = (int32_t) w; - }; - if (!geni) { - for (int64_t c = 0; c < cells; ++c) put(c, c, c, c); - } else { - struct Img { int64_t n, nx, ny; size_t off; }; - std::vector imgs; - img_rows.clear(); - std::FILE* f = std::fopen(emb_path.c_str(), "rb"); - if (!f) ve = "cannot open " + emb_path; - while (f && ve.empty()) { - int32_t hdr[5]; - const size_t got = std::fread(hdr, sizeof(int32_t), 5, f); - if (got == 0) break; - if (got != 5 || hdr[0] != 0x31455653 || hdr[1] < 1 || hdr[2] < 1 || hdr[3] < 1 || - (int64_t) hdr[2] * hdr[3] != hdr[1] || hdr[4] != (int32_t) g.n_embd) { - ve = "bad embeddings file (expected strata-vision records of width " + - std::to_string((long long) g.n_embd) + ")"; - break; - } - const size_t off = img_rows.size(), cnt = (size_t) hdr[1] * (size_t) hdr[4]; - img_rows.resize(off + cnt); - if (std::fread(img_rows.data() + off, sizeof(float), cnt, f) != cnt) { ve = "short embeddings file"; break; } - imgs.push_back({hdr[1], hdr[2], hdr[3], off}); - } - if (f) std::fclose(f); - int64_t p = 0, i = 0; - size_t k = 0; - while (ve.empty() && i < n) { - if (ids[(size_t) i] != kImagePad) { put(i, p, p, p); ++p; ++i; continue; } - if (k >= imgs.size()) { ve = "the prompt has more images than the embeddings file"; break; } - const Img& im = imgs[k++]; - { // what the conversation cache compares: a picture is its grid and its embeddings - const int64_t grid[3] = {im.n, im.nx, im.ny}; - uint64_t h = fnv1a(grid, sizeof grid); - h = fnv1a(img_rows.data() + im.off, (size_t) im.n * (size_t) g.n_embd * sizeof(float), h); - req_imgs.push_back({i, h}); - } - for (int64_t j = 0; j < im.n && ve.empty(); ++j) - if (i + j >= n || ids[(size_t) (i + j)] != kImagePad) - ve = "image " + std::to_string(k) + " has " + std::to_string((long long) im.n) + - " rows but fewer <|image_pad|> tokens"; - for (int64_t j = 0; j < im.n && ve.empty(); ++j) { - const int64_t y = j / im.nx, x = j % im.nx; - put(i + j, p, p + y, p + x); - row_ptr[(size_t) (i + j)] = img_rows.data() + im.off + (size_t) j * (size_t) g.n_embd; - } - i += im.n; - p += std::max(im.nx, im.ny); - } - if (ve.empty() && k != imgs.size()) ve = "the embeddings file has more images than the prompt"; - if (ve.empty() && n > 0 && ids[(size_t) (n - 1)] == kImagePad) ve = "the prompt cannot end in an image"; - for (int64_t c = n; ve.empty() && c < cells; ++c) put(c, p + (c - n), p + (c - n), p + (c - n)); - } - tr("positions built", (long long) img_rows.size()); - cudaDeviceSynchronize(); - tr("device idle"); - // CUDA0's table and, with a layer split, every later stage's (each device reads its own) - auto upload_mrope = [&]() -> bool { - bool ok = cudaMemcpy(d_mrope, mrope_host.data(), mrope_host.size() * sizeof(int32_t), - cudaMemcpyHostToDevice) == cudaSuccess; - for (auto& st : stages) { - const strata::core::OnDevice on(st->dev); - cudaDeviceSynchronize(); - ok = ok && cudaMemcpy(st->mrope, mrope_host.data(), mrope_host.size() * sizeof(int32_t), - cudaMemcpyHostToDevice) == cudaSuccess; - } - return ok; - }; - if (ve.empty() && !upload_mrope()) ve = "the image position upload failed"; - if (!ve.empty()) { - // leave the table as the identity so the next text request is untouched - for (int64_t c = 0; c < cells; ++c) put(c, c, c, c); - upload_mrope(); - mrope_identity = true; - std::printf("ERR %s\n", ve.c_str()); - std::fflush(stdout); - continue; - } - mrope_identity = !geni; - } - sp.embd_rows = geni ? row_ptr.data() : nullptr; - if (n + max_new + 8 > o.max_context) { - std::printf("ERR prompt (%lld tokens) + max_new (%lld) exceeds the context (%lld)\n", (long long) n, - (long long) max_new, (long long) o.max_context); - continue; - } - bool bad = false; - for (int64_t t : ids) bad = bad || t < 0 || t >= n_vocab; - if (bad) { std::printf("ERR a token id is outside the vocabulary\n"); continue; } - std::array remote_before{}; - std::array launches_before{}; - std::array compact_before{}, full_before{}; - // ms_begin/ms_wait are cumulative since boot; the log line used to print them next to per-request deltas, - // so the host time read as if it belonged to this request. Take deltas here like every other column. - std::array begin_before{}, wait_before{}; - for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) - { - remote_before[(size_t) r] = remote_experts[(size_t) r].computed(); - launches_before[(size_t) r] = remote_experts[(size_t) r].launched_layers(); - compact_before[(size_t) r] = remote_experts[(size_t) r].returned_bytes(); - full_before[(size_t) r] = remote_experts[(size_t) r].full_row_bytes(); - begin_before[(size_t) r] = remote_experts[(size_t) r].ms_begin(); - wait_before[(size_t) r] = remote_experts[(size_t) r].ms_wait(); - } - cur = ids; - const Clock::time_point r0 = Clock::now(); - // ---- where this request starts reading: the live session, or a checkpoint, whose tokens AND pictures are - // exactly the start of this prompt - at most n - 1 of them, the last token is always the first window - auto starts_with = [&](const std::vector& pre, const std::vector& pre_imgs) -> bool { - const int64_t L = (int64_t) pre.size(); - if (L < 1 || L > n - 1) return false; - for (int64_t i = 0; i < L; ++i) - if ((int32_t) ids[(size_t) i] != pre[(size_t) i]) return false; - return imgs_below(req_imgs, L) == pre_imgs; - }; - const bool want_cvec = strata::kernels::cvec().loaded() ? req_cvec != 0 : true; - // the last request's final commit may still be running on the verifier's stream (set_commit_async): - // everything below reads, restores or zeroes the session from other streams and the host (the end of the - // last request waited already; this covers a request that ended on an error path) - if (!ver.wait_commit(err)) { - std::printf("ERR %s\n", err.c_str()); - return 1; - } - int64_t resume = 0; - bool from_live = false; - if (o.prompt_cache > 0 && want_cvec == cvec_cached) { - if (live_ok && starts_with(live, live_imgs)) { resume = (int64_t) live.size(); from_live = true; } - for (const ConvCheckpoint& c : checks) - if ((int64_t) c.ids.size() > resume && starts_with(c.ids, c.imgs)) { - resume = (int64_t) c.ids.size(); - from_live = false; - } - } - // --batch: an idle slot that holds the start of this prompt (the conversation it served last) is a - // source too - its sessions are copied back below, so only the new part is read - int slot_source = -1; - int64_t slot_tokens = 0; - bool resumed_from0 = false; // a prompt read parked in a slot (BYIELD) that had started at token 0 - const ConvCheckpoint* slot_ck = nullptr; // the slot's checkpoint the prompt continues from (else its end) - if (o.prompt_cache > 0 && req_imgs.empty()) - for (int b = 0; b < (int) bs.size(); ++b) { - const BSlot& sl = bs[(size_t) b]; - if (sl.active || !sl.cached || sl.cvec != want_cvec) continue; - if ((int64_t) sl.ids.size() > std::max(resume, slot_tokens) && starts_with(sl.ids, {})) { - slot_source = b; - slot_tokens = (int64_t) sl.ids.size(); - slot_ck = nullptr; - } - for (const ConvCheckpoint& c : sl.checks) - if ((int64_t) c.ids.size() > std::max(resume, slot_tokens) && starts_with(c.ids, c.imgs)) { - slot_source = b; - slot_tokens = (int64_t) c.ids.size(); - slot_ck = &c; - } - } - const auto parked = conversations.best(ids, req_imgs, want_cvec); - std::optional incoming; - if (parked.tokens > std::max(resume, slot_tokens)) incoming.emplace(conversations.take(parked.index)); - if (incoming) slot_source = -1; - // Reject the entire image before parking/overwriting the outgoing - // state. Invalid entries can safely fall back to its existing prefix. - if (incoming && incoming->stage_images.size() != stages.size()) { - std::fprintf(stderr, "strata serve: conversation cache: discard snapshot (stage count)\n"); - incoming.reset(); - } - if (incoming) for (size_t i = 0; i < stages.size(); ++i) { - const strata::core::OnDevice on(stages[i]->dev); - if (!strata::core::conversation_snapshot_validate(incoming->stage_images[i], stages[i]->ss, g, - i + 1 == stages.size() ? &mtp.kv_state() : nullptr, err)) { // the draft: the last stage's - std::fprintf(stderr, "strata serve: conversation cache: discard invalid stage snapshot (%s)\n", - err.c_str()); - incoming.reset(); - err.clear(); - break; - } - } - if (incoming && !strata::core::conversation_snapshot_validate(*incoming, ss, g, - stages.empty() ? &mtp.kv_state() : nullptr, err)) { - std::fprintf(stderr, "strata serve: conversation cache: discard invalid snapshot (%s)\n", err.c_str()); - incoming.reset(); - err.clear(); - } - // Preserve the outgoing branch before any checkpoint rewind, reset, - // or incoming restore overwrites the positional state it requires. - if ((!from_live || incoming || slot_source >= 0) && !park_current(incoming ? incoming->bytes() : 0)) { - std::printf("ERR %s\n", err.c_str()); - return 1; - } - if (slot_source >= 0) { - const auto t0 = Clock::now(); - if (!copy_from_slot(slot_source, slot_ck, err)) { - // the main session may be half written: read this prompt from the start - std::fprintf(stderr, "strata batch: restoring slot %d failed (%s); reading the prompt\n", - slot_source, err.c_str()); - err.clear(); - live.clear(); - live_imgs.clear(); - checks.clear(); - resume = 0; - from_live = false; - } else { - checks.clear(); // the main session's checkpoints were of the conversation it held before - // a read that gave way, the same request again (into its own slot): on with it - its segments and - // checkpoints as if it had not stopped - if (slot_ck == nullptr && bs[(size_t) slot_source].partial && admit_slot == slot_source) { - resumed_from0 = bs[(size_t) slot_source].partial_from0; - for (const ConvCheckpoint& c : bs[(size_t) slot_source].checks) checks.push_back(c); - bs[(size_t) slot_source].partial = false; - } - if (slot_ck != nullptr) { - live = slot_ck->ids; - checks.push_back(*slot_ck); // the main session's chain has it now - checks.back().used = ++check_clock; - } else { - live = bs[(size_t) slot_source].ids; - } - live_imgs.clear(); - resume = slot_tokens; - from_live = true; - std::fprintf(stderr, "strata batch: slot %d gave back %lld tokens of this conversation (%s) in " - "%.1f ms\n", slot_source, (long long) slot_tokens, - slot_ck != nullptr ? "its turn checkpoint" : "all it holds", - std::chrono::duration(Clock::now() - t0).count()); - } - } - if (incoming) { - const auto t0 = Clock::now(); - if (strata::core::conversation_snapshot_restore(*incoming, ss, g, - stages.empty() ? &mtp.kv_state() : nullptr, err) != - strata::core::ConversationRestore::restored) { - // Already prevalidated above: a failure here is fatal, never - // permission to decode from a partially restored session. - std::printf("ERR restoring parked conversation: %s\n", err.c_str()); - return 1; - } - for (size_t i = 0; i < stages.size(); ++i) { // the later stages' parts - const strata::core::OnDevice on(stages[i]->dev); - if (strata::core::conversation_snapshot_restore(incoming->stage_images[i], stages[i]->ss, g, - i + 1 == stages.size() ? &mtp.kv_state() : nullptr, err) != - strata::core::ConversationRestore::restored) { - std::printf("ERR restoring parked conversation (stage CUDA%d): %s\n", stages[i]->dev, - err.c_str()); - return 1; - } - if (cudaDeviceSynchronize() != cudaSuccess) { std::printf("ERR stage sync\n"); return 1; } - } - if (std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr) { - uint64_t draft_hash = 0; - const auto& draft_kv = stages.empty() ? incoming->kv.back() : incoming->stage_images.back().kv.back(); - const strata::core::OnDevice on_d(stages.empty() ? 0 : stages.back()->dev); - if (!strata::core::conversation_kv_verify(draft_kv, mtp.kv_state(), g, - int64_t(incoming->live.ids.size()), false, draft_hash, err)) { - std::printf("ERR verifying restored draft KV: %s\n", err.c_str()); - return 1; - } - std::fprintf(stderr, "strata serve: SNAPSHOT_VERIFY draft=%016llx cells=%lld mode=%d source=%s resident=%lld\n", - (unsigned long long) draft_hash, (long long) draft_kv.cells, - mtp.kv_state().kv_mode, "ram", - (long long) (mtp.kv_state().n_slots * strata::kernels::qsa_real_shapes().page_size)); - } - live = std::move(incoming->live.ids); - live_imgs = std::move(incoming->live.imgs); - if (stages.empty()) { - checks = std::move(incoming->checkpoints); - } else { // give each checkpoint back its stage parts (moved, not copied); none if they do not line up - strata::core::ConversationCheckpointSplit cs; - cs.stage0 = std::move(incoming->checkpoints); - for (auto& si : incoming->stage_images) cs.parts.push_back(std::move(si.checkpoints)); - if (!strata::core::conversation_checkpoints_merge(std::move(cs), checks)) checks.clear(); - } - cvec_cached = incoming->cvec; - resume = parked.tokens; - from_live = parked.live; - if (std::getenv("STRATA_SNAPSHOT_FULL_CAPTURE") == nullptr) { - std::vector> stage_kv; // every stage's, for its next park - for (auto& si : incoming->stage_images) stage_kv.push_back(std::move(si.kv)); - conversations.retain(std::move(incoming->kv), int64_t(live.size()), std::move(stage_kv)); - } - incoming.reset(); // Running-state/checkpoint copies are no longer needed. - std::fprintf(stderr, "strata serve: conversation cache: restored %lld tokens (%s) in %.1f ms; parked=%zu bytes=%zu\n", - (long long) resume, from_live ? "live" : "checkpoint", - std::chrono::duration(Clock::now() - t0).count(), - conversations.size(), conversations.bytes()); - } - if (want_cvec != cvec_cached) { - live_ok = false; - checks.clear(); - cvec_cached = want_cvec; - } - if (strata::kernels::cvec().loaded()) strata::kernels::cvec_set_enabled(want_cvec); - // this request rewrites every cell from `resume` on, so a checkpoint past it (or not on this prompt's - // path) no longer has its cells; the ones kept are prefixes of both the old tokens and the new - checks.erase(std::remove_if(checks.begin(), checks.end(), [&](const ConvCheckpoint& c) { - return (int64_t) c.ids.size() > resume || !starts_with(c.ids, c.imgs); - }), checks.end()); - live_ok = false; // until this request has finished, the session is in between - int64_t reread_to = -1; // STRATA_CKPT_REREAD only: read [0, reread_to) again instead of restoring - if (resume == 0) { - strata::core::session_zero(ss, g, nullptr, main_cs); - cudaStreamSynchronize(main_stream); - for (auto& st : stages) { - const strata::core::OnDevice on(st->dev); - strata::core::session_zero(st->ss, g, nullptr, (void*) st->stream); - cudaStreamSynchronize(st->stream); - } - checks.clear(); - } else if (!from_live) { - ConvCheckpoint* c = nullptr; - for (ConvCheckpoint& k : checks) if ((int64_t) k.ids.size() == resume) c = &k; - if (c != nullptr) c->used = ++check_clock; // mounting through it is the use LRU counts - static const bool reread = std::getenv("STRATA_CKPT_REREAD") != nullptr; - if (reread && c != nullptr) { - // THE CHECK OF THE CHECKPOINT: instead of restoring it, read its tokens again from position 0 in - // one run (below, with the prompt path's slots lent like any read) - the same chunks the request - // that saved it read them in, when that request started at 0. With the VRAM expert set fixed - // (--adapt-swaps 0) the answer must match the restored one token for token; anything the - // checkpoint missed shows up as a difference. - strata::core::session_zero(ss, g, nullptr, main_cs); - cudaStreamSynchronize(main_stream); - for (auto& st : stages) { - const strata::core::OnDevice on(st->dev); - strata::core::session_zero(st->ss, g, nullptr, (void*) st->stream); - cudaStreamSynchronize(st->stream); - } - reread_to = resume; - std::fprintf(stderr, "strata serve: STRATA_CKPT_REREAD: reading %lld tokens again instead of " - "restoring\n", (long long) resume); - } else if (c == nullptr || !checkpoint_restore(*c, ss, g) || c->stage_parts.size() != stages.size() || - [&] { - for (size_t i = 0; i < stages.size(); ++i) { - const strata::core::OnDevice on(stages[i]->dev); - if (!checkpoint_restore(c->stage_parts[i], stages[i]->ss, g)) return true; - } - return false; - }()) { - std::printf("ERR restoring a conversation checkpoint failed\n"); - return 1; - } - } - // KV streaming: the drafter's ring may hold cells past `resume` from a longer turn; the main layers' - // host copies and slots are always current (every writer writes both), so they need nothing - if (resume > 0 && reread_to <= 0) mtp.kv_restore(resume); - tr("request", n, geni ? 1 : 0); - mtp.set_prompt_len(n); - const int64_t read_from = reread_to > 0 ? 0 : resume; - conversations.limit_reuse(read_from); - pp_total = n; - pp_from = read_from; - pp_reached = read_from; - pp_t0 = r0; - pp_next_check = reread_to > 0 ? INT64_MAX : resume + o.prompt_cache_every; - { - std::lock_guard lk(part_mu); - part_at.clear(); - std::fill(part_next.begin(), part_next.end(), pp_next_check); - } - std::printf("RESUME %lld\n", (long long) resume); // before reading: this many prompt tokens are reused - strata::core::progress_at("reading the prompt, from token", read_from); - std::fflush(stdout); - // A SHORT PART OF THE PROMPT - the new message of a chat that continues from a checkpoint, the assistant - // header - goes through the verify windows, S tokens at a time, as decode reads them. The batched path - // costs ~300 ms per run however few tokens it has (it streams every expert the chunk routes to that is - // not in VRAM over PCIe), and it borrows slots it must refill after (~180 ms); a window costs ~16 ms a - // token, with the misses on the CPU. Each part below is decided on its own, so a long first message is - // read batched and its header still goes through the windows. Picture rows need the batched path. - // STRATA_CKPT_REREAD compares a restored checkpoint with a batched re-read, so it keeps every read batched. - static const bool no_short = std::getenv("STRATA_CKPT_REREAD") != nullptr; - auto windows_ok = [&](int64_t a, int64_t b) -> bool { - if (no_short || b - a > o.short_read) return false; - if (sp.embd_rows != nullptr) - for (int64_t i = a; i < b; ++i) - if (sp.embd_rows[i] != nullptr) return false; - return true; - }; - // tokens [a, b) through the windows: commit all of them, then give the draft layer their residuals - auto read_windows = [&](int64_t a, int64_t b, std::string& e) -> bool { - strata::core::progress_at("reading the prompt (verify windows), from token", a); // #217: not "batched" - // every token is committed and the picks are discarded: no head sampling (see set_head_sampling) - struct NoHeadSampling { - strata::core::Verifier& v; - explicit NoHeadSampling(strata::core::Verifier& x) : v(x) { v.set_head_sampling(false); } - ~NoHeadSampling() { v.set_head_sampling(true); } - } no_head_sampling(ver); - std::vector win((size_t) S), outw((size_t) S), nxt((size_t) S); - for (int64_t q = a; q < b;) { - if (stop_req.load()) { e = "cancelled"; return false; } - const int T = (int) std::min(S, b - q); - for (int t = 0; t < T; ++t) { - win[(size_t) t] = (int32_t) cur[(size_t) (q + t)]; - nxt[(size_t) t] = (int32_t) cur[(size_t) (q + t + 1)]; - } - drive.d.layers = 0; - drive.d.experts = 0; - drive.d.failed = false; - if (!ver.run(T, win.data(), q, win_pool_fn, win_pool_user, outw.data(), e) || drive.d.failed) { - if (drive.d.failed && drive.d.fail) e = drive.d.fail; - return false; - } - // STRATA_LOGPOS=: the teacher-forced log-probability of every token read here (every - // token is committed and nxt[t] is the prompt's own next token), appended to ; the last - // column is the log-probability of STRATA_LOGPOS_EXTRA (default 248046, <|im_end|>), so the - // end-of-turn mass a chat model puts on raw text can be taken out of the measurement - static std::FILE* logpos = [] { - const char* p = std::getenv("STRATA_LOGPOS"); - return p != nullptr ? std::fopen(p, "ab") : nullptr; - }(); - static const int32_t logpos_extra = [] { - const char* p = std::getenv("STRATA_LOGPOS_EXTRA"); - return p != nullptr ? (int32_t) std::atoi(p) : (int32_t) 248046; - }(); - if (logpos != nullptr && !ver.window_logprobs(nxt.data(), T, q, logpos_extra, logpos, e)) - return false; - if (!ver.commit(T, e) || !mtp.prefill(ver.final_R_all(), nxt.data(), T, q, e)) return false; - q += T; - pp_reached = q; // #471 - } - // the batched prompt path (other streams), checkpoints and snapshots may follow: the last commit first - if (!ver.wait_commit(e)) return false; - const double ms = std::chrono::duration(Clock::now() - pp_t0).count(); - std::printf("PP %lld %lld %.0f %.1f\n", (long long) b, (long long) pp_total, ms, - ms > 0.0 ? 1000.0 * (double) (b - pp_from) / ms : 0.0); - strata::core::progress_beat(); - std::fflush(stdout); - return true; - }; - // the batched path's slots are lent just before its first run and given back (refilled) before a window - // reads - so the windows always see the whole expert cache - or once the prompt is read - // Every participant gives its loan back here: the rows it lent are refilled into the SAME slots from - // the arena, the residency table is restored, and one upload puts it on every device. A stage refills - // through its own cache and its own device - a slot refilled into the wrong cache would leave that - // stage's cache holding an expert it does not own, which is silent and produces plausible tokens. - // (split in two halves so a layer split can queue every stage's copies before it waits for any: #340) - auto refill_issue = [&](PfPart& p, std::string& e) -> bool { - tr("refill start", (long long) p.lent.size()); - const strata::core::OnDevice on(p.dev); - for (const auto& [i, slot] : p.lent) { // D-4: queued, one wait (STRATA_REFILL_BLOCKING=1: each) - const uint8_t* b = srcp->blob(i / g.n_expert, i % g.n_expert); - const int64_t nb = (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(i / g.n_expert); - if (b == nullptr || !(refill_blocking() ? p.cache->fill_slot_blocking(slot, b, e, nb) - : p.cache->fill_slot_queued(slot, b, e, nb))) - return false; - host_res[(size_t) i] = slot; - } - return true; - }; - auto refill_wait = [&](PfPart& p, std::string& e) -> bool { - const strata::core::OnDevice on(p.dev); - if (!p.cache->sync_queued(e)) return false; - p.lent.clear(); - p.lent_chunk = 0; - return true; - }; - auto refill_one = [&](PfPart& p, std::string& e) -> bool { - if (p.lent.empty()) return true; - return refill_issue(p, e) && refill_wait(p, e); - }; - // #340: with several stages every stage's copies go out first (each card on its own link), then each is - // waited for - the same copies into the same slots, so the same cache; one stage: refill_one exactly. - // STRATA_REFILL_SERIAL=1: stage after stage, as 0.1.30/0.1.31. - static const bool refill_serial = std::getenv("STRATA_REFILL_SERIAL") != nullptr; - auto refill = [&](std::string& e) -> bool { - const auto t_rf = Clock::now(); - int64_t n_lent = 0, n_parts = 0; - for (PfPart& p : pf_parts) - if (!p.lent.empty()) { n_lent += (int64_t) p.lent.size(); ++n_parts; } - if (n_parts > 1 && !refill_serial) { - for (PfPart& p : pf_parts) - if (!p.lent.empty() && !refill_issue(p, e)) return false; - for (PfPart& p : pf_parts) - if (!p.lent.empty() && !refill_wait(p, e)) return false; - } else { - for (PfPart& p : pf_parts) - if (!p.lent.empty() && !refill_one(p, e)) return false; - } - if (n_parts > 0) res_upload(); - if (trace && n_parts > 0) { - std::fprintf(stderr, "strata trace: refilled %lld slots on %lld stage(s) in %.1f ms\n", - (long long) n_lent, (long long) n_parts, - std::chrono::duration(Clock::now() - t_rf).count()); - std::fflush(stderr); - } - return true; - }; - // lend the slots `tokens` batched prompt tokens need: the prompt path's buffers for min(chunk, tokens - // rounded up to 256), laid out in the last of the slots it may borrow - per participant, out of that - // participant's own cache, and marking only that participant's own layers - auto lend = [&](int64_t tokens, std::string& e) -> bool { - if (pf_parts.empty()) return true; // its own buffers: nothing to lend - const auto t_ln = Clock::now(); - // what this segment needs, capped by the configured chunk: a request lends only what its own - // prompt needs, so a large chunk costs a short prompt nothing - const int64_t want_full = request_chunk(tokens, o.prefill_chunk); - // #340: a short enough request reads in the stages' own S-token chunks (nothing lent) - const int64_t want = split_small > 0 && tokens <= split_small_max ? std::min(want_full, split_small) - : want_full; - if (want <= 0) { - e = "prefill: cannot lend buffers for an empty request segment"; - return false; - } - bool any = false; - for (PfPart& p : pf_parts) { - if (p.first < 0) continue; - if (!p.lent.empty()) { - if (want <= p.lent_chunk) continue; // its current loan already covers this - // ONLY this participant's loan goes back: `refill` would return the other participants' - // loans too, and their buffers are still laid out in their caches - marking those slots - // resident again would hand the next window a prompt buffer in place of an expert - if (!refill_one(p, e)) return false; - } - const strata::core::OnDevice on(p.dev); - const int32_t first = std::max(p.first, (int32_t) (p.cache->slots() - part_slots(p, want))); - if (want != p.sp->chunk() || first != p.first_now) { - if (!p.sp->relayout(want, p.cache->device_slot(first), part_bytes(p, first), e)) return false; - p.first_now = first; - } - for (int64_t l = p.lb; l < p.le; ++l) // THIS participant's layers only - for (int64_t ex = 0; ex < g.n_expert; ++ex) { - const size_t i = (size_t) (l * g.n_expert + ex); - if (host_res[i] >= first) { - p.lent.emplace_back((int32_t) i, host_res[i]); - host_res[i] = strata::core::kNotResident; - any = true; - } - } - p.lent_chunk = want; - } - if (any) res_upload(); - if (trace) { - int64_t n_lent = 0; - for (const PfPart& p : pf_parts) n_lent += (int64_t) p.lent.size(); - std::fprintf(stderr, "strata trace: lent %lld slots for %lld tokens in %.1f ms\n", (long long) n_lent, - (long long) want, std::chrono::duration(Clock::now() - t_ln).count()); - std::fflush(stderr); - } - return true; - }; - // --batch: a prompt read while slots are decoding goes one prompt chunk at a time (the same chunks as one - // run: each run starts where the last ended, at a multiple of the chunk), and between two chunks the slots - // decode for a share of the time the chunk took (STRATA_BATCH_DECODE_SHARE, default 0.5), so a long - // prompt does not stop the others. The slots' windows then see the cache without the slots this prompt - // borrowed (marked missing: those experts run on the CPU), never a prompt buffer. - static const double decode_share = [] { - const char* v = std::getenv("STRATA_BATCH_DECODE_SHARE"); - return v != nullptr ? std::max(0.0, std::atof(v)) : 0.5; - }(); - bool batch_fatal = false; - int64_t il_parts = 0; // the slots' windows run between this prompt's chunks - double il_ms = 0; - int64_t yielded_at = -1; // BYIELD: the read stopped here and its slot holds it - int yielded_slot = -1; - // `BYIELD ` (the server: a shorter request is waiting): at the next chunk boundary the part read so - // far is copied into (this admission's own, or a free one the server reserved for a solo request), - // the request ends with `YIELDED ` + DONE cancel, and the server sends it again later: it - // continues from the slot with the same chunks. #656's cooperative preemption, with a slot as the park. - auto read_part = [&](int64_t a0, int64_t b0, std::string& e) -> bool { - // (a layer split reads its stages as a pipeline over one run's chunks: in pieces only beside slots) - if (o.batch <= 0 || piped || (!stages.empty() && !batch_on())) return sp.run(ids.data() + a0, b0 - a0, a0, e); - const int64_t C = std::max(sp.chunk(), 1); - for (int64_t q = a0; q < b0;) { - const int64_t r = std::min(b0, q + C); - const auto tq = Clock::now(); - if (!sp.run(ids.data() + q, r - q, q, e)) return false; - q = r; - if (q >= b0) continue; - int ys = -1; - { // a BSTOP that came meanwhile ends its slot at its next window; a BYIELD is for this read - std::lock_guard lk(in_mu); - for (auto it = in_lines.begin(); it != in_lines.end();) { - if (it->rfind("BSTOP ", 0) == 0) { - const int b = std::atoi(it->c_str() + 6); - if (b >= 0 && b < (int) bs.size()) bs[(size_t) b].stop = true; - it = in_lines.erase(it); - } else if (it->rfind("BYIELD ", 0) == 0) { - ys = std::atoi(it->c_str() + 7); - it = in_lines.erase(it); - } else { - ++it; - } - } - } - if (ys >= 0) { - // only where the rest is read the same way after it (more than a chunk and more than a short - // read left), text only, and into a slot that is not decoding - const bool can = ys < (int) bs.size() && !bs[(size_t) ys].active && - (admit_slot < 0 || ys == admit_slot) && req_imgs.empty() && o.prompt_cache > 0 && - b0 - q > std::max(C, o.short_read); - std::string ye; - const auto ty = Clock::now(); - std::vector pre(ids.begin(), ids.begin() + q); - if (can && copy_to_slot(ys, pre, ye)) { - BSlot& sl = bs[(size_t) ys]; - sl = BSlot{}; - sl.ids = std::move(pre); - sl.cached = true; - sl.partial = true; - sl.partial_from0 = read_from == 0 || resumed_from0; - sl.cvec = cvec_cached; - for (const ConvCheckpoint& c : checks) // the root / periodic checkpoints of this read - if ((int64_t) c.ids.size() <= q && std::equal(c.ids.begin(), c.ids.end(), ids.begin(), - [](int32_t x, int64_t y) { return (int64_t) x == y; })) - sl.checks.push_back(c); - yielded_at = q; - yielded_slot = ys; - std::fprintf(stderr, "strata batch: the prompt read gives way at %lld of %lld tokens; slot %d " - "holds it (copied in %.1f ms)\n", (long long) q, (long long) n, ys, - std::chrono::duration(Clock::now() - ty).count()); - e = "yield"; - return false; - } - if (can) bs[(size_t) ys].cached = false; // half written - std::fprintf(stderr, "strata batch: BYIELD %d not taken at %lld of %lld%s%s\n", ys, (long long) q, - (long long) n, ye.empty() ? "" : ": ", ye.c_str()); - } - if (decode_share <= 0.0 || !batch_on()) continue; - const double budget = decode_share * std::chrono::duration(Clock::now() - tq).count(); - const auto td = Clock::now(); - do { - if (!batch_step()) { batch_fatal = true; e = "a batch window failed"; return false; } - } while (batch_on() && std::chrono::duration(Clock::now() - td).count() < budget); - ++il_parts; - il_ms += std::chrono::duration(Clock::now() - td).count(); - if (trace) { - std::fprintf(stderr, "strata trace: prompt chunk to %lld, then the slots decoded %.0f ms\n", - (long long) q, std::chrono::duration(Clock::now() - td).count()); - std::fflush(stderr); - } - } - return true; - }; - apply_pending(true); - // per-request sampling for the verify window's head (greedy when temperature is absent) - strata::kernels::SamplerParams req_sp; - req_sp.greedy = req_temperature <= 0.0f; - req_sp.temperature = req_temperature; - req_sp.top_p = req_top_p; - req_sp.top_k = req_top_k; - req_sp.seed = req_seed ? req_seed - : (unsigned long long) std::chrono::steady_clock::now().time_since_epoch().count(); - req_sp.min_p = std::clamp(req_min_p, 0.0f, 1.0f); - req_sp.penalty_last_n = std::max(req_penalty_last_n, 0); - req_sp.penalty_repeat = req_penalty_repeat; - req_sp.penalty_freq = req_penalty_freq; - req_sp.penalty_present = req_penalty_present; - req_sp.counter = 0; - ver.set_sampling(req_sp); - mtp.set_draft_sampling(req_sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise) - drive.d.pcie_num = std::max(0, std::min(256, (int) (req_pcie_frac * 256.0 + 0.5))); - // a layer split: CUDA0's share as asked; a later GPU keeps its own (its link) unless the request sets one - for (int st = 0; st < split_drive.n; ++st) - split_drive.pcie_num[st] = (st == 0 || split_same || req_pcie_frac != o.pcie_frac) - ? drive.d.pcie_num : pcie_num_of(stages[(size_t) st - 1]->pcie_frac); - const int hist_n = std::min(req_sp.penalty_last_n, kPenaltyWindowCap); - ver.set_history(hist_n > 0 ? d_hist : nullptr, hist_n); - bool cancelled = false; - tr("prompt start", n - 1); - // The prompt is read in two parts when it has a turn boundary past `resume`: up to the last <|im_start|> - // (the conversation so far), a checkpoint there, then the new turn's header. The next request of the same - // chat renders the same history - but not always the same header or the thinking of this reply - so that - // checkpoint is the one it reuses. - int64_t turn_at = -1; - if (o.prompt_cache > 0 && o.turn_token >= 0) - for (int64_t i = n - 1; i > resume; --i) - if (ids[(size_t) i] == o.turn_token) { turn_at = i; break; } - // #458 (opt-in): a short turn of --tail-role-token's role right before the new assistant turn (the - // server's trailing reasoning-effort turn) stays out of the checkpoint, so the next request - another - // effort, or the next turn of the chat - finds the conversation without it - if (turn_at > 0 && o.tail_role_token >= 0) - for (int64_t i = turn_at - 1; i > resume; --i) - if (ids[(size_t) i] == o.turn_token) { - if (ids[(size_t) i + 1] == o.tail_role_token) turn_at = i; - break; - } - // A prompt read from token 0 also stops at its FIRST turn boundary: the end of the system prompt (with - // the tools), which every new chat of the same client shares. That checkpoint becomes the chain's root, - // which the retention policy pins (conv_cache.hpp), so the next new chat reads only what comes after it. - // (PR #65, code-martin.) Only for a system prompt of --prompt-cache-root tokens or more: a small one - // is cheaper to read again than the extra part costs (~0.3 s). - int64_t root_at = -1; - if (o.prompt_cache > 0 && o.turn_token >= 0 && o.prompt_cache_root > 0 && (read_from == 0 || resumed_from0)) - for (int64_t i = 1; i < turn_at; ++i) - if (ids[(size_t) i] == o.turn_token) { - if (i >= o.prompt_cache_root) root_at = i; - break; - } - int64_t at = read_from; - for (const int64_t to : {reread_to, root_at, turn_at, n - 1}) { - if (to <= at) continue; - err.clear(); - const bool win = windows_ok(at, to); - if (win && !refill(err)) { - std::printf("ERR refilling a lent slot failed: %s\n", err.c_str()); - return 1; - } - if (!win && !lend(to - at, err)) { - std::printf("ERR lending the prompt path its slots failed: %s\n", err.c_str()); - return 1; - } - const auto tsp = Clock::now(); - const bool sp_ok = win ? read_windows(at, to, err) : read_part(at, to, err); - if (trace) { - std::fprintf(stderr, "strata trace: read %lld tokens (%s) in %.1f ms\n", (long long) (to - at), - win ? "windows" : "batched", - std::chrono::duration(Clock::now() - tsp).count()); - std::fflush(stderr); - } - if (!sp_ok) { - if (yielded_at < 0 && (batch_fatal || !stop_req.load())) { - std::fprintf(stderr, "strata serve: %s\n", err.c_str()); - std::printf("ERR %s\n", err.c_str()); - // #224: a CUDA fault (an illegal address) poisons the context for the whole process, and - // unwinding the destructors on it could hang until the 60 s watchdog: leave at once - if (cudaPeekAtLastError() != cudaSuccess) { - std::fflush(stdout); - std::fflush(stderr); - std::_Exit(1); - } - return 1; - } - cancelled = true; // stopped while reading the prompt: refill the lent slots below, then DONE cancel - break; - } - at = to; - if ((to == turn_at || to == root_at) && !checkpoint_at(to)) { - std::printf("ERR saving a conversation checkpoint failed%s\n", ckpt_why.c_str()); - return 1; - } - } - if (!refill(err)) { - std::printf("ERR refilling a lent slot failed: %s\n", err.c_str()); - return 1; - } - tr("prompt done (slots refilled)"); - if (il_parts > 0) - std::fprintf(stderr, "strata batch: the prompt was read in %lld parts, the slots decoding %.0f ms between " - "them\n", (long long) il_parts + 1, il_ms); - const double prompt_ms = std::chrono::duration(Clock::now() - r0).count(); - std::printf("REUSED %lld\n", (long long) resume); // the prompt is read; the first window comes next - std::fflush(stdout); - // the verify windows: the first holds the last prompt token alone - int64_t p = n - 1; - int32_t x = (int32_t) ids[(size_t) (n - 1)]; - std::vector drafts((size_t) S, 0), window((size_t) S), outv((size_t) S); - std::vector dprob((size_t) S, 0.0f); - std::vector sbuf((size_t) S, 0); - if (o.suffix_draft > 0) { - sfx.reset(); - for (int64_t t : ids) sfx.append((int32_t) t); - } - bool first_window = true; - int64_t produced_n = 0, sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0; - int64_t draft_offered = 0, draft_accepted = 0; - // what the session holds once this request is done: the prompt read so far, then every committed token - std::vector consumed; - consumed.reserve((size_t) (n + max_new + S)); - for (int64_t i = 0; i < n - 1; ++i) consumed.push_back((int32_t) ids[(size_t) i]); - const char* finish = "length"; - const Clock::time_point d0 = Clock::now(); - // STRATA_DECODE_TIMING=1: where a request's decode time goes (one line per request) - static const bool dec_timing = std::getenv("STRATA_DECODE_TIMING") != nullptr; - struct DecSnap { - double wait, pool, host, plan, actq, jobs, run; - int64_t misses, entries, hits, pcie; - }; - auto dec_snap = [&]() { - return DecSnap{ver.ms_wait, ver.ms_pool, ver.ms_host, drive.d.ms_plan, drive.d.ms_actq, drive.d.ms_jobs, - drive.d.ms_run, drive.d.multi_misses, drive.d.multi_entries, drive.d.cache_hits, - drive.d.pcie_experts}; - }; - const DecSnap ds0 = dec_snap(); - double dt_run = 0, dt_commit = 0, dt_draft = 0; - int64_t dec_windows = 0, dec_T = 0; - const int64_t decode_hits0 = drive.d.cache_hits; - // CS-T: the RAM and file tiers of this request (the mmap source; 0 with the arena) - const int64_t ram0 = src.ram_reads(), files0 = src.file_reads(); - const uint64_t file_bytes0 = src.file_read_bytes(); - const int64_t decode_look0 = drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused; - const int64_t offload0 = drive.d.offload_entries; // #588 - if (cancelled) finish = "cancel"; - while (!cancelled && produced_n < max_new) { - int T = S_mtp; - if (req_spec_min_p > 0.0) { - T = 1; - while (T < S_mtp && dprob[(size_t) T - 1] >= (float) req_spec_min_p) ++T; - } - if (first_window) T = 1; - // a repeat of earlier context (prompt lookup) where the MTP's own first guess agrees: the policy takes it - // when its expected tokens per ms, from the measured acceptance and window costs, beat the MTP window's - bool from_sfx = false; - int sfx_match = 0; - if (o.suffix_draft > 0 && !first_window) { - const int k = sfx.propose(S - 1, sbuf.data()); - sfx_match = sfx.last_match(); - if (k > 0 && sbuf[0] == drafts[0]) { - const strata::spec::DraftPolicy::Pick pk = policy.choose(T, k, sfx_match); - if (pk.lookup) { T = pk.t; from_sfx = true; } - } - } - const bool timed_round = !first_window; - const Clock::time_point round0 = Clock::now(); - if (p + T > o.max_context) break; - window[0] = x; - for (int i = 1; i < T; ++i) window[(size_t) i] = from_sfx ? sbuf[(size_t) i - 1] : drafts[(size_t) i - 1]; - drive.d.layers = 0; - drive.d.experts = 0; - drive.d.failed = false; - // #463: the previous adapt round's copies land first - with a non-blocking query, whether a swapped-in - // expert ran on the GPU or the CPU (they round differently) depended on the copy's timing - // (STRATA_ADAPT_NOWAIT=1: 0.1.37's non-blocking query, the A/B) - apply_pending(!adapt_nowait()); - if (hist_n > 0) { - // the tails the penalties count over, ONE PER ROW: the tokens the state has consumed, the - // fed-back head `x` (it joins `consumed` only after this window commits), then the drafts - // before that row - what plain decode would have counted there. (Until 0.1.19 only row 0 - // was staged, and the drafted rows read unwritten slots.) - strata::kernels::penalty_rows(consumed.data(), (int64_t) consumed.size(), window.data(), T, - hist_n, hist_stage.data()); - const strata::core::OnDevice on_h(hist_dev); - cudaMemcpy(d_hist, hist_stage.data(), (size_t) T * (size_t) hist_n * sizeof(int32_t), - cudaMemcpyHostToDevice); - } - tr("window", p, T); - const Clock::time_point tw0 = Clock::now(); - if (!ver.run(T, window.data(), p, win_pool_fn, win_pool_user, outv.data(), err) || drive.d.failed) { - std::printf("ERR %s\n", drive.d.failed && drive.d.fail ? drive.d.fail : err.c_str()); - return 1; - } - 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..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 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; - if (!drive.d.usage.empty() && ((rounds + 1) % o.adapt_every) == 0) - adapt_thr = std::thread([&] { adapt_ok = adapt(); }); - strata::core::progress_at("commit", p); - if (!ver.commit(a + 1, err)) { - if (adapt_thr.joinable()) adapt_thr.join(); - std::printf("ERR %s\n", err.c_str()); - return 1; - } - // the window's first a + 1 tokens are in the session now (the last output is not: it is next x) - for (int i = 0; i <= a; ++i) consumed.push_back(window[(size_t) i]); - draft_offered += T - 1; - draft_accepted += a; - first_window = false; - bool eos = false; - strata::core::progress_at("emit tokens", p); - for (int i = 0; i <= a && produced_n < max_new && !eos; ++i) { - std::printf("T %d\n", (int) outv[(size_t) i]); - strata::core::progress_beat(); - ++produced_n; - if (o.suffix_draft > 0) sfx.append(outv[(size_t) i]); - eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end(); - } - std::fflush(stdout); - ++rounds; - const Clock::time_point tw2 = Clock::now(); - // coupled drafts with penalties: the next window's row-0 history (`consumed` holds this window's - // commit, outv[a] is its row 0) - the drafts extend it on the device as the verify rows will - if (hist_n > 0 && mtp.coupled() && !eos && produced_n < max_new) - mtp.set_draft_history(consumed.data(), (int64_t) consumed.size(), outv[(size_t) a]); - strata::core::progress_at("MTP draft", p); - const bool drafted = eos || produced_n >= max_new || - mtp.draft(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) req_spec_min_p); - { - const Clock::time_point tw3 = Clock::now(); - auto msd = [](Clock::time_point a0, Clock::time_point b0) { return std::chrono::duration(b0 - a0).count(); }; - dt_run += msd(tw0, tw1); dt_commit += msd(tw1, tw2); dt_draft += msd(tw2, tw3); - ++dec_windows; dec_T += T; - } - strata::core::progress_at("adaptive refill join", p); - if (adapt_thr.joinable()) adapt_thr.join(); - if (!adapt_ok) { - std::printf("ERR an adaptive refill failed\n"); - return 1; - } - if (!drafted) { - std::printf("ERR %s\n", err.c_str()); - return 1; - } - if (timed_round && !eos) - policy.observe(from_sfx, T, a, sfx_match, - std::chrono::duration(Clock::now() - round0).count()); - if (eos) { finish = "stop"; break; } - if (stop_req.load()) { finish = "cancel"; break; } - x = outv[(size_t) a]; - p += a + 1; - } - const double decode_ms = std::chrono::duration(Clock::now() - d0).count(); - // the last commit (set_commit_async): the session is complete before anything reads or copies it - if (!ver.wait_commit(err)) { - std::printf("ERR %s\n", err.c_str()); - return 1; - } - if (dec_timing && dec_windows > 0) { - const DecSnap d1 = dec_snap(); - const double w = (double) dec_windows, L = (double) g.n_layers; - std::fprintf(stderr, "strata decode timing: %lld windows, avg T %.2f, %.2f tokens/window, %.2f ms/window = " - "verify %.2f (GPU-reach wait %.2f + per-layer host %.2f [plan %.2f actq %.2f jobs %.2f " - "CPU %.2f] + stage %.2f) + commit/emit %.2f + draft %.2f; per layer-window: CPU experts " - "%.2f (%.2f entries), VRAM hits %.2f, PCIe %.2f\n", - (long long) dec_windows, dec_T / w, produced_n / w, decode_ms / w, dt_run / w, - (d1.wait - ds0.wait) / w, (d1.pool - ds0.pool) / w, (d1.plan - ds0.plan) / w, - (d1.actq - ds0.actq) / w, (d1.jobs - ds0.jobs) / w, (d1.run - ds0.run) / w, - (d1.host - ds0.host) / w, dt_commit / w, dt_draft / w, (d1.misses - ds0.misses) / (w * L), - (d1.entries - ds0.entries) / (w * L), (d1.hits - ds0.hits) / (w * L), (d1.pcie - ds0.pcie) / (w * L)); - const std::string pr = ver.profile_report(); - if (!pr.empty()) std::fprintf(stderr, "strata decode GPU stages (ms/window):%s\n", pr.c_str()); - } - if (!cancelled) { - // a prompt stopped halfway leaves the session somewhere between two chunks: nothing to continue from - // (the checkpoints taken while reading it are still good) - live.swap(consumed); - live_imgs = imgs_below(req_imgs, (int64_t) live.size()); - live_ok = o.prompt_cache > 0; - } - static const bool state_hash = std::getenv("STRATA_STATE_HASH") != nullptr; - if (state_hash && live_ok) { - // DEBUG: a fingerprint of every part of the session over the positions it holds ([0, L)), and - // separately of what lies past them in the last KV page (stale cells, fine unless something reads them) - if (cudaDeviceSynchronize() != cudaSuccess) { - std::printf("ERR synchronizing state fingerprint\n"); - return 1; - } - const int64_t L = (int64_t) live.size(); - const strata::kernels::QsaShapes qs = [&] { - strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_dim = g.idx_key_dim; - return s; - }(); - bool hash_ok = true; - std::array hash_buffer; - auto hash_dev = [&](const void* p, size_t bytes, uint64_t h) { - for (size_t offset = 0; hash_ok && offset < bytes;) { - const size_t n = std::min(hash_buffer.size(), bytes - offset); - // VRAM or a streamed host copy, with fixed diagnostic workspace. - if (cudaMemcpy(hash_buffer.data(), static_cast(p) + offset, n, cudaMemcpyDefault) != cudaSuccess) { - hash_ok = false; - break; - } - h = fnv1a(hash_buffer.data(), n, h); - offset += n; - } - return h; - }; - // the cells [c0, c1) of one int8 K or V pool ([page][kv_head][page_size][head_dim]), bytes per value `w` - auto hash_cells = [&](const void* pool, int64_t per_cell, int64_t c0, int64_t c1, uint64_t h) { - const int64_t ps = qs.page_size; - for (int64_t pg = c0 / ps; pg * ps < c1; ++pg) - for (int64_t hd = 0; hd < qs.n_head_kv; ++hd) { - const int64_t a = std::max(c0, pg * ps) - pg * ps, e = std::min(c1, (pg + 1) * ps) - pg * ps; - const size_t off = (size_t) (((pg * qs.n_head_kv + hd) * ps + a) * per_cell); - h = hash_dev((const uint8_t*) pool + off, (size_t) ((e - a) * per_cell), h); - } - return h; - }; - const ConvStateSizes z = conv_state_sizes(g, ss); - uint64_t h_gdn = hash_dev(ss.gdn_state, z.gdn, 1469598103934665603ull); - if (std::getenv("STRATA_STATE_HASH_GDN") != nullptr && ss.gdn_alloc > 0) { // per GDN layer: which one differs first - const size_t per = z.gdn / (size_t) ss.gdn_alloc; - std::string s; - char b[8]; - for (int64_t i = 0; i < ss.gdn_alloc; ++i) { - std::snprintf(b, sizeof(b), "%04llx ", (unsigned long long) (hash_dev((const uint8_t*) ss.gdn_state + i * per, per, 1469598103934665603ull) & 0xffff)); - s += b; - } - std::fprintf(stderr, "strata serve: STATE_HASH_GDN %s\n", s.c_str()); - } - uint64_t h_ple = hash_dev(ss.ple_hist, ss.ple_hist ? z.ple : 0, 1469598103934665603ull); - uint64_t h_tail = 1469598103934665603ull, h_pool = h_tail, h_kv = h_tail, h_stale = h_tail; - // pooled= keeps its 0.1.29 meaning: the completed rows [0, L / idx_block) only. pooled_full= adds the - // spare row at L / idx_block (the `dead` key the next block completion overwrites), which a - // conversation restore writes back; dead= is the spare key itself - uint64_t h_dead = h_tail, h_pool_full = h_tail; - const int64_t kvb = qs.head_dim, scb = (qs.head_dim / 64) * 2; - // a state's K/V arrays and their bytes per (cell, head) row: the host copy when it has one - auto kv_arrays = [&](const strata::core::QsaState& st) { - const bool h = st.kv_mode != 0; - std::vector> a; - if (st.kv_q4) { - const int64_t q4b = (int64_t) strata::kernels::kv_q4_bytes_per_head((int) qs.head_dim); - a = {{h ? st.host.k_q4 : st.k_q4, q4b}, {h ? st.host.v_q4 : st.v_q4, q4b}}; - } else if (st.kv_hybrid) { - const int64_t q4b = (int64_t) strata::kernels::kv_q4_bytes_per_head((int) qs.head_dim); - a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q4 : st.v_q4, q4b}, - {h ? st.host.k_scale : st.k_scale, scb}}; - } else if (st.kv_int8) { - a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q : st.v_q, kvb}, - {h ? st.host.k_scale : st.k_scale, scb}, {h ? st.host.v_scale : st.v_scale, scb}}; - } else { - a = {{h ? st.host.k_pool : st.k_pool, qs.head_dim * 2}, - {h ? st.host.v_pool : st.v_pool, qs.head_dim * 2}}; - } - return a; - }; - const int64_t end_cell = std::min(((L + qs.page_size - 1) / qs.page_size) * qs.page_size, - ss.max_cells); // = the primary state's max_cells - for (int64_t j = 0; j < ss.qsa_alloc; ++j) { // this session's owned QSA ordinals only - const strata::core::QsaState& st = ss.qsa_states[ss.qsa_ord0 + j]; - h_tail = hash_dev(st.idx_tail, z.tail, h_tail); - h_dead = hash_dev(st.idx_dead, z.dead, h_dead); - h_pool = hash_dev(st.idx_pooled, (size_t) (L / qs.idx_block) * qs.idx_dim * 4, h_pool); - h_pool_full = hash_dev(st.idx_pooled, (size_t) (L > 0 ? L / qs.idx_block + 1 : 0) * qs.idx_dim * 4, - h_pool_full); - // KV streaming: the host copy is the identity layout and holds every cell - for (const auto& [pool, w] : kv_arrays(st)) { - h_kv = hash_cells(pool, w, 0, L, h_kv); - h_stale = hash_cells(pool, w, L, end_cell, h_stale); - } - } - const strata::core::QsaState& ms = mtp.kv_state(); - uint64_t h_mtp = 1469598103934665603ull; - const int64_t mL = std::min(L, ms.max_cells); - for (const auto& [pool, w] : kv_arrays(ms)) - if (pool != nullptr) h_mtp = hash_cells(pool, w, 0, mL, h_mtp); - if (!hash_ok) { - std::printf("ERR reading state fingerprint\n"); - return 1; - } - std::fprintf(stderr, "strata serve: STATE_HASH L=%lld gdn=%016llx ple=%016llx tail=%016llx pooled=%016llx " - "kv=%016llx mtp=%016llx stale=%016llx dead=%016llx pooled_full=%016llx ple_prev=%d,%d\n", (long long) L, - (unsigned long long) h_gdn, (unsigned long long) h_ple, (unsigned long long) h_tail, - (unsigned long long) h_pool, (unsigned long long) h_kv, (unsigned long long) h_mtp, - (unsigned long long) h_stale, (unsigned long long) h_dead, - (unsigned long long) h_pool_full, ss.ple_prev[0], ss.ple_prev[1]); - } - const int64_t req_hits = drive.d.cache_hits - decode_hits0; - const int64_t req_look = (drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused) - decode_look0; - const int64_t req_offload = drive.d.offload_entries - offload0; - // #471: the prompt tokens this request read - all the fresh ones, or as far as the prompt pass got when a - // cancel stopped it part-way (a cancelled request used to be logged and counted as having read them all) - const int64_t fresh = n - resume; - const int64_t read_n = cancelled ? std::clamp(pp_reached - resume, 0, fresh) : fresh; - // DONE [hits] [lookups] - // [RAM blobs] [file blobs] [file MB] (CS-T tiers; appended, so an older server reads the rest) - // [prompt tokens read] (#471: fewer than - when a cancel stopped the read) - // [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, - (long long) resume, (long long) req_hits, (long long) req_look, - (long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0), - (double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n, - (long long) req_offload); - std::fflush(stdout); - if (admit_slot >= 0) { // --batch: BADM <1 = continues in the batch windows | 0 = done> - bool cont = !cancelled && produced_n == 1 && admit_max_new > 1 && std::strcmp(finish, "length") == 0 && - (int64_t) live.size() == p; - const auto tc0 = Clock::now(); - if (cont && !copy_to_slot(admit_slot, live, err)) { - std::fprintf(stderr, "strata serve: batch admission failed: %s\n", err.c_str()); - bs[(size_t) admit_slot].cached = false; // its sessions may be half written - cont = false; - } - if (cont) { - ver.set_slot_sampling(admit_slot, req_sp); // the request's own sampling, row by row - BSlot& sl = bs[(size_t) admit_slot]; - sl = BSlot{}; - sl.active = true; - sl.x = x; - sl.p = p; - sl.produced = 1; - sl.max_new = admit_max_new; - sl.t0 = Clock::now(); - sl.ids = live; - sl.cvec = cvec_cached; - sl.img = !live_imgs.empty(); // pictures: not matched again by tokens alone, so not cached - const ConvCheckpoint* best = nullptr; - for (const ConvCheckpoint& c : checks) - if (c.ids.size() < live.size() && (best == nullptr || c.ids.size() > best->ids.size()) && - std::equal(c.ids.begin(), c.ids.end(), live.begin())) - best = &c; - if (best != nullptr && !sl.img) sl.checks.push_back(*best); - std::fprintf(stderr, "strata batch: slot %d takes %lld tokens (copied in %.1f ms)\n", admit_slot, - (long long) live.size(), std::chrono::duration(Clock::now() - tc0).count()); - } - std::printf("BADM %d %d\n", admit_slot, cont ? 1 : 0); - std::fflush(stdout); - admit_slot = -1; - } - if (drive.routing != nullptr) std::fflush(drive.routing); // the routing trace survives a crash and is watchable mid-session - // "12288 of 98179" when cancelled mid-read (#471), the rate from what was read - char read_txt[64]; - if (cancelled) - std::snprintf(read_txt, sizeof(read_txt), "%lld of %lld", (long long) read_n, (long long) fresh); - else - std::snprintf(read_txt, sizeof(read_txt), "%lld", (long long) fresh); - std::fprintf(stderr, "strata serve: prompt %lld tokens = %lld reused + %s read in %.0f ms (%.1f tok/s), " - "%lld generated in %.0f ms (%.1f tok/s), drafts accepted %lld of %lld, %zu checkpoints%s\n", - (long long) n, (long long) resume, read_txt, prompt_ms, - prompt_ms > 0 ? 1000.0 * read_n / prompt_ms : 0.0, (long long) produced_n, decode_ms, - decode_ms > 0 ? 1000.0 * produced_n / decode_ms : 0.0, (long long) draft_accepted, - (long long) draft_offered, checks.size(), cancelled ? " (cancelled)" : ""); - // the VRAM share of the experts the pool looked up while decoding; experts it sent over PCIe for the GPU - // to read (--pcie-frac) are in neither count - #588: so that share is said beside it (raising --pcie-frac - // raises the hit rate while the PCIe reads may make the decode slower) - if (req_look > 0) { - char off[160] = ""; - if (req_offload > 0) - std::snprintf(off, sizeof off, "; %lld more read by the GPU over PCIe or from another GPU (%.1f%% of " - "all %lld routed)", (long long) req_offload, - 100.0 * (double) req_offload / (double) (req_look + req_offload), - (long long) (req_look + req_offload)); - std::fprintf(stderr, "strata serve: decode expert cache hit rate: %.1f%% (%lld hits / %lld lookups)%s\n", - 100.0 * (double) req_hits / (double) req_look, - (long long) req_hits, (long long) req_look, off); - } - // the resident RAM mode, cumulative: experts read from experts.bin since the copy was made (what the plain - // mmap mode reads through the OS file cache, from the SSD when the RAM could not keep it) - if (src.complement_ready()) - std::fprintf(stderr, "strata serve: resident RAM: %.2f GiB of experts in RAM, %lld exchanged with the " - "VRAM tier, %lld blob reads from the file\n", - (double) src.resident_bytes() / 1073741824.0, (long long) src.exchanges(), - (long long) src.file_reads()); - // CS-T: the tiers, cumulative - GPU cache hits (the decode lookups above), RAM copy, files (SSD / OS cache) - if (srcp == &src) - std::fprintf(stderr, "strata serve: expert tiers: GPU %lld hits this request; since the start RAM %lld blobs, files %lld blobs " - "%.1f MB read%s\n", (long long) req_hits, (long long) src.ram_reads(), - (long long) src.file_reads(), (double) src.file_read_bytes() / 1e6, - src.gguf_mode() ? " (the GGUF in place)" : ""); - // STRATA_SPLIT_TIMING: where each verify stage's host time went, cumulative per window since the start - // (waiting for its GPU to ring a layer, the CPU pool and plan per layer, staging the window) - if (static const bool st_timing = std::getenv("STRATA_SPLIT_TIMING") != nullptr; st_timing) - for (int st = 0; st < n_stages; ++st) { - const strata::core::Verifier& v = stage_ver(st); - const double w = v.windows > 0 ? (double) v.windows : 1.0; - std::fprintf(stderr, "strata serve: stage %d: %lld windows; per window: wait for the GPU %.3f ms, " - "pool + plan %.3f ms, host staging %.3f ms, commit %.3f ms\n", st, - (long long) v.windows, v.ms_wait / w, v.ms_pool / w, v.ms_host / w, v.ms_commit / w); - } - if (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1) { - // KV streaming, cumulative over the process: blocks the selections named vs blocks read from RAM - // (this device's owned ordinals; a split's other stages hold theirs) - uint64_t miss = 0, look = 0; - bool over = false; - for (int64_t j = 0; j < ss.qsa_alloc; ++j) { - const strata::kernels::KvStreamCounters c = - strata::kernels::kv_stream_counters(ss.qsa_states[ss.qsa_ord0 + j].map); - miss += c.misses; look += c.lookups; over = over || c.overflow; - } - std::fprintf(stderr, "strata serve: KV streaming: %.2f%% of %llu block reads hit VRAM, %.1f MiB read " - "from RAM%s\n", look ? 100.0 * (double) (look - miss) / (double) look : 100.0, - (unsigned long long) look, (double) miss * 4224.0 / 1048576.0, - over ? " - OVERFLOW (too few resident cells)" : ""); - } - if (sfx_windows > 0) - std::fprintf(stderr, "strata serve: suffix drafts: %lld windows, %lld of %lld drafts accepted\n", - (long long) sfx_windows, (long long) sfx_ok, (long long) sfx_drafts); - for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) - std::fprintf(stderr, "strata serve: CUDA%d: %lld expert entries, %lld active layer launches, %.1f MiB returned " - "(%.1f MiB with full rows) in this request; host %.0f ms staging+launching, %.0f ms " - "waiting for it in this request\n", r + 1, - (long long) (remote_experts[(size_t) r].computed() - remote_before[(size_t) r]), - (long long) (remote_experts[(size_t) r].launched_layers() - launches_before[(size_t) r]), - (double) (remote_experts[(size_t) r].returned_bytes() - compact_before[(size_t) r]) / 1048576.0, - (double) (remote_experts[(size_t) r].full_row_bytes() - full_before[(size_t) r]) / 1048576.0, - remote_experts[(size_t) r].ms_begin() - begin_before[(size_t) r], - remote_experts[(size_t) r].ms_wait() - wait_before[(size_t) r]); - } - save_profile("exit"); // #477: QUIT, or the server closed stdin - return 0; - } - - // ---- plan v0.3 P5: the prompt's conditioning positions [0, n_prompt - 1) in batched chunks. The token loop - // then starts at the last prompt position, whose prediction is the first generated token. - int64_t pos_start = 0; - int64_t spec_pos = 0; // plan v0.3 P6: where the speculative loop starts (0 = not used) - strata::prefill::Prefill prefill; - double prefill_batched_ms = 0; - std::FILE* final_r = o.dump_final_r.empty() ? nullptr : std::fopen(o.dump_final_r.c_str(), "wb"); - std::vector final_r_host(final_r ? (size_t) (g.hc * g.n_embd) : 0); - std::vector> lent; // (residency index, slot) lent to the prompt path - const int64_t n_batched = (o.prefill_until > 0 && o.prefill_until < n_prompt - 1) ? o.prefill_until : n_prompt - 1; - if (o.prefill_chunk > 0 && n_prompt > 1) { - void* borrow = nullptr; - uint64_t borrow_bytes = 0; - if (!o.no_prefill_borrow && !host_res.empty() && d_res != nullptr) { - int64_t chunk = o.prefill_chunk; - int64_t k = plan_lend(chunk); // auto: the largest chunk that fits; fixed: halved to fit - const int64_t request_sized = request_chunk(n_batched, chunk); - if (k > 0 && request_sized < chunk) { // no bigger than this prompt segment needs - chunk = request_sized; - k = lend_slots(chunk); - if (k + 128 > xcache.slots()) k = 0; - if (!o.prefill_auto) o.prefill_chunk = chunk; - } - if (o.prefill_auto) { - o.prefill_chunk = k > 0 ? chunk : request_chunk(n_batched, 1024); - std::fprintf(stderr, "strata generate: prompt chunk auto: %lld tokens\n", (long long) o.prefill_chunk); - } else if (chunk != o.prefill_chunk) { - k = 0; // a fixed chunk that does not fit: its own buffers, as before - } - const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; - if (k > 0) { // the lent slots are refilled after the prompt - const int32_t first = (int32_t) (xcache.slots() - k); - for (size_t i = 0; i < host_res.size(); ++i) - if (host_res[i] >= first) { - lent.emplace_back((int32_t) i, host_res[i]); - host_res[i] = strata::core::kNotResident; - } - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); - borrow = xcache.device_slot(first); - borrow_bytes = xcache.slot_offsets() ? (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[first]) - : (uint64_t) k * (uint64_t) blob; - std::fprintf(stderr, "strata generate: prompt path borrows %lld cache slots (%.2f GiB)\n", (long long) k, - (double) borrow_bytes / 1073741824.0); - } - } - if (borrow == nullptr) - std::fprintf(stderr, "strata generate: prompt path allocates its own buffers (no cache slots to borrow)\n"); - if (!prefill.init(wt, g, ss, srcp, o.expert_cache > 0 ? &xcache : nullptr, - host_res.empty() ? nullptr : host_res.data(), o.prefill_chunk, main_cs, err, borrow, - borrow_bytes)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - if (!o.mtp.empty()) { - if (!mtp.bind(wt, &native_head, nullptr, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - prefill.on_chunk = [&](const float* R_rows, int64_t T, int64_t p0, std::string& e) -> bool { - // cell i pairs R_i with the token at i + 1 (every such token is in the prompt) - std::vector nxt((size_t) T); - for (int64_t t = 0; t < T; ++t) nxt[(size_t) t] = (int32_t) o.tokens[(size_t) (p0 + t + 1)]; - if (prefill.draft_kv(mtp, R_rows, nxt.data(), T, p0, e)) return true; // E-9 - return e.empty() && mtp.prefill(R_rows, nxt.data(), T, p0, e); - }; - } - const Clock::time_point tp0 = Clock::now(); - if (!prefill.run(o.tokens.data(), n_batched, 0, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - // refill the lent slots from the arena and give them back to the decode tier - if (!lent.empty()) { - const Clock::time_point tr = Clock::now(); - for (const auto& [i, slot] : lent) { // D-4: queued, one wait (STRATA_REFILL_BLOCKING=1: each) - const uint8_t* b = srcp->blob(i / g.n_expert, i % g.n_expert); - const int64_t nb = (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(i / g.n_expert); - if (b == nullptr || !(refill_blocking() ? xcache.fill_slot_blocking(slot, b, err, nb) - : xcache.fill_slot_queued(slot, b, err, nb))) { - std::fprintf(stderr, "strata generate: refilling a lent slot failed: %s\n", err.c_str()); - return 1; - } - host_res[(size_t) i] = slot; - } - if (!xcache.sync_queued(err)) { - std::fprintf(stderr, "strata generate: refilling the lent slots failed: %s\n", err.c_str()); - return 1; - } - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); - std::fprintf(stderr, "strata generate: %zu lent slots refilled in %.1f ms\n", lent.size(), - std::chrono::duration(Clock::now() - tr).count()); - } - prefill_batched_ms = std::chrono::duration(Clock::now() - tp0).count(); - prefill_ms += prefill_batched_ms; - pos_start = n_batched; - tok = o.tokens[(size_t) pos_start]; - // the PLE window of the token path: the two tokens before `pos_start` - ss.ple_prev[0] = pos_start >= 2 ? (int32_t) o.tokens[(size_t) (pos_start - 2)] : -1; - ss.ple_prev[1] = pos_start >= 1 ? (int32_t) o.tokens[(size_t) (pos_start - 1)] : -1; - const strata::prefill::PrefillStats& ps = prefill.stats(); - std::fprintf(stderr, "strata generate: prefill %lld tokens in %lld chunks, %.1f ms (%.1f tok/s); experts " - "streamed %lld (%lld by DMA, host %.1f ms), resident %lld; PLE %.1f ms\n", - (long long) ps.tokens, (long long) ps.chunks, ps.ms_total, - ps.ms_total > 0 ? 1000.0 * (double) ps.tokens / ps.ms_total : 0.0, (long long) ps.experts_streamed, - (long long) ps.experts_dma, ps.ms_experts_host, (long long) ps.experts_resident, ps.ms_ple); - } - - for (int64_t pos = pos_start;; ++pos) { - // plan v0.3 P6: a native pack's last prompt token is the first verify window (T = 1) - if (native_pack) { spec_pos = pos; break; } - if (pos >= o.max_context) { - std::fprintf(stderr, "strata generate: ran out of context at position %lld\n", (long long) pos); - return 2; - } - // **THE TOKEN TIMER STARTS HERE, BEFORE ANY OF THE TOKEN'S WORK (A7).** It used to start after - // `put_input`/`embed_row`, which excluded the embedding and the PLE window advance from the reported - // rate, and it stopped before the NaN scan, the logits dump and the sampler. The published tok/s - // figure is a WALL-CLOCK rate: everything one token costs, PLE advance to sampled id. A rate that - // excludes real per-token work is not a rate anyone can plan against. - const Clock::time_point t0 = Clock::now(); - // **THE PLE'S TOKEN WINDOW ADVANCES HERE, ONCE PER TOKEN, AND `ple_stage_token` RUNS OUTSIDE THE - // CAPTURE.** Both are the driver's job: `ngram_rows` is a host hash over the last three tokens and the - // table gather is a host read, so either one inside a captured graph would run once at capture time and - // replay forever. `ple_prev` is OLDEST FIRST and `-1` means "no predecessor", which `ngram_rows` - // treats as the EOS cut - a sequence boundary. - ss.ple_token = (int32_t) tok; - Clock::time_point tp = Clock::now(); - // Plan v0.3 P2: the 16 SSD reads start here and complete while the embedding is staged; `ms_ple` is - // the issue plus the time still spent WAITING afterwards, i.e. the part the embedding did not hide. - if (ss.ple.ready() && !strata::core::ple_issue_token(ss.ple, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - { - const Clock::time_point n = Clock::now(); - ms_ple += std::chrono::duration(n - tp).count(); - tp = n; - } - if (!put_input(tok, pos)) return 1; - { - const Clock::time_point n = Clock::now(); - ms_embed += std::chrono::duration(n - tp).count(); - tp = n; - } - if (ss.ple.ready() && !strata::core::ple_finish_token(ss.ple, token_stream, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - { - const Clock::time_point n = Clock::now(); - ms_ple += std::chrono::duration(n - tp).count(); - tp = n; - } - - if (pos % 256 == 0 || pos + 1 >= n_prompt - 1) - std::fprintf(stderr, "strata generate: position %lld, token %lld%s\n", (long long) pos, (long long) tok, - pos < n_prompt ? " (prompt)" : ""); - // **`d.layers` IS THE BLOB'S LAYER AXIS, NOT A COUNTER.** The adapter uses it to index - // `experts.bin` as `layer * n_expert + expert`, so it MUST restart at 0 for every token. Leaving it - // running across tokens asks for layer 48 of a 48-layer file on the second token - which - // `FileExpertSource` REFUSES rather than wrapping into layer 0's experts, and that refusal is the only - // reason this was a clean error instead of a silently wrong second token. - drive.d.layers = 0; - drive.d.experts = 0; - drive.d.failed = false; - err.clear(); - if (o.no_capture) { - if (!strata::core::session_token(wt, g, pos, /*pos_base=*/0, ss, d_parts, main_cs, - o.sync_every_layer, err)) { - std::fprintf(stderr, "strata generate: session_token: %s\n", err.c_str()); - return 1; - } - } else { - strata::core::doorbell_reset(db); - if (tgraph.captured) { - if (!strata::core::session_run_token(g, pos, /*pos_base=*/0, ss, tgraph, pool_fn, pool_user, - loop_scratch.y_miss, main_cs, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - } else if (!strata::core::session_loop(g, pos, /*pos_base=*/0, ss, gr, pool_fn, hit_fn, pool_user, /*overlap=*/true, main_cs, - err, layer_stage, &loop_scratch)) { - std::fprintf(stderr, "strata generate: session_loop: %s\n", err.c_str()); - return 1; - } - } - if (final_r != nullptr) { - cudaMemcpy(final_r_host.data(), ss.R, final_r_host.size() * sizeof(float), cudaMemcpyDeviceToHost); - const int64_t posrec[2] = {pos, tok}; - std::fwrite(posrec, sizeof posrec, 1, final_r); - std::fwrite(final_r_host.data(), sizeof(float), final_r_host.size(), final_r); - } - if (drive.d.failed) { - std::fprintf(stderr, "strata generate: the expert pool failed at layer %lld expert %lld: %s\n", - (long long) drive.d.fail_layer, (long long) drive.d.fail_expert, - drive.d.fail ? drive.d.fail : "(no message)"); - return 1; - } - { - // **THE LAYER LOOP ITSELF, WHICH IS WHAT `--gpu-only-full` HAS TO BE COMPARED AGAINST.** - const Clock::time_point n = Clock::now(); - ms_layers += std::chrono::duration(n - tp).count(); - tp = n; - } - // ---- the ladder for THIS position, in the order `session_loop` filled it: layer 0 first. - if (layer_dump != nullptr) std::fwrite(layer_stage, sizeof(float), layer_floats, layer_dump); - if (half_dump != nullptr) { - std::fwrite(half_stage, sizeof(float), (size_t) g.n_layers * (size_t) half_stride, half_dump); - } - if (!run_head(token_stream)) { - std::fprintf(stderr, "strata generate: lm_head: %s\n", err.c_str()); - return 1; - } - // **A CHECKPOINT AFTER THE HEAD, BECAUSE AN ASYNC FAULT IS STICKY AND LIES ABOUT WHERE IT HAPPENED.** - // Measured, and it cost an hour: without this, `embed_row`'s D2H on the NEXT token reported "an illegal - // memory access" at a plane offset that has nothing to do with the fault, and the layer that actually - // faulted had completed its own error checks successfully - because its kernels had not run yet. A - // sticky error surfaces at the next SYNCHRONISING call, which is whatever happens to come next. - if (!o.stream_token && cudaDeviceSynchronize() != cudaSuccess) { - std::fprintf(stderr, "strata generate: the device faulted in lm_head at position %lld: %s\n", - (long long) pos, cudaGetErrorString(cudaGetLastError())); - return 1; - } - { - const Clock::time_point n = Clock::now(); - ms_head += std::chrono::duration(n - tp).count(); - tp = n; - } - const bool emit_logits = dump != nullptr && - strata::program::logits_selection::selected(pos, dump_positions, o.logits_stride); - const bool read_logits = !o.stream_token || o.check_logits || emit_logits; - if (read_logits && (cudaMemcpyAsync(logits.data(), d_logits, (size_t) n_vocab * 4, - cudaMemcpyDeviceToHost, (cudaStream_t) token_stream) != cudaSuccess || - cudaStreamSynchronize((cudaStream_t) token_stream) != cudaSuccess)) { - std::fprintf(stderr, "strata generate: reading the logits back failed\n"); - return 1; - } - int bad = 0; - if (read_logits) for (float v : logits) if (!std::isfinite(v)) ++bad; - if (bad != 0) { - std::fprintf(stderr, "strata generate: %d of %lld logits are not finite at position %lld\n", bad, - (long long) n_vocab, (long long) pos); - return 1; - } - // the header with the first row (see `hdr`): a run that dumps nothing leaves an empty file - if (emit_logits && !hdr_written && std::fwrite(hdr, sizeof hdr, 1, dump) != 1) { - std::fprintf(stderr, "strata generate: cannot write logits header\n"); - std::fclose(dump); - return 1; - } - if (emit_logits) hdr_written = true; - if (emit_logits && std::fwrite(logits.data(), sizeof(float), (size_t) n_vocab, dump) != (size_t) n_vocab) { - std::fprintf(stderr, "strata generate: cannot write logits at position %lld\n", (long long) pos); - std::fclose(dump); - return 1; - } - { - // **993 KB OF SYNCHRONOUS D2H AND A 248,320-FLOAT HOST SCAN, EVERY TOKEN.** (The review's notes - // say 151,936 floats; the artifact's `output.weight` is 248,320 rows, so the real figure is 1.6x - // that - a number nobody had checked because nothing measured this term.) R2.6 asks for the dump - // and the scan to be behind flags; round 36 did exactly that and measured it SLOWER, because on - // this driver a large blocking readback is also what flushes the pipeline for the sampler that - // follows. Timed so the claim can be re-checked rather than remembered. - const Clock::time_point n = Clock::now(); - ms_readback += std::chrono::duration(n - tp).count(); - tp = n; - } - - int next = 0; - // The draw is Philox(seed, position), as in a verify window (row t at pos0 draws pos0 + t): a seed gives - // the same text whether a token comes from this path or from the speculative loop below. - sp.counter = (uint64_t) pos; - strata::kernels::sample_tokens(d_logits, 1, (int) n_vocab, nullptr, 0, sp, d_next, token_stream); - if (cudaMemcpyAsync(&next, d_next, sizeof(int), cudaMemcpyDeviceToHost, - (cudaStream_t) token_stream) != cudaSuccess || - cudaStreamSynchronize((cudaStream_t) token_stream) != cudaSuccess) { - std::fprintf(stderr, "strata generate: reading the sampled token back failed: %s\n", - cudaGetErrorString(cudaGetLastError())); - return 1; - } - // The sampled-token synchronization also completes every captured QSA - // status readback. Retain one status per layer so a later layer cannot - // hide an earlier failure; no extra synchronization or token allocation. - if (o.native_flash_attn_short) for (int64_t j = 0; j < ss.qsa_alloc; ++j) { - const int64_t i = ss.qsa_ord0 + j; // the global ordinal, as the session's carve names it - const int32_t status = ss.qsa_states[i].host_step[strata::kernels::kStepCount]; - if (status != 0) { - std::fprintf(stderr, "strata generate: native attention status %d at QSA layer %lld, position %lld\n", - status, (long long) i, (long long) pos); - return 1; - } - } - if (next < 0 || next >= n_vocab) { - std::fprintf(stderr, "strata generate: the sampler returned %d, outside 0..%lld\n", next, - (long long) (n_vocab - 1)); - return 1; - } - { - // **TWO DEVICE-WIDE SYNCS FOR FOUR BYTES.** `sample_tokens(nullptr)` ends in - // `cudaDeviceSynchronize()` (`sampler.cu:245`) and the blocking 4-byte read below is the second. - const Clock::time_point n = Clock::now(); - ms_sample += std::chrono::duration(n - tp).count(); - ++phase_tokens; - } - // CHARGED HERE, AFTER THE SAMPLER, so the wall-clock rate covers the whole token including the embedding, - // the NaN scan, the logits readback and the sample (A7). Only DECODE positions count; prefill is - // measured separately. - if (pos >= n_prompt - 1) total_ms += std::chrono::duration(Clock::now() - t0).count(); - else prefill_ms += std::chrono::duration(Clock::now() - t0).count(); - if (pos == n_prompt - 1) ttft_ms = std::chrono::duration(Clock::now() - t_start).count(); - // **THE PREDICTION AT THE LAST PROMPT POSITION *IS* THE FIRST GENERATED TOKEN.** Sampling on every - // position and recording only from `n_prompt - 1` onward is what keeps the two cases from needing - // separate handling - and the version that "obviously" only samples after the prompt loses exactly one - // token's worth of conditioning. - if (pos >= n_prompt - 1) produced.push_back(next); - if ((int64_t) produced.size() >= o.max_new) break; - if (o.stop_eos && pos >= n_prompt - 1 && - std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) next) != o.eos_ids.end()) break; - // TEACHER FORCING while the prompt lasts: the next input is the prompt's own next token, not the - // model's guess. Feeding the guess would make the run depend on the model's own errors from position - // 1, which is a different (and worse) measurement of the same prompt. - // and the window advances: the token just decoded becomes the newest predecessor. - ss.ple_prev[0] = ss.ple_prev[1]; - ss.ple_prev[1] = (int32_t) tok; - tok = (pos + 1 < n_prompt) ? o.tokens[(size_t) (pos + 1)] : next; - // Plan v0.3 P6: from the first generated token on, the speculative loop below takes over. - if (o.spec > 0 && pos >= n_prompt - 1) { spec_pos = pos + 1; break; } - } - - // ================================ plan v0.3 P6: SPECULATIVE DECODING ================================ - // - // Each round verifies [the last emitted token, drafts...] in one window; the window's argmax after token t - // is exactly what greedy decode would emit there, so the first draft that differs ends the round and the - // round emits (accepted drafts + 1) tokens. `commit` keeps the state of the tokens that were emitted. - const bool ended = o.stop_eos && !produced.empty() && - std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) produced.back()) != o.eos_ids.end(); - if (spec_pos > 0 && (int64_t) produced.size() < o.max_new && !ended) { - std::vector oracle; - if (!o.spec_oracle.empty()) { - std::ifstream in(o.spec_oracle); - std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); - std::string e; - if (!in || !parse_i64_list(text.c_str(), oracle, e)) { - 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, " - "--expert-cache and the token graph)\n"); - return 2; - } - mem_mark("the head and the prompt path"); - strata::core::Verifier ver; - strata::core::VerifyHits vh; - vh.d_res = thits.d_res; - vh.h_res = host_res.empty() ? nullptr : host_res.data(); - vh.cache_base = thits.cache_base; - vh.blob = thits.blob; - vh.slot_off = xcache.slot_offsets(); // E-6: the device plan's pointers - vh.n_slots = xcache.slots(); - if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - const bool use_mtp = !o.mtp.empty(); - if (use_mtp && !mtp.bind(wt, &native_head, ver.final_R_all(), err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - mem_mark("the verifier and the drafter's binding"); - ver.set_sampling(sp); // the CLI's own sampling (until 0.1.19 this loop was always greedy); no penalties here - if (use_mtp) mtp.set_draft_sampling(sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise) - ver.set_split(o.spec_split); - // auto: the copy kernel for every pack. DMA (the native packs' default until 0.1.13) has the host call - // cudaMemcpyAsync + cudaLaunchHostFunc inside a verify window while the GPU spins on the flag they raise; - // issue #31's thread dumps show the host stuck in that cudaMemcpyAsync on a driver lock for good. The copy - // kernel needs no host CUDA call there, and costs ~1-3% decode on IQ3_S (45.3 -> 44.8 tok/s, 8 requests). - ver.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2); - drive.d.plan = ver.plan_sink(); - drive.d.pcie_num = (int) (o.pcie_frac * 256.0 + 0.5); - if (drive.d.pcie_num < 0) drive.d.pcie_num = 0; - if (drive.d.pcie_num > 256) drive.d.pcie_num = 256; - const int64_t pcie0 = drive.d.pcie_experts; - // CS-T: the file tier since the decode began (the prompt path's copies are before this) - const int64_t files0 = src.file_reads(), ram0 = src.ram_reads(); - const uint64_t fbytes0 = src.file_blob_bytes(), fall0 = src.file_read_bytes(); - const double fms0 = src.file_ms(); - if (o.adapt_every > 0 && o.adapt_swaps > 0) drive.d.usage.assign((size_t) (g.n_layers * g.n_expert), 0.0f); - int64_t swaps_total = 0; - double ms_adapt = 0; - cudaStream_t adapt_stream = nullptr; - if (!drive.d.usage.empty() && cudaStreamCreateWithFlags(&adapt_stream, cudaStreamNonBlocking) != cudaSuccess) { - std::fprintf(stderr, "strata generate: cannot create the refill stream\n"); - return 1; - } - // plan v0.3 P6: swaps in flight - (residency index, slot) admitted when adapt_ev has completed - std::vector> pending; - std::vector pin_live; // the swaps' locked arena pages (pin_blob), unlocked once they have landed - cudaEvent_t adapt_ev = nullptr; - cudaEventCreateWithFlags(&adapt_ev, cudaEventDisableTiming); - int64_t adapt_rounds = 0; // counted here: `rounds` is declared below the adapt lambda - auto apply_pending = [&](bool wait) { - if (pending.empty()) return; - // STRATA_TRACE_ADAPT=1: whether a round's copies had landed when the next window read the table - static const bool trace_pending = std::getenv("STRATA_TRACE_ADAPT") != nullptr; - if (wait) cudaEventSynchronize(adapt_ev); - else if (cudaEventQuery(adapt_ev) != cudaSuccess) { - if (trace_pending) - std::fprintf(stderr, "strata: PENDING not landed, %zu stay non-resident this window\n", - pending.size()); - return; - } - if (trace_pending) - std::fprintf(stderr, "strata: PENDING landed, %zu experts become resident\n", pending.size()); - unpin_blobs(pin_live); - src.commit_exchanges(); // the resident RAM mode: the evicted experts take their places in RAM - for (const auto& [i, slot] : pending) { - host_res[(size_t) i] = slot; - srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert); // in VRAM now: RAM not needed - } - pending.clear(); - if (d_res != nullptr) - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); - }; - // Plan v0.3 P6: the VRAM tier follows the conversation. Candidates are missing experts routed at least - // twice (decayed); each is paired with its layer's least-routed resident expert and swapped when it was - // routed clearly more often. Copies run between rounds, when the GPU is idle. - auto adapt = [&]() -> bool { - const Clock::time_point ta = Clock::now(); - ++adapt_rounds; - // STRATA_TRACE_ADAPT: why an adapt round did or did not swap. Default off, one getenv, and it - // reports the only thing that can make an adapt round a coin flip: whether the PREVIOUS round's - // asynchronous expert copies had landed by the time this round started. - static const bool trace_adapt = std::getenv("STRATA_TRACE_ADAPT") != nullptr; - if (!pending.empty()) { - if (trace_adapt) - std::fprintf(stderr, "strata: ADAPT round=%lld SKIPPED, %zu swaps still in flight\n", - (long long) adapt_rounds, pending.size()); - return true; // the previous swaps are still in flight - } - if (trace_adapt) std::fprintf(stderr, "strata: ADAPT round=%lld considering\n", (long long) adapt_rounds); - struct Swap { float gain; int32_t layer, in, out; }; - std::vector swaps; - std::vector> cand, vict; - for (int64_t l = 0; l < g.n_layers; ++l) { - cand.clear(); - vict.clear(); - const float* u = drive.d.usage.data() + l * g.n_expert; - const int32_t* r = host_res.data() + l * g.n_expert; - for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) { - if (r[e] < 0) { if (u[e] >= 2.0f) cand.emplace_back(u[e], e); } - else vict.emplace_back(u[e], e); - } - if (cand.empty() || vict.empty()) continue; - std::sort(cand.begin(), cand.end(), [](auto& a, auto& b) { return a.first > b.first; }); - const size_t nc = std::min(cand.size(), vict.size()); - std::partial_sort(vict.begin(), vict.begin() + (ptrdiff_t) nc, vict.end(), - [](auto& a, auto& b) { return a.first < b.first; }); - for (size_t i = 0; i < nc; ++i) { - if (cand[i].first < vict[i].first + 1.5f) break; - swaps.push_back({cand[i].first - vict[i].first, (int32_t) l, cand[i].second, vict[i].second}); - } - } - std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; }); - if ((int) swaps.size() > o.adapt_swaps) swaps.resize((size_t) o.adapt_swaps); - if (!resident_stage_swaps(src, xcache, host_res, g.n_expert, swaps, adapt_stream)) { - std::fprintf(stderr, "strata generate: an adaptive refill failed (copying evicted experts back)\n"); - return false; - } - if (pin_blobs_on()) { // lock the batch's source pages (a file-backed arena on AMD; see pin_blobs) - std::vector> spans; - for (const Swap& s : swaps) - if (const uint8_t* b = srcp->blob(s.layer, s.in)) - spans.emplace_back((uintptr_t) b, - (uintptr_t) b + strata::kernels::cpu::expert_layout().blob_bytes(s.layer)); - pin_blobs(std::move(spans), pin_live); - } - for (const Swap& s : swaps) { - const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out; - const int32_t slot = host_res[out]; - const uint8_t* b = srcp->blob(s.layer, s.in); - // asynchronous: the copies run while the MTP drafts; the next window waits for them - if (slot < 0 || b == nullptr || - cudaMemcpyAsync(xcache.device_slot(slot), b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer), - cudaMemcpyHostToDevice, adapt_stream) != cudaSuccess) { - std::fprintf(stderr, "strata generate: an adaptive refill failed\n"); - return false; - } - host_res[out] = strata::core::kNotResident; // evicted now: the CPU computes it meanwhile - srcp->prefetch(s.layer, s.out); // a file-backed arena released its pages: read them back ahead - pending.emplace_back((int32_t) in, slot); // resident once the copy has landed - } - if (!swaps.empty()) cudaEventRecord(adapt_ev, adapt_stream); - if (trace_adapt) - std::fprintf(stderr, "strata: ADAPT round=%lld swapped %zu of %d slots, usage decayed\n", - (long long) adapt_rounds, swaps.size(), o.adapt_swaps); - for (float& v : drive.d.usage) v *= o.adapt_decay; - swaps_total += (int64_t) swaps.size(); - ms_adapt += std::chrono::duration(Clock::now() - ta).count(); - return true; - }; - int64_t p = spec_pos; - int32_t x = (int32_t) tok; - std::vector drafts((size_t) o.spec, 0); - std::vector dprob((size_t) o.spec, 1.0f); - std::vector window_hist((size_t) o.spec + 1, 0); - // plan v0.3 P6: with a native pack the first window is the last prompt token alone (it produces the first - // generated token and the MTP's first cell); otherwise the token loop already did that. - bool first_window = native_pack; - if (use_mtp && !first_window && - !mtp.draft_first(o.spec, ss.R, x, p - 1, drafts.data(), err, dprob.data(), (float) o.spec_min_p)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - std::vector window((size_t) o.spec), outv((size_t) o.spec); - std::vector 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); - strata::spec::DraftPolicy policy(o.spec); // MTP or lookup window (see draft_policy.hpp) - std::vector sbuf((size_t) o.spec, 0); - int64_t sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0; - if (o.suffix_draft > 0) { - for (int64_t t : o.tokens) sfx.append((int32_t) t); - for (int64_t t : produced) sfx.append((int32_t) t); - } - const double pool_ms0 = drive.cpu_ms; - const int64_t misses0 = drive.d.multi_misses, entries0 = drive.d.multi_entries; - while ((int64_t) produced.size() < o.max_new) { - const Clock::time_point t0 = Clock::now(); - int T = S_mtp; - if (use_mtp && o.spec_min_p > 0.0) { - T = 1; - 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(T, o.max_new - (int64_t) produced.size()); - bool from_sfx = false; - int sfx_match = 0; - 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])) { - const strata::spec::DraftPolicy::Pick pk = policy.choose(T, k, sfx_match); - if (pk.lookup) { T = pk.t; from_sfx = true; } - } - } - const bool timed_round = !first_window; - ++window_hist[(size_t) T]; - if (p + T > o.max_context) { - std::fprintf(stderr, "strata generate: ran out of context at position %lld\n", (long long) p); - return 2; - } - window[0] = x; - for (int i = 1; i < T; ++i) { - const size_t at = produced.size() - 1 + (size_t) i; - int32_t d = from_sfx ? sbuf[(size_t) i - 1] : use_mtp ? drafts[(size_t) i - 1] - : at < oracle.size() ? (int32_t) oracle[at] : 0; - if (o.spec_corrupt > 0 && (++corrupt_counter % o.spec_corrupt) == 0) d = (d + 1) % (int32_t) n_vocab; - window[(size_t) i] = d; - } - drive.d.layers = 0; - drive.d.experts = 0; - drive.d.failed = false; - // #463: the previous adapt round's copies land first - with a non-blocking query, whether a swapped-in - // expert ran on the GPU or the CPU (they round differently) depended on the copy's timing - // (STRATA_ADAPT_NOWAIT=1: 0.1.37's non-blocking query, the A/B) - apply_pending(!adapt_nowait()); - if (!ver.run(T, window.data(), p, &drive_pool_multi, &drive, outv.data(), err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - if (drive.d.failed) { - std::fprintf(stderr, "strata generate: the expert pool failed at layer %lld expert %lld: %s\n", - (long long) drive.d.fail_layer, (long long) drive.d.fail_expert, - drive.d.fail ? drive.d.fail : "(no message)"); - return 1; - } - 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(Clock::now() - t_start).count(); - // Diagnostics: the first window runs the prompt's last token over the state the prompt path left - // (keys, values, recurrent state), so its logits carry whatever that path did. A native pack never - // runs the per-token loop --dump-logits reads; this is where prompt paths can be compared by output. - if (const char* fl = std::getenv("STRATA_DUMP_FIRST_LOGITS")) { - std::vector row((size_t) ver.vocab()); - std::FILE* f = ver.copy_logits(0, row.data()) ? std::fopen(fl, "wb") : nullptr; - if (f == nullptr || std::fwrite(row.data(), sizeof(float), row.size(), f) != row.size()) - std::fprintf(stderr, "strata generate: STRATA_DUMP_FIRST_LOGITS: cannot write %s\n", fl); - if (f) std::fclose(f); - } - } - // plan v0.3 P6: the adaptive tier's host work (ranking, copy submission) runs on its own thread while the - // GPU commits and drafts; it touches only the residency tables, which nothing reads until the next window - std::thread adapt_thr; - bool adapt_ok = true; - if (!drive.d.usage.empty() && ((rounds + 1) % o.adapt_every) == 0) - adapt_thr = std::thread([&] { adapt_ok = adapt(); }); - if (!ver.commit(a + 1, err)) { - if (adapt_thr.joinable()) adapt_thr.join(); - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - ++rounds; - drafts_total += T - 1; - drafts_ok += a; - ++accepted_hist[(size_t) a]; - if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; } - bool eos = false; - 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.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(); - total_ms += std::chrono::duration(Clock::now() - t0).count(); - break; - } - const bool drafted = !use_mtp || (int64_t) produced.size() >= o.max_new || - mtp.draft(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) o.spec_min_p); - if (adapt_thr.joinable()) adapt_thr.join(); - if (!adapt_ok) return 1; - if (!drafted) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - // 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(Clock::now() - t0).count(); - total_ms += round_ms; - if (timed_round) policy.observe(from_sfx, T, a, sfx_match, round_ms); - if (rounds % 64 == 0) - std::fprintf(stderr, "strata generate: position %lld, %lld tokens, %lld rounds\n", (long long) p, - (long long) produced.size(), (long long) rounds); - } - // the last commit (set_commit_async) before anything reads the session again - if (!ver.wait_commit(err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - std::printf("%-24s %lld rounds of %d, drafts accepted %lld of %lld (%.3f), %.2f tokens per round\n", - "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]); - std::printf(" (min draft probability %.2f)\n", o.spec_min_p); - } - if (o.suffix_draft > 0) - std::printf("%-24s %lld windows, drafts accepted %lld of %lld\n", "suffix drafts", (long long) sfx_windows, - (long long) sfx_ok, (long long) sfx_drafts); - std::printf("%-24s", "accepted per round"); - for (size_t i = 0; i < accepted_hist.size(); ++i) std::printf(" %zu:%lld", i, (long long) accepted_hist[i]); - std::printf("\n"); - if (rounds > 0) - std::printf("%-24s wait for rings %.3f pool %.3f host %.3f commit %.3f ms/round; CPU experts %.2f " - "distinct / %.2f routed per layer\n", - "verify window", ver.ms_wait / rounds, ver.ms_pool / rounds, ver.ms_host / rounds, - ver.ms_commit / rounds, - (double) (drive.d.multi_misses - misses0) / (double) (rounds * g.n_layers), - (double) (drive.d.multi_entries - entries0) / (double) (rounds * g.n_layers)); - if (rounds > 0) - std::printf("%-24s gate/up %.3f quantize %.3f down %.3f ms/round; %.1f GB/s over the rows phases; " - "CPU pool call %.3f ms/round\n", "pool multi", pool.ms_multi_gu / rounds, - pool.ms_multi_q / rounds, pool.ms_multi_down / rounds, - (double) pool.multi_bytes / 1e6 / std::max(1e-9, pool.ms_multi_gu + pool.ms_multi_down), - (drive.cpu_ms - pool_ms0) / rounds); - if (rounds > 0) - std::printf("%-24s plan %.3f activation quantize %.3f jobs %.3f run %.3f ms/round\n", "dispatch", - drive.d.ms_plan / rounds, drive.d.ms_actq / rounds, drive.d.ms_jobs / rounds, - drive.d.ms_run / rounds); - if (rounds > 0 && !drive.d.usage.empty()) - std::printf("%-24s %lld experts swapped into the VRAM tier (every %d rounds, %.3f ms/round)\n", "adaptive tier", - (long long) swaps_total, o.adapt_every, ms_adapt / rounds); - if (src.complement_ready()) - std::printf("%-24s %.2f GiB of experts in RAM, %lld exchanged with the VRAM tier, %lld blob reads from " - "the file\n", "resident RAM", (double) src.resident_bytes() / 1073741824.0, - (long long) src.exchanges(), (long long) src.file_reads()); - if (srcp == &src) { // CS-T: the RAM and file tiers (the GPU cache's share is the hit rate above) - const double fms = src.file_ms() - fms0, fmb = (double) (src.file_blob_bytes() - fbytes0) / 1e6; - std::printf("%-24s decode: RAM %lld blobs, files %lld blobs, %.1f MB read from the files (%.2f MB/round, " - "%.1f ms/round of reading, %.2f GB/s per reading thread)%s; prompt copies %.1f MB\n", - "expert tiers", (long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0), - fmb, rounds > 0 ? fmb / rounds : 0.0, rounds > 0 ? fms / rounds : 0.0, - fms > 0 ? fmb / fms : 0.0, src.gguf_mode() ? " (the GGUF in place)" : "", - (double) (fall0 - fbytes0) / 1e6); - if (drive.d.lookahead != nullptr) - std::printf("%-24s %lld experts warmed, %lld of the file tier's %lld blob reads had been warmed (%.1f%%); " - "predictor %.1f ms/round on its thread, %lld layers skipped (still busy)\n", "routing prefetch", - (long long) src.warmed(), (long long) src.warmed_hits(), - (long long) (src.file_reads() - files0), - src.file_reads() > files0 ? 100.0 * (double) src.warmed_hits() / (double) (src.file_reads() - files0) : 0.0, - rounds > 0 ? drive.d.lookahead->busy_ms() / rounds : 0.0, (long long) drive.d.lookahead->skipped()); - } - if (rounds > 0 && drive.d.pcie_num > 0) - std::printf("%-24s %.2f distinct experts per layer read over PCIe (share %d/256 of the misses)\n", - "pcie experts", (double) (drive.d.pcie_experts - pcie0) / (double) (rounds * g.n_layers), - drive.d.pcie_num); - (void) pool_ms0; - if (use_mtp && rounds > 0) - std::printf("%-24s %.3f ms/round drafting (%lld rounds), MTP prompt %.1f ms, %.0f MiB of VRAM\n", "mtp", - mtp.ms_draft / (double) mtp.rounds, (long long) mtp.rounds, mtp.ms_prefill, - (double) mtp.vram_bytes() / 1048576.0); - } - - if (dump != nullptr && std::fclose(dump) != 0) { - std::fprintf(stderr, "strata generate: cannot finish logits dump\n"); - return 1; - } - if (layer_dump != nullptr) { - std::fclose(layer_dump); - cudaFreeHost(layer_stage); - std::printf("%-24s %s (%lld layers + the input x %d streams x %lld per position)\n", "layers dumped", - o.dump_layers.c_str(), (long long) g.n_layers, (int) g.hc, (long long) g.n_embd); - } - if (half_dump != nullptr) { - std::fclose(half_dump); - cudaFreeHost(half_stage); - std::printf("%-24s %s (%lld layers x %llu per position)\n", "halves dumped", o.dump_halves.c_str(), - (long long) g.n_layers, (unsigned long long) half_stride); - } - if (routing != nullptr) { - std::fclose(routing); - drive.routing = nullptr; - std::printf("%-24s %s (%lld records of layer, k, ids, weights)\n", "routing dumped", - o.dump_routing.c_str(), (long long) drive.calls); - } - if (o.stage_timing) strata::core::stage_timing_report(g.n_layers); - - const int64_t decoded = (int64_t) produced.size(); - std::printf("prompt :"); - for (int64_t t : o.tokens) std::printf(" %lld", (long long) t); - std::printf("\noutput :"); - for (int64_t t : produced) std::printf(" %lld", (long long) t); - std::printf("\n"); - const double decode_ms = decoded > 0 ? total_ms / (double) decoded : 0.0; - std::printf("%-24s %lld tokens in %.1f ms -> %.2f tok/s\n", "decode", (long long) decoded, total_ms, - decode_ms > 0.0 ? 1000.0 / decode_ms : 0.0); - if (n_prompt > 1) - std::printf("%-24s %lld tokens in %.1f ms -> %.2f tok/s (time to first token %.1f ms)\n", "prefill", - (long long) (n_prompt - 1), prefill_ms, - prefill_ms > 0 ? 1000.0 * (double) (n_prompt - 1) / prefill_ms : 0.0, ttft_ms); - if (!o.dump_mixed.empty()) { - std::vector mx((size_t) g.n_embd); - if (cudaMemcpy(mx.data(), ss.block.mixed, mx.size() * sizeof(float), cudaMemcpyDeviceToHost) != - cudaSuccess) { - std::fprintf(stderr, "strata generate: reading mixed back failed\n"); - return 1; - } - std::FILE* mf = std::fopen(o.dump_mixed.c_str(), "wb"); - if (mf == nullptr) { - std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_mixed.c_str()); - return 1; - } - std::fwrite(mx.data(), sizeof(float), mx.size(), mf); - std::fclose(mf); - double s2 = 0, mag = 0; - for (float v : mx) { s2 += (double) v * (double) v; mag += std::fabs((double) v); } - std::printf("%-24s %s (n_embd %lld, rms %.5g, mean|.| %.5g)\n", "mixed dumped", o.dump_mixed.c_str(), - (long long) g.n_embd, std::sqrt(s2 / (double) mx.size()), mag / (double) mx.size()); - } - - // ---- the residual, for bisecting the head against the layers (see `dump_residual`'s note) - if (!o.dump_residual.empty()) { - std::vector R((size_t) g.hc * g.n_embd); - if (cudaMemcpy(R.data(), ss.R, R.size() * sizeof(float), cudaMemcpyDeviceToHost) != cudaSuccess) { - std::fprintf(stderr, "strata generate: reading R back failed\n"); - return 1; - } - std::FILE* rf = std::fopen(o.dump_residual.c_str(), "wb"); - if (rf == nullptr) { - std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_residual.c_str()); - return 1; - } - const int32_t hdr[2] = {(int32_t) g.hc, (int32_t) g.n_embd}; - std::fwrite(hdr, sizeof hdr, 1, rf); - std::fwrite(R.data(), sizeof(float), R.size(), rf); - std::fclose(rf); - double mag = 0, mx = 0; - int bad = 0; - for (float v : R) { - if (!std::isfinite(v)) ++bad; - else { mag += std::fabs((double) v); mx = std::max(mx, (double) std::fabs((double) v)); } - } - std::printf("%-24s %s (%d x %lld, nonfinite %d, mean|.| %.4g, max|.| %.4g)\n", "residual dumped", - o.dump_residual.c_str(), (int) g.hc, (long long) g.n_embd, bad, mag / (double) R.size(), mx); - } - - if (o.stats) { - std::printf("%-24s %.3f ms/token (WALL CLOCK: embed, layers, head, sample)\n", " per token", decode_ms); - // **THE PER-TOKEN HOST TERM, WHICH `--gpu-only-full` CANNOT SEE.** That measurement never enters the - // token loop, so it excludes all six of these. On the 78-token fixture + 200 generated tokens the six - // sum to ~9 ms of non-layer work against ~1.5 ms of actual head GPU work - 16% of the token, and it is - // not the pool. - if (phase_tokens > 0) { - const double pt = (double) phase_tokens; - std::printf("%-24s PLE %.3f embed %.3f LAYERS %.3f head %.3f readback %.3f sample %.3f " - "(sum %.3f of %.3f ms)\n", - " token host phases", ms_ple / pt, ms_embed / pt, ms_layers / pt, ms_head / pt, - ms_readback / pt, ms_sample / pt, - (ms_ple + ms_embed + ms_layers + ms_head + ms_readback + ms_sample) / pt, decode_ms); - } - if (const std::string io = ple_table.io_report(); !io.empty()) std::printf(" %s\n", io.c_str()); - // **THE DENOMINATOR IS THE POSITIONS THE POOL ACTUALLY RAN ON, NOT THE DECODED TOKENS (A6).** - // `drive_pool` is called once per layer per position and PREFILL runs the loop too, so accumulating - // `cpu_ms` over prefill and then dividing by `decoded` inflates this figure. `drive.calls / n_layers` - // is the number of positions - the same correction the ring counters below already received, which is - // why they print "of 192" rather than "240 of 192". - const double pool_positions = g.n_layers > 0 ? (double) drive.calls / (double) g.n_layers : 0.0; - std::printf("%-24s %.3f ms/token over %lld layers (%.0f positions, %lld dispatches)\n", - " the CPU expert pool", pool_positions > 0.0 ? drive.cpu_ms / pool_positions : 0.0, - (long long) g.n_layers, pool_positions, (long long) drive.calls); - // **AND WHERE INSIDE `run()` IT WENT.** Three phases per layer and they were one number, which cannot - // tell a pool that is slow at the WORK from one that is slow at the SYNCHRONISATION - opposite fixes. - // Wait-for-park is expected to be ~0 (the workers re-parked at the end of the previous layer); the - // question is whether the time is in the drain or in the re-park barrier. - if (pool_positions > 0.0) { - double wp = 0, dr = 0, rp = 0; - pool.phase_ms(wp, dr, rp); - const double per = pool_positions; - std::printf("%-24s wait-park %.3f drain %.3f re-park %.3f ms/token\n", - " pool phases", wp / per, dr / per, rp / per); - } - std::printf("%-24s %lld blobs read\n", " expert blobs", (long long) srcp->reads()); - for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) - std::printf(" CUDA%d experts %lld routed entries computed\n", - r + 1, (long long) remote_experts[(size_t) r].computed()); - // ---- **R4's DISPATCH MEASUREMENT: h, ON THE ENGINE'S OWN ROUTING.** No offline trace, no corpus - // question, no k-fold - these are the ids the router actually produced on this run. Reported as - // hits/lookups so it can be read directly as the h the cache would deliver, and alongside `refused` - // so a full cache is visible rather than silently capping the rate. - if (o.expert_cache > 0) { - const int64_t look = drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused; - const int64_t hl = drive.d.hit_ready + drive.d.hit_late; - std::printf("%-24s %lld of %lld layers the hit work was DONE when the pool returned\n", - " R4 overlap", (long long) drive.d.hit_ready, (long long) hl); - std::printf("%-24s %lld of %lld = %.4f (%lld admitted, %lld refused, cache %.4f%% full)\n", - " R4 expert-cache hits", (long long) drive.d.cache_hits, (long long) look, - look > 0 ? (double) drive.d.cache_hits / (double) look : 0.0, - (long long) drive.d.cache_admitted, (long long) drive.d.cache_refused, - 100.0 * (double) (drive.d.cache_admitted + drive.d.cache_hits > 0 - ? (double) xcache.resident() / (double) xcache.slots() - : 0.0)); - } - if (tgraph.captured && tgraph.calls > 0) { - const double per = (double) tgraph.calls; - std::printf("%-24s wait for rings %.3f pool %.3f ms/token (%lld flushes over %lld positions)\n", - " token graph", tgraph.ms_wait / per, tgraph.ms_pool / per, (long long) tgraph.flushes, - (long long) tgraph.calls); - } - if (gr.captured && gr.calls_total > 0) { - // The counters are CUMULATIVE over every `session_loop` call, and PREFILL runs the loop too - so - // the denominator is the number of positions, not the number of generated tokens. Dividing by - // `n_layers * decoded` printed "240 of 192", which is a reporting bug that looks like a ring - // firing more often than it should. - const int64_t positions = gr.calls_total; - std::printf("%-24s %lld of %lld over %lld positions\n", " rings seen MID-GRAPH", - (long long) gr.rings_mid_graph, (long long) (g.n_layers * positions), - (long long) positions); - std::printf("%-24s %.3f ms of a %.3f ms layer\n", " ring latency", - gr.ms_to_ring / (double) (g.n_layers * positions), decode_ms / (double) g.n_layers); - // **THE ROUND TRIP, SPLIT AT THE RING.** `ring latency` is the first half and stops when the ring - // is seen; this is the second half - the driver calls after it, during which the GPU is IDLE - // because `post[l]` has not been launched yet. `--no-pool` is the arm that isolates it: 38.73 - // ms/token against a 26.32 ms pure-GPU floor is 12.4 ms of round trip with no expert work at all. - // - // Same denominator as the pool line above (the positions the loop actually ran on), so the two can - // be added without one of them being inflated by prefill. - const double perlap = (double) (g.n_layers * positions); - std::printf("%-24s %.3f ms/token over %.0f positions (%.3f ms/layer, after the ring)\n", - " host after ring", pool_positions > 0.0 ? gr.ms_host / pool_positions : 0.0, - pool_positions, gr.ms_host / perlap); - } - } - - if (dump != nullptr) std::printf("%-24s %s\n", "logits dumped", o.dump_logits.c_str()); - - strata::core::session_graphs_free(gr); - strata::core::doorbell_free(db); - cudaFree(d_next); - cudaFree(d_logits); - cudaFree(d_emb); - cudaFree(d_parts); - cudaFree(sbuf); - cudaFree(arena); - return 0; -} diff --git a/src/spec/controller.cpp b/src/spec/controller.cpp deleted file mode 100644 index be31270..0000000 --- a/src/spec/controller.cpp +++ /dev/null @@ -1,73 +0,0 @@ -// src/spec/controller.cpp - see include/strata/spec/controller.hpp. -#include "strata/spec/controller.hpp" - -#include - -namespace strata::spec { - -double CostModel::step_ms(int k, bool mtp) const { - const int n = std::clamp(k + 1, 1, K_MAX + 1); - const double dense = dense_ms * dense_ratio[n - 1]; - // CPU misses: distinct experts grow as U(n); each extra token routed to a missed expert adds a fraction of a - // read. Tokens per distinct expert = n / U(n)-ratio (U measured in units of one token's 10 experts). - const double u = distinct_ratio[n - 1]; - const double uses_per_expert = (double) n / u; - const double cpu = (1.0 - hit_rate) * cpu_all_miss_ms * u * (1.0 + extra_use_cost * (uses_per_expert - 1.0)); - const double draft = k * (mtp ? mtp_draft_ms : lookup_draft_ms); - return dense + cpu + sync_ms + draft; -} - -Controller::Controller(CostModel cost, double min_gain, double ema) : cost_(cost), min_gain_(min_gain), ema_(ema) { - // Priors: MTP per-position acceptance from flyweight's measurement on this model (0.86 per draft); lookup by - // match length from the offline replay (2026-09-23-suffix-lookup). Both are then learned per session. - mtp_p_.fill(0.86); - lookup_q_ = {0.35, 0.6, 0.8, 0.92}; -} - -double Controller::expected(const double* p, int k, bool same) { - double e = 1.0, run = 1.0; // the verify pass always commits one token - for (int i = 0; i < k; ++i) { - run *= same ? p[0] : p[i]; - e += run; - } - return e; -} - -Choice Controller::choose(int lookup_available, int lookup_match, bool mtp_ready) const { - Choice best; - best.tokens_per_ms = 1.0 / cost_.step_ms(0, false); - const double baseline = best.tokens_per_ms; - auto consider = [&](Source s, int k, double e) { - const double rate = e / cost_.step_ms(k, s == Source::Mtp); - if (rate > best.tokens_per_ms) best = Choice{s, k, e, rate}; - }; - const int lk = std::min(lookup_available, K_MAX); - const double q = lookup_q_[bucket(lookup_match)]; - for (int k = 1; k <= lk; ++k) consider(Source::Lookup, k, expected(&q, k, true)); - if (mtp_ready) - for (int k = 1; k <= K_MAX; ++k) consider(Source::Mtp, k, expected(mtp_p_.data(), k, false)); - if (best.source != Source::None && best.tokens_per_ms < baseline * (1.0 + min_gain_)) { - Choice none; - none.tokens_per_ms = baseline; - return none; - } - return best; -} - -void Controller::observe(const Choice& c, int accepted, int lookup_match) { - if (c.source == Source::None || c.k <= 0) return; - accepted = std::clamp(accepted, 0, c.k); - // Positions 0..accepted-1 were accepted given their prefix; position `accepted` (if drafted) was rejected. - const int seen = std::min(c.k, accepted + 1); - for (int i = 0; i < seen; ++i) { - const double hit = i < accepted ? 1.0 : 0.0; - if (c.source == Source::Mtp) mtp_p_[i] += ema_ * (hit - mtp_p_[i]); - else lookup_q_[bucket(lookup_match)] += ema_ * (hit - lookup_q_[bucket(lookup_match)]); - } - // Everything drafted was accepted: the positions beyond the window were never tested, so without this they - // keep their prior forever and the window can never grow. Pull them toward the deepest observed rate. - if (c.source == Source::Mtp && accepted == c.k && c.k < K_MAX) - for (int i = c.k; i < K_MAX; ++i) mtp_p_[i] += ema_ * (mtp_p_[c.k - 1] - mtp_p_[i]); -} - -} // namespace strata::spec diff --git a/src/spec/controller_test.cpp b/src/spec/controller_test.cpp deleted file mode 100644 index ee056ab..0000000 --- a/src/spec/controller_test.cpp +++ /dev/null @@ -1,74 +0,0 @@ -// src/spec/controller_test.cpp - plan v0.3 P6: the speculation controller's decisions (no model, no GPU). -#include "strata/spec/controller.hpp" - -#include - -using namespace strata::spec; - -namespace { -int g_fail = 0; -void check(bool ok, const char* what) { - if (!ok) { std::fprintf(stderr, "FAIL: %s\n", what); ++g_fail; } -} -const char* name(Source s) { return s == Source::Mtp ? "mtp" : s == Source::Lookup ? "lookup" : "none"; } -} // namespace - -int main() { - { // priors (MTP 0.86 per draft): MTP with a short-to-medium window beats plain decoding - Controller c; - const Choice ch = c.choose(0, 0, true); - check(ch.source == Source::Mtp && ch.k >= 2 && ch.k <= 5, "MTP chosen with k in 2..5 at the prior"); - std::printf("prior: %s k=%d expected %.2f tokens, %.1f tok/s (plain %.1f)\n", name(ch.source), ch.k, - ch.expected_tokens, 1000 * ch.tokens_per_ms, 1000.0 / c.cost().step_ms(0, false)); - } - { // a drafter that keeps missing its first token is switched off - Controller c; - Choice ch = c.choose(0, 0, true); - for (int i = 0; i < 400; ++i) { c.observe(ch, 0, 0); ch = c.choose(0, 0, true); if (ch.source == Source::None) break; } - check(ch.source == Source::None, "persistent rejection turns speculation off"); - std::printf("after rejections: %s, p0 %.2f\n", name(ch.source), c.mtp_accept(0)); - } - { // a long lookup match beats MTP; how LONG a window pays depends on what a wide verify costs - Controller c; - const Choice ch = c.choose(8, 20, true); - check(ch.source == Source::Lookup, "long lookup match preferred over MTP"); - std::printf("long lookup match, measured costs: %s k=%d expected %.2f, %.1f tok/s\n", name(ch.source), ch.k, - ch.expected_tokens, 1000 * ch.tokens_per_ms); - CostModel cheap; // a verify pass whose cost barely grows with width - cheap.dense_ratio = {1.0, 1.02, 1.04, 1.06, 1.08, 1.1, 1.12, 1.14, 1.16}; - cheap.hit_rate = 0.95; - Controller c2(cheap); - const Choice ch2 = c2.choose(8, 20, true); - check(ch2.source == Source::Lookup && ch2.k == 8, "cheap wide verify takes the whole lookup window"); - std::printf("long lookup match, cheap wide verify: %s k=%d expected %.2f, %.1f tok/s\n", name(ch2.source), - ch2.k, ch2.expected_tokens, 1000 * ch2.tokens_per_ms); - } - { // a bare trigram match, no MTP: not worth a verify window - Controller c; - const Choice ch = c.choose(8, 3, false); - check(ch.source == Source::None, "short lookup match alone is not used"); - } - { // perfect acceptance is learned and widens the window - Controller c; - Choice ch = c.choose(0, 0, true); - const int k0 = ch.k; - for (int i = 0; i < 400; ++i) { c.observe(ch, ch.k, 0); ch = c.choose(0, 0, true); } - check(ch.k > k0 && c.mtp_accept(0) > 0.99, "full acceptance learned and the window widens"); - std::printf("after full acceptance: %s k=%d (was %d), p0 %.3f\n", name(ch.source), ch.k, k0, c.mtp_accept(0)); - } - std::printf("\nMTP acceptance -> choice (default cost model):\n"); - for (double p : {0.5, 0.6, 0.7, 0.8, 0.86, 0.9, 0.95}) { - Controller c; - Choice ch = c.choose(0, 0, true); - for (int i = 0; i < 2000; ++i) { // feed a stream with iid acceptance p per position - int acc = 0; - unsigned r = 2654435761u * (unsigned) (i + 1); - while (acc < ch.k && ((r = r * 1103515245u + 12345u) >> 8) % 1000 < p * 1000) ++acc; - c.observe(ch, acc, 0); - ch = c.choose(0, 0, true); - } - std::printf(" p=%.2f: %s k=%d, %.1f tok/s\n", p, name(ch.source), ch.k, 1000 * ch.tokens_per_ms); - } - std::printf("controller tests: %s\n", g_fail ? "FAILED" : "OK"); - return g_fail ? 1 : 0; -} diff --git a/src/spec/draft_policy.cpp b/src/spec/draft_policy.cpp deleted file mode 100644 index 1ac7719..0000000 --- a/src/spec/draft_policy.cpp +++ /dev/null @@ -1,101 +0,0 @@ -// src/spec/draft_policy.cpp - see include/strata/spec/draft_policy.hpp. -#include "strata/spec/draft_policy.hpp" - -#include - -namespace strata::spec { -namespace { - -// The shape of a round's cost by window size, relative to one token, used only for sizes not measured yet (the -// measured round times replace it). Between the RTX 5070's measured curves: +10 ms per token with every missed expert -// on the CPU (bench/results/2026-09-27-spec/window-cost), flatter with the default CPU/DMA split. -constexpr double kShape[DraftPolicy::kMaxT + 1] = {0.0, 1.0, 1.35, 1.7, 2.05, 2.45, 2.85, 3.25, 3.6}; -constexpr double kCostAlpha = 0.1; // EMA weight of a new round time -constexpr double kTokAlpha = 0.05; // EMA weight of a new MTP window outcome -constexpr double kDecay = 0.97; // lookup counts: older windows fade -// Before a bucket has data: the longer the match, the likelier its continuation (llama.cpp's lookup decoding gates -// on the same thing); worth 4 observations, so a few real windows override it -constexpr double kPriorQ[DraftPolicy::kBuckets] = {0.75, 0.88, 0.93, 0.96}; -constexpr double kPriorN = 4.0; -constexpr int kProbes = 3; // a lookup window size is tried this often before its guessed cost can veto it - -} // namespace - -DraftPolicy::DraftPolicy(int max_t, double margin) - : max_t_(std::clamp(max_t, 1, kMaxT)), margin_(margin) {} - -int DraftPolicy::bucket(int match) { - return match < 6 ? 0 : match < 12 ? 1 : match < 24 ? 2 : 3; -} - -double DraftPolicy::lookup_rate(int match) const { - const int b = bucket(match); - return (ok_[b] + kPriorN * kPriorQ[b]) / (ok_[b] + bad_[b] + kPriorN); -} - -double DraftPolicy::cost_ms(int t) const { - t = std::clamp(t, 1, kMaxT); - if (cost_n_[t] > 0) return cost_[t]; - // scale from the measured sizes, weighting each by how often it was seen - double num = 0.0, den = 0.0; - for (int u = 1; u <= kMaxT; ++u) - if (cost_n_[u] > 0) { - const double w = std::min(cost_n_[u], 20.0); - num += w * cost_[u] * kShape[t] / kShape[u]; - den += w; - } - return den > 0 ? num / den : kShape[t]; -} - -double DraftPolicy::mtp_tokens(int t) const { - if (mtp_n_[t] > 0) return mtp_tok_[t]; - return 1.0 + 0.7 * (t - 1); // before any MTP window of this size: a typical acceptance -} - -DraftPolicy::Pick DraftPolicy::choose(int t_mtp, int lookup_k, int match) const { - Pick p; - p.t = std::clamp(t_mtp, 1, max_t_); - if (lookup_k <= 0) return p; - const double base = mtp_tokens(p.t) / cost_ms(p.t); - const double q = lookup_rate(match); - double e = 1.0, qi = 1.0, best = 0.0; - int best_t = 0; - for (int k = 1; k <= std::min(lookup_k, max_t_ - 1); ++k) { - qi *= q; - e += qi; - const double r = e / cost_ms(k + 1); - if (r > best) { best = r; best_t = k + 1; } - } - if (best_t > 0 && best > base * (1.0 + margin_)) { - p.lookup = true; - p.t = best_t; - return p; - } - // a guessed cost can keep the policy from ever measuring a size: the first few times a confident lookup would - // need a size not measured yet, it is tried (verification keeps the output; only the one round's speed is at stake) - const int t_full = std::min(lookup_k, max_t_ - 1) + 1; - if (t_full > p.t && cost_n_[t_full] < kProbes && q >= 0.85) { - p.lookup = true; - p.t = t_full; - } - return p; -} - -void DraftPolicy::observe(bool lookup, int t, int accepted, int match, double round_ms) { - t = std::clamp(t, 1, kMaxT); - if (round_ms > 0) { - cost_[t] = cost_n_[t] > 0 ? (1.0 - kCostAlpha) * cost_[t] + kCostAlpha * round_ms : round_ms; - cost_n_[t] += 1.0; - } - if (lookup) { - const int b = bucket(match); - ok_[b] = kDecay * ok_[b] + accepted; - bad_[b] = kDecay * bad_[b] + (accepted < t - 1 ? 1.0 : 0.0); - } else { - const double got = accepted + 1.0; - mtp_tok_[t] = mtp_n_[t] > 0 ? (1.0 - kTokAlpha) * mtp_tok_[t] + kTokAlpha * got : got; - mtp_n_[t] += 1.0; - } -} - -} // namespace strata::spec diff --git a/src/spec/draft_policy_test.cpp b/src/spec/draft_policy_test.cpp deleted file mode 100644 index e04b3de..0000000 --- a/src/spec/draft_policy_test.cpp +++ /dev/null @@ -1,63 +0,0 @@ -// src/spec/draft_policy_test.cpp - DraftPolicy: when does a lookup window beat the MTP's? -// -// Simulated rounds with the costs measured on the RTX 5070 (window-cost: ~10 ms more per token) check that -// 1. with no lookup proposal the MTP window is kept; -// 2. lookup drafts that are mostly rejected stop being taken (their bucket's rate falls); -// 3. lookup drafts that are always accepted are taken, and the window grows with them; -// 4. match-length buckets learn separately (short matches failing does not stop long ones); -// 5. the policy never proposes a window beyond its cap. -#include "strata/spec/draft_policy.hpp" - -#include - -using strata::spec::DraftPolicy; - -namespace { -int g_fail = 0; -void check(bool ok, const char* what) { - std::printf(" %-66s %s\n", what, ok ? "ok" : "FAIL"); - if (!ok) ++g_fail; -} -double cost(int t) { return 19.0 + 10.5 * (t - 1); } // ms per round, measured shape -} // namespace - -int main() { - std::printf("draft_policy_test\n"); - { - DraftPolicy p(6); - for (int i = 0; i < 50; ++i) p.observe(false, 4, 2, 0, cost(4)); // MTP windows of 4: 3 tokens each - const DraftPolicy::Pick k = p.choose(4, 0, 0); - check(!k.lookup && k.t == 4, "no proposal: the MTP window"); - } - { - DraftPolicy p(6); - for (int i = 0; i < 50; ++i) p.observe(false, 4, 2, 0, cost(4)); - for (int t = 2; t <= 6; ++t) p.observe(false, t, 0, 0, cost(t)); - for (int i = 0; i < 40; ++i) p.observe(true, 6, 0, 4, cost(6)); // short matches, all rejected - check(p.lookup_rate(4) < 0.15, "rejected short-match drafts: their rate falls below 0.15"); - check(!p.choose(4, 5, 4).lookup, "rejected short-match drafts: no longer taken"); - for (int i = 0; i < 40; ++i) p.observe(true, 6, 5, 30, cost(6)); // long matches, all accepted - check(p.lookup_rate(30) > 0.9, "accepted long-match drafts: their rate rises above 0.9"); - const DraftPolicy::Pick k = p.choose(4, 5, 30); - check(k.lookup && k.t == 6, "accepted long matches: the full lookup window is taken"); - check(!p.choose(4, 5, 4).lookup, "buckets are separate: short matches still not taken"); - check(p.choose(4, 20, 30).t <= 6, "never beyond the window cap"); - } - { - DraftPolicy p(8); - for (int i = 0; i < 50; ++i) p.observe(false, 3, 2, 0, cost(3)); // a very good MTP: 3 of 3 tokens - for (int t = 2; t <= 8; ++t) p.observe(false, t, t - 1, 0, cost(t)); - for (int i = 0; i < 40; ++i) p.observe(true, 4, 2, 8, cost(4)); // lookup at q ~ 0.67 - check(!p.choose(3, 7, 8).lookup, "a mediocre lookup does not replace a strong MTP window"); - } - { - DraftPolicy p(6); - for (int i = 0; i < 50; ++i) p.observe(false, 4, 3, 0, cost(4)); // a near-perfect MTP, only size 4 seen - const DraftPolicy::Pick k = p.choose(4, 5, 40); - check(k.lookup && k.t == 6, "an unmeasured size is probed for a confident lookup"); - for (int i = 0; i < 3; ++i) p.observe(true, 6, 5, 40, 3.0 * cost(6)); // it turns out very expensive - check(!p.choose(4, 5, 40).lookup, "after the probes, the measured cost decides"); - } - std::printf(g_fail ? "FAIL\n" : "PASS\n"); - return g_fail ? 1 : 0; -} diff --git a/src/spec/suffix_drafter.cpp b/src/spec/suffix_drafter.cpp deleted file mode 100644 index 6f04f76..0000000 --- a/src/spec/suffix_drafter.cpp +++ /dev/null @@ -1,88 +0,0 @@ -// src/spec/suffix_drafter.cpp - see include/strata/spec/suffix_drafter.hpp. -#include "strata/spec/suffix_drafter.hpp" - -#include - -namespace strata::spec { - -namespace { -uint64_t mix(uint64_t x) { - x ^= x >> 33; - x *= 0xff51afd7ed558ccdull; - x ^= x >> 33; - x *= 0xc4ceb9fe1a85ec53ull; - return x ^ (x >> 33); -} -} // namespace - -SuffixDrafter::SuffixDrafter(int min_match, int max_match, size_t capacity_tokens) - : min_match_(std::max(3, min_match)), max_match_(std::max(min_match, max_match)) { - size_t cap = 1; - while (cap < capacity_tokens * 2) cap <<= 1; // load factor <= 0.5 at the nominal capacity - table_.assign(cap, Slot{}); - mask_ = cap - 1; - hist_.reserve(capacity_tokens); -} - -void SuffixDrafter::reset() { - hist_.clear(); - std::fill(table_.begin(), table_.end(), Slot{}); - last_match_ = 0; -} - -uint64_t SuffixDrafter::key_at(size_t end) const { - const uint64_t a = (uint32_t) hist_[end - 2], b = (uint32_t) hist_[end - 1], c = (uint32_t) hist_[end]; - return mix(a * 0x9E3779B97F4A7C15ull ^ mix(b + 0x632BE59BD9B4E019ull) ^ (c << 1)) | 1ull; // never 0 -} - -SuffixDrafter::Slot* SuffixDrafter::find_slot(uint64_t key, bool insert) { - for (size_t i = key & mask_, probes = 0; probes <= mask_; i = (i + 1) & mask_, ++probes) { - Slot& s = table_[i]; - if (s.key == key) return &s; - if (s.key == 0) { - if (!insert) return nullptr; - s.key = key; - return &s; - } - } - return nullptr; // table full: the history outgrew its capacity -} - -void SuffixDrafter::append(const int32_t* tokens, size_t n) { - for (size_t i = 0; i < n; ++i) { - hist_.push_back(tokens[i]); - const size_t end = hist_.size() - 1; - if (end < 2) continue; - Slot* s = find_slot(key_at(end), true); - if (s == nullptr) continue; - for (int w = WAYS - 1; w > 0; --w) s->pos[w] = s->pos[w - 1]; - s->pos[0] = (uint32_t) end; - if (s->n < WAYS) ++s->n; - } -} - -int SuffixDrafter::propose(int max_k, int32_t* out) { - last_match_ = 0; - const size_t n = hist_.size(); - if (n < 4 || max_k <= 0) return 0; - const size_t cur = n - 1; - const Slot* s = find_slot(key_at(cur), false); - if (s == nullptr) return 0; - size_t best_end = 0; - int best_len = 0; - for (int w = 0; w < s->n; ++w) { - const size_t p = s->pos[w]; - if (p >= cur) continue; // the current suffix itself - int len = 0; - while (len < max_match_ && len <= (int) p && hist_[p - len] == hist_[cur - len]) ++len; - if (len > best_len) { best_len = len; best_end = p; } // most recent first, so ties keep the newer - } - if (best_len < min_match_) return 0; - last_match_ = best_len; - int k = 0; - // The continuation may run into the current suffix (periodic text); reading history up to `cur` is valid. - for (size_t q = best_end + 1; q <= cur && k < max_k; ++q) out[k++] = hist_[q]; - return k; -} - -} // namespace strata::spec diff --git a/src/spec/suffix_drafter_test.cpp b/src/spec/suffix_drafter_test.cpp deleted file mode 100644 index 9fa8611..0000000 --- a/src/spec/suffix_drafter_test.cpp +++ /dev/null @@ -1,141 +0,0 @@ -// src/spec/suffix_drafter_test.cpp - plan v0.3 P6: suffix-lookup drafter tests and an offline simulation. -// -// suffix_drafter_test unit tests -// suffix_drafter_test --simulate [--k K] FILE.ids ... -// -// The simulation replays text as if a model had produced it: each step drafts up to K tokens, accepts the -// prefix that matches the true next tokens, and commits that prefix plus one model token (the verify pass's -// bonus). tokens/step is the lookup drafter's ceiling speedup on that text when a K+1-token verify costs the same -// as a 1-token step. Two regimes per file: -// continue history = first half of the prompt; generate its second half (natural continuation) -// copy history = the whole prompt; generate its middle third again (output quoting input: edits) -// No model runs; this measures the drafter on text, not on the model's own outputs. -#include "strata/spec/suffix_drafter.hpp" - -#include -#include -#include -#include -#include -#include -#include - -using strata::spec::SuffixDrafter; - -namespace { -int g_fail = 0; -void check(bool ok, const char* what) { - if (!ok) { std::fprintf(stderr, "FAIL: %s\n", what); ++g_fail; } -} - -std::vector read_ids(const char* path) { - std::ifstream f(path); - std::string text((std::istreambuf_iterator(f)), std::istreambuf_iterator()); - for (char& c : text) if (c == ',') c = ' '; - std::istringstream in(text); - std::vector ids; - for (int32_t v; in >> v;) ids.push_back(v); - return ids; -} - -struct Sim { long steps = 0, tokens = 0, proposals = 0, accepted = 0; }; - -Sim simulate(const std::vector& history, const std::vector& target, int K) { - SuffixDrafter d(3, 32, history.size() + target.size() + 16); - d.append(history.data(), history.size()); - Sim s; - std::vector draft(K); - size_t i = 0; - while (i < target.size()) { - const int n = d.propose(K, draft.data()); - int a = 0; - while (a < n && i + a < target.size() && draft[a] == target[i + a]) ++a; - if (n > 0) { ++s.proposals; s.accepted += a; } - const size_t commit = std::min(target.size() - i, (size_t) a + 1); - d.append(&target[i], commit); - i += commit; - s.tokens += (long) commit; - ++s.steps; - } - return s; -} - -void unit_tests() { - { // a repeated passage is proposed verbatim - SuffixDrafter d; - const std::vector doc = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; - d.append(doc.data(), doc.size()); - const int32_t again[] = {10, 11, 12}; - d.append(again, 3); - int32_t out[8]; - const int n = d.propose(5, out); - check(n == 5 && out[0] == 13 && out[4] == 17, "repeat proposes the continuation"); - check(d.last_match() == 3, "match length is the shared suffix"); - } - { // no earlier occurrence: nothing proposed - SuffixDrafter d; - const std::vector doc = {1, 2, 3, 4, 5, 6, 7}; - d.append(doc.data(), doc.size()); - int32_t out[4]; - check(d.propose(4, out) == 0, "no match proposes nothing"); - } - { // two occurrences of the trigram: the longer match wins even though it is older - SuffixDrafter d; - const std::vector doc = {7, 8, 1, 2, 3, 100, 101, 9, 1, 2, 3, 200, 201, 50, 7, 8, 1, 2, 3}; - d.append(doc.data(), doc.size()); - int32_t out[2]; - const int n = d.propose(2, out); - check(n == 2 && out[0] == 100 && out[1] == 101, "longest match preferred over most recent"); - check(d.last_match() == 5, "longest match length 5"); - } - { // a match shorter than min_match is ignored (only a bigram in common) - SuffixDrafter d(4); - const std::vector doc = {1, 2, 3, 9, 5, 2, 3}; - d.append(doc.data(), doc.size()); - int32_t out[2]; - check(d.propose(2, out) == 0, "min_match respected"); - } - { // periodic text: the continuation may run into the current suffix - SuffixDrafter d; - const std::vector doc = {1, 2, 3, 1, 2, 3, 1, 2, 3}; - d.append(doc.data(), doc.size()); - int32_t out[6]; - const int n = d.propose(6, out); - check(n >= 3 && out[0] == 1 && out[1] == 2 && out[2] == 3, "periodic continuation"); - } - { // bounded memory: appending beyond the nominal capacity does not crash and still works - SuffixDrafter d(3, 32, 1024); - std::vector doc; - for (int i = 0; i < 5000; ++i) doc.push_back(i % 997); - d.append(doc.data(), doc.size()); - int32_t out[4]; - check(d.propose(4, out) > 0, "propose after overflow of nominal capacity"); - } - std::printf("suffix_drafter unit tests: %s\n", g_fail ? "FAILED" : "OK"); -} -} // namespace - -int main(int argc, char** argv) { - if (argc > 1 && std::strcmp(argv[1], "--simulate") == 0) { - int K = 8, first = 2; - if (argc > 3 && std::strcmp(argv[2], "--k") == 0) { K = std::atoi(argv[3]); first = 4; } - std::printf("%-28s %8s | %-44s | %-44s\n", "prompt", "tokens", "continue: tok/step proposals acc/proposal", - "copy: tok/step proposals acc/proposal"); - for (int f = first; f < argc; ++f) { - const std::vector ids = read_ids(argv[f]); - if (ids.size() < 64) continue; - const size_t half = ids.size() / 2; - const Sim c = simulate({ids.begin(), ids.begin() + half}, {ids.begin() + half, ids.end()}, K); - const size_t a = ids.size() / 3, b = 2 * ids.size() / 3; - const Sim p = simulate(ids, {ids.begin() + a, ids.begin() + b}, K); - const char* name = std::strrchr(argv[f], '/') ? std::strrchr(argv[f], '/') + 1 : argv[f]; - std::printf("%-28s %8zu | %8.2f %10.1f%% %10.2f | %8.2f %10.1f%% %10.2f\n", name, ids.size(), - (double) c.tokens / c.steps, 100.0 * c.proposals / c.steps, - c.proposals ? (double) c.accepted / c.proposals : 0.0, (double) p.tokens / p.steps, - 100.0 * p.proposals / p.steps, p.proposals ? (double) p.accepted / p.proposals : 0.0); - } - return 0; - } - unit_tests(); - return g_fail ? 1 : 0; -} diff --git a/tests/core/expert_cache_per_layer_test.cpp b/tests/core/expert_cache_per_layer_test.cpp deleted file mode 100644 index 26bfdd4..0000000 --- a/tests/core/expert_cache_per_layer_test.cpp +++ /dev/null @@ -1,44 +0,0 @@ -// #369: per-layer admission on a sized cache (open_sized, every native pack) - each layer admits into its own slot -// range, as on the uniform cache, so no two layers write the same slot. Needs a CUDA device (exits 77 without one). -#include "strata/core/expert_cache.hpp" - -#include - -#include -#include -#include - -int main() { - int n = 0; - if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { - std::puts("no CUDA device: skipped"); - return 77; - } - std::string err; - for (int sized = 0; sized < 2; ++sized) { - strata::core::ExpertCache cache; - const bool ok = sized ? cache.open_sized(std::vector(6, 1024), 3, 4, err) - : cache.open(6, 3, 4, 1024, err); - if (!ok) { - std::fprintf(stderr, "open: %s\n", err.c_str()); - return 1; - } - cache.set_per_layer_admission(true); - for (int64_t layer = 0; layer < 3; ++layer) { - int64_t lo = 0, hi = 0; - cache.layer_slot_range(layer, lo, hi); - for (int64_t e = 0; e < 3; ++e) { - const int32_t slot = cache.admit(layer, e); - const bool want_room = lo + e < hi; - if (want_room ? slot != (int32_t) (lo + e) : slot != strata::core::kNotResident) { - std::fprintf(stderr, "%s cache: layer %lld expert %lld got slot %d (range %lld..%lld)\n", - sized ? "sized" : "uniform", (long long) layer, (long long) e, slot, (long long) lo, - (long long) hi - 1); - return 1; - } - } - } - } - std::puts("expert cache per-layer admission: uniform and sized caches passed"); - return 0; -} diff --git a/tests/core/expert_cache_segmented_test.cpp b/tests/core/expert_cache_segmented_test.cpp deleted file mode 100644 index cabf24a..0000000 --- a/tests/core/expert_cache_segmented_test.cpp +++ /dev/null @@ -1,99 +0,0 @@ -// #533: the segmented expert cache (--vram-elastic). A shrink gives the last segments' VRAM back to the driver and -// keeps every slot left exactly as it was (same address, same bytes); a grow maps them again at the same addresses. -// Uniform and sized slots. Needs a CUDA device with virtual memory management (exits 77 without one). -#include "strata/core/expert_cache.hpp" - -#include - -#include -#include -#include - -namespace { -int fail(const char* what, const std::string& err = "") { - std::fprintf(stderr, "FAIL %s %s\n", what, err.c_str()); - return 1; -} - -size_t free_vram() { - size_t f = 0, t = 0; - cudaMemGetInfo(&f, &t); - return f; -} - -// slot i holds the byte (i * 7 + 1) everywhere -bool fill(strata::core::ExpertCache& c, int64_t from, int64_t to, int64_t blob) { - std::vector b((size_t) blob); - for (int64_t i = from; i < to; ++i) { - std::fill(b.begin(), b.end(), (uint8_t) (i * 7 + 1)); - if (cudaMemcpy(c.device_slot((int32_t) i), b.data(), (size_t) blob, cudaMemcpyHostToDevice) != cudaSuccess) - return false; - } - return true; -} - -bool check(const strata::core::ExpertCache& c, int64_t to, int64_t blob) { - std::vector b((size_t) blob); - for (int64_t i = 0; i < to; ++i) { - if (cudaMemcpy(b.data(), c.device_slot((int32_t) i), (size_t) blob, cudaMemcpyDeviceToHost) != cudaSuccess) - return false; - for (const uint8_t x : b) - if (x != (uint8_t) (i * 7 + 1)) return false; - } - return true; -} -} // namespace - -int main() { - int n = 0; - if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { - std::puts("no CUDA device: skipped"); - return 77; - } - constexpr int64_t kBlob = 1 << 20, kSlots = 96, kSeg = 8ll << 20; - for (int sized = 0; sized < 2; ++sized) { - strata::core::ExpertCache c; - c.set_segment_bytes(kSeg); - std::string err; - const bool ok = sized ? c.open_sized(std::vector(kSlots, kBlob), 4, 64, err) - : c.open(kSlots, 4, 64, kBlob, err); - if (!ok) { - if (err.find("virtual memory management") != std::string::npos) { - std::printf("%s: skipped\n", err.c_str()); - return 77; - } - return fail("open", err); - } - if (!c.segmented() || c.slots() != kSlots || c.mapped_bytes() < kSlots * kBlob) return fail("open sizes"); - uint8_t* const first = c.device_slot(0); - if (!fill(c, 0, kSlots, kBlob)) return fail("fill"); - const size_t before = free_vram(); - // keep 30 MiB: rounded up to whole 8 MiB segments = 32 MiB = 32 slots - if (!c.shrink(30ll << 20, err)) return fail("shrink", err); - if (c.slots() != 32 || c.mapped_bytes() != 32ll << 20 || c.bytes() != 32ll << 20) - return fail("shrunk sizes"); - if (c.full_slots() != kSlots || c.full_bytes() != kSlots * kBlob) return fail("full sizes"); - const size_t freed = free_vram() - before; - if (freed + (8u << 20) < (size_t) (64ll << 20)) { // ~64 MiB back to the driver (WDDM rounds a little) - std::fprintf(stderr, "freed %zu bytes\n", freed); - return fail("VRAM not given back"); - } - if (c.device_slot(0) != first || !check(c, 32, kBlob)) return fail("slots kept after the shrink"); - // grow to 70 MiB: whole segments only, 64 MiB = 64 slots - if (!c.grow(70ll << 20, err) || c.slots() != 64) return fail("grow part", err); - if (!c.grow(1ll << 40, err) || c.slots() != kSlots || c.mapped_bytes() < kSlots * kBlob) - return fail("grow all", err); - if (c.device_slot(0) != first || !check(c, 32, kBlob)) return fail("slots kept after the grow"); - if (!fill(c, 32, kSlots, kBlob) || !check(c, kSlots, kBlob)) return fail("the grown slots"); - if (c.slots_within(0) != 0 || c.slots_within(kBlob * 3 + 5) != 3 || c.bytes_of(5) != 5 * kBlob) - return fail("slots_within / bytes_of"); - c.close(); - if (c.valid() || c.slots() != 0) return fail("close"); - } - // the default (no segment size): one allocation, shrink refused - strata::core::ExpertCache d; - std::string err; - if (!d.open(8, 2, 4, kBlob, err) || d.segmented() || d.shrink(0, err)) return fail("unsegmented", err); - std::puts("expert cache segments: shrink gives VRAM back and keeps the slots, grow maps them again"); - return 0; -} diff --git a/tests/core/expert_layout_test.cpp b/tests/core/expert_layout_test.cpp deleted file mode 100644 index 76c6066..0000000 --- a/tests/core/expert_layout_test.cpp +++ /dev/null @@ -1,412 +0,0 @@ -// tests/core/expert_layout_test.cpp - native_experts.txt (v2/v3/v4) and the expert arena filled from GGUF shards, -// without a model or a GPU. -// -// 1. Copies of the real packs' native_experts.txt (tests/data/native_experts: Q2_0, IQ2_XS, IQ3_XXS, IQ3_S, -// Coder IQ1_M, Swift IQ2_XS; v2 and v3 headers) parse to the layout the pre-v4 reader produced: the test -// parses each line again with that reader's rules (one shard name for all three roles) and compares every -// field, and the totals with the header's. -// 2. The v4 shard column `gate,up,down` (an empty field = the --native shard); v5, four names, two names and a -// trailing column are refused. -// 3. check_experts_gguf + load_experts_gguf on a synthetic arena at the real dimensions 2560/640 with Unsloth's -// format pairs (Q4_K/Q5_1, Q5_K/Q8_0): layer 1's gate/up in another file than its down. Every byte of the -// arena is compared with the source tensors. Then the refusals: an offset that is not the tensor's, a -// truncated file, a role named in the wrong file, a type or a shape the pack does not say, a missing file. -#include "gguf_fixture.hpp" - -#include "strata/core/expert_source.hpp" -#include "strata/core/pinned.hpp" -#include "strata/kernels/cpu/expert_layout.hpp" -#include "strata/kernels/cpu/native_expert.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fs = std::filesystem; -using strata::kernels::cpu::ExpertLayout; - -namespace { -int g_fail = 0; -void check(bool ok, const std::string& what) { - std::printf(" %-84s %s\n", what.c_str(), ok ? "ok" : "FAIL"); - if (!ok) ++g_fail; -} - -struct TempDir { - fs::path path; - TempDir() { - path = fs::temp_directory_path() / - ("strata-expert-layout-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); - fs::create_directories(path); - } - ~TempDir() { - std::error_code ignored; - fs::remove_all(path, ignored); - } -}; - -void write_text(const fs::path& p, const std::string& s) { std::ofstream(p, std::ios::binary) << s; } - -bool load(const fs::path& dir, int64_t n_layers, int64_t n_expert, int64_t n_embd, int64_t n_ff, std::string& err) { - err.clear(); - return strata::kernels::cpu::expert_layout_load(dir.string(), n_layers, n_expert, n_embd, n_ff, err); -} -bool load(const fs::path& dir, int64_t n_layers, int64_t n_expert, std::string& err) { - return load(dir, n_layers, n_expert, 2560, 640, err); -} - -// ---- 1. the real packs' files -void real_packs(const fs::path& data) { - for (const char* pack : {"q2_0", "iq2_xs", "iq3_xxs", "iq3_s", "coder-iq1_m", "swift-iq2_xs"}) { - TempDir d; - fs::copy_file(data / (std::string(pack) + ".txt"), d.path / "native_experts.txt"); - std::string err; - const bool ok = load(d.path, 48, 512, err); - check(ok, std::string(pack) + ": loads" + (ok ? "" : ": " + err)); - if (!ok) continue; - const ExpertLayout& L = strata::kernels::cpu::expert_layout(); - // the pre-v4 reader's rules, applied to the same text - std::ifstream in(d.path / "native_experts.txt"); - std::string line; - long long hdr_n = -1, hdr_total = -1; - bool same = L.native && L.n_layers == 48 && L.gguf_off.size() == 3 * 48; - uint64_t max_blob = 0; - while (std::getline(in, line)) { - if (line.empty()) continue; - if (line[0] == '#') { - if (line.find("(n_expert ") == std::string::npos) continue; - std::istringstream h(line.substr(line.find("(n_expert ") + 10)); - char comma = 0; - std::string word; - h >> hdr_n >> comma >> word >> hdr_total; // "(n_expert N, total T; ..." - continue; - } - std::istringstream ss(line); - long long l = 0, gt = 0, dt = 0; - unsigned long long off = 0, blob = 0, o[3] = {0, 0, 0}; - std::string file; - ss >> l >> gt >> dt >> off >> blob >> o[0] >> o[1] >> o[2]; - ss >> file; - same = same && L.fmt[(size_t) l].gu_type == gt && L.fmt[(size_t) l].d_type == dt && - L.offset[(size_t) l] == off && L.bytes[(size_t) l] == blob; - for (int r = 0; r < 3; ++r) { - same = same && L.gguf_off[(size_t) (3 * l + r)] == o[r]; - const std::string got = L.gguf_file.empty() ? std::string() : L.gguf_file[(size_t) (3 * l + r)]; - same = same && got == file; - } - if (blob > max_blob) max_blob = blob; - } - same = same && L.n_expert == hdr_n && (long long) L.total == hdr_total && L.max_blob == max_blob; - check(same, std::string(pack) + ": every field as the pre-v4 reader, totals as the header (v" + - std::to_string(L.version) + ", n_expert " + std::to_string(L.n_expert) + ")"); - } -} - -// ---- 1b. Qwen3.6-35B-A3B's two files (tools/iq_pack.py --layout-only over the real UD-IQ3_XXS and UD-Q4_K_XL files, -// 2026-10-11): 40 layers x 256 experts at 2048 x 512. Loaded with the model's geometry every layer's NativeFmt makes -// the pack's blob; loaded with Flash-Next's 2560 x 640 (what expert_layout_load passed until the Qwen3.6 port's -// step 2, geometry-inventory.md row 108) the same files are refused by their numbers. The per-layer types are -// the census of docs/QWEN36-35B-A3B.md section 1: IQ2_S gate/up with IQ3_XXS down on 37 layers and IQ4_XS on -// layers 34, 38, 39; Q4_K/Q5_K on 37 layers, Q4_K/Q6_K on 34 and 38, Q5_K/Q6_K on 39 (the largest blob). -void qwen36(const fs::path& data) { - struct Case { const char* file; int gu, d, d_odd; int64_t blob, blob_odd, blob_39; uint64_t total; }; - const Case cases[] = { - {"qwen36-iq3_xxs.txt", 22, 18, 23, 1073152, 1228800, 1228800, 11108614144ull}, - {"qwen36-q4_k_xl.txt", 12, 13, 14, 1900544, 2039808, 2301952, 19635634176ull}, - }; - for (const Case& c : cases) { - TempDir d; - fs::copy_file(data / c.file, d.path / "native_experts.txt"); - std::string err; - const bool ok = load(d.path, 40, 256, 2048, 512, err); - check(ok, std::string(c.file) + ": loads at the model's 40 x 256 x 2048 x 512" + (ok ? "" : ": " + err)); - if (ok) { - const ExpertLayout& L = strata::kernels::cpu::expert_layout(); - bool types = L.native && L.n_layers == 40 && L.n_expert == 256 && L.total == c.total && L.max_blob == (uint64_t) c.blob_39; - for (int64_t l = 0; l < 40 && types; ++l) { - const auto& f = L.fmt[(size_t) l]; - const bool odd = l == 34 || l == 38 || l == 39; - types = f.n_embd == 2048 && f.n_ff == 512 && f.bytes == L.bytes[(size_t) l] && - f.gu_type == (l == 39 && c.gu == 12 ? 13 : c.gu) && f.d_type == (odd ? c.d_odd : c.d) && - (int64_t) f.bytes == (l == 39 ? c.blob_39 : odd ? c.blob_odd : c.blob); - } - check(types, std::string(c.file) + ": per-layer formats and blobs (down " + std::to_string(c.d_odd) + - " on 34/38/39, " + std::to_string(c.blob_39) + " B at layer 39, total " + - std::to_string(c.total) + " B)"); - const auto& f0 = L.fmt[0]; - check(f0.up_off == f0.gu_row * 512 && f0.down_off == 2 * f0.up_off && f0.bytes == f0.down_off + f0.d_row * 2048, - std::string(c.file) + ": blob = gate rows | up rows | down rows at 512 and 2048"); - } - // n_ff 640 is not whole 256-value blocks for IQ2_S / Q4_K rows, so native_fmt refuses before the blob is - // compared; a geometry that IS whole blocks (2048 x 512 for a 2560 x 640 pack) would reach the blob message. - const bool refused = !load(d.path, 40, 256, 2560, 640, err); - check(refused && (err.find("not whole blocks") != std::string::npos || - (err.find("layer 0 blob is") != std::string::npos && err.find("2560 x n_ff 640") != std::string::npos)), - std::string(c.file) + ": at Flash-Next's 2560 x 640 refused: " + err.substr(0, 60)); - } - // a pack with no native_experts.txt is the canonical Q2_0 form, which bakes 2560 x 640: refused for a 2048 x 512 model - TempDir d; - std::string err; - check(!load(d.path, 40, 256, 2048, 512, err) && err.find("canonical Q2_0") != std::string::npos, - "no native_experts.txt (canonical Q2_0 pack) refused for a 2048 x 512 model: " + err.substr(0, 50)); - check(load(d.path, 48, 512, 2560, 640, err), "no native_experts.txt at the canonical 2560 x 640 still loads"); -} - -// ---- 2. the v4 column and the refusals -std::string manifest(int version, const std::string& col1, int64_t blob, int n_expert = 2) { - std::string s = "# strata native experts v" + std::to_string(version) + - ": layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard | gate,up,down] " - "(n_expert " + std::to_string(n_expert) + ", total " + std::to_string(2 * blob * n_expert) + ")\n"; - s += "0 12 7 0 " + std::to_string(blob) + " 100 200 300\n"; - s += "1 12 7 " + std::to_string(blob * n_expert) + " " + std::to_string(blob) + " 400 500 600" + - (col1.empty() ? "" : " " + col1) + "\n"; - return s; -} - -void columns() { - strata::kernels::cpu::NativeFmt f; - std::string err; - if (!strata::kernels::cpu::native_fmt(12, 7, 2560, 640, f, err)) { - check(false, "Q4_K/Q5_1 native format: " + err); - return; - } - const int64_t blob = (int64_t) f.bytes; - TempDir d; - write_text(d.path / "native_experts.txt", manifest(4, "B.gguf,B.gguf,", blob)); - bool ok = load(d.path, 2, 512, err); - const ExpertLayout& L = strata::kernels::cpu::expert_layout(); - check(ok && L.version == 4 && L.gguf_file.size() == 6 && L.gguf_file[0].empty() && L.gguf_file[2].empty() && - L.gguf_file[3] == "B.gguf" && L.gguf_file[4] == "B.gguf" && L.gguf_file[5].empty() && - L.gguf_off[5] == 600, - "v4: `B.gguf,B.gguf,` = gate and up in B.gguf, down in the --native shard" + (ok ? "" : ": " + err)); - write_text(d.path / "native_experts.txt", manifest(3, "A.gguf", blob)); - ok = load(d.path, 2, 512, err); - check(ok && L.gguf_file[3] == "A.gguf" && L.gguf_file[4] == "A.gguf" && L.gguf_file[5] == "A.gguf", - "v3: one name covers the three roles"); - write_text(d.path / "native_experts.txt", manifest(5, "", blob)); - ok = load(d.path, 2, 512, err); - check(!ok && err.find("v5") != std::string::npos, "v5 is refused (\"" + err.substr(0, 40) + "...\")"); - write_text(d.path / "native_experts.txt", manifest(4, "a,b,c,d", blob)); - check(!load(d.path, 2, 512, err) && err.find("gate,up,down") != std::string::npos, "four names are refused"); - write_text(d.path / "native_experts.txt", manifest(4, "a,b", blob)); - check(!load(d.path, 2, 512, err), "two names are refused"); - write_text(d.path / "native_experts.txt", manifest(4, "a extra", blob)); - check(!load(d.path, 2, 512, err), "a column after the shard column is refused"); -} - -// ---- 3. the arena from synthetic shards -void arena() { - using fixture::Tensor; - constexpr int64_t H = 2560, FF = 640, NE = 2; - const uint32_t Q4_K = 12, Q5_1 = 7, Q5_K = 13, Q8_0 = 8, Q3_K = 11, IQ3_S = 21; - strata::kernels::cpu::NativeFmt f0, f1; - std::string err; - if (!strata::kernels::cpu::native_fmt(Q4_K, Q5_1, H, FF, f0, err) || - !strata::kernels::cpu::native_fmt(Q5_K, Q8_0, H, FF, f1, err)) { - check(false, "Q4_K/Q5_1 and Q5_K/Q8_0 native formats: " + err); - return; - } - TempDir d; - const fs::path A = d.path / "M-00002-of-00003.gguf", B = d.path / "M-00003-of-00003.gguf"; - // A: layer 0 (all roles) and layer 1's down; B: layer 1's gate and up - const std::vector ta = {{"blk.0.ffn_gate_exps.weight", {H, FF, NE}, Q4_K, 11}, - {"blk.0.ffn_up_exps.weight", {H, FF, NE}, Q4_K, 12}, - {"blk.0.ffn_down_exps.weight", {FF, H, NE}, Q5_1, 13}, - {"blk.1.ffn_down_exps.weight", {FF, H, NE}, Q8_0, 23}}; - const std::vector tb = {{"blk.1.ffn_gate_exps.weight", {H, FF, NE}, Q5_K, 21}, - {"blk.1.ffn_up_exps.weight", {H, FF, NE}, Q5_K, 22}}; - const auto wa = fixture::write(A, {}, ta); - const auto wb = fixture::write(B, {}, tb); - auto at = [](const fixture::Written& w, size_t i) { return std::to_string(w.data_start + w.offsets[i]); }; - const uint64_t total = (f0.bytes + f1.bytes) * NE; - auto text = [&](const std::string& down1, const std::string& col1) { - return "# strata native experts v4: layer gu_type d_type offset blob_bytes gate_off up_off down_off " - "[shard | gate,up,down] (n_expert 2, total " + std::to_string(total) + ")\n" + - "0 12 7 0 " + std::to_string(f0.bytes) + " " + at(wa, 0) + " " + at(wa, 1) + " " + at(wa, 2) + "\n" + - "1 13 8 " + std::to_string(f0.bytes * NE) + " " + std::to_string(f1.bytes) + " " + at(wb, 0) + " " + - at(wb, 1) + " " + down1 + " " + col1 + "\n"; - }; - const fs::path pack = d.path / "pack"; - fs::create_directories(pack); - write_text(pack / "native_experts.txt", text(at(wa, 3), B.filename().string() + "," + B.filename().string() + ",")); - bool ok = load(pack, 2, 512, err); - check(ok, "the v4 manifest of the split layer loads" + (ok ? "" : ": " + err)); - if (!ok) return; - const ExpertLayout& L = strata::kernels::cpu::expert_layout(); - ok = strata::core::check_experts_gguf(A.string(), L, err); - check(ok, "check_experts_gguf: every span is its tensor" + (ok ? "" : ": " + err)); - std::vector dst((size_t) L.total, 0xEE); - const strata::core::LoadStats st = strata::core::load_experts_gguf(A.string(), dst.data(), L, 3); - check(st.ok && st.bytes == L.total && L.total == total, "load_experts_gguf reads the whole arena (" + - std::to_string(L.total) + " B)"); - // every byte: expert e's slice of role r comes from byte e * per[r] of that role's tensor - bool exact = true; - for (int64_t l = 0; l < 2 && exact; ++l) { - const auto& fm = L.fmt[(size_t) l]; - const uint64_t per[3] = {fm.up_off, fm.up_off, fm.bytes - fm.down_off}; - const uint64_t off[3] = {0, fm.up_off, fm.down_off}; - const uint8_t seed[2][3] = {{11, 12, 13}, {21, 22, 23}}; - for (int64_t e = 0; e < NE && exact; ++e) - for (int r = 0; r < 3 && exact; ++r) { - const uint8_t* got = dst.data() + L.blob_offset(l, e) + off[r]; - for (uint64_t j = 0; j < per[r]; ++j) - if (got[j] != fixture::pattern(seed[l][r], (uint64_t) e * per[r] + j)) { exact = false; break; } - } - } - check(exact, "every blob is [gate | up | down] of its expert, layer 1 from both files"); - - { // CS-T: the same blobs from FileExpertSource reading the shards in place (no experts.bin in the pack) - strata::core::FileExpertSource fs; - fs.set_gguf(A.string()); - std::string e1; - const bool opened = fs.open(pack.string(), 2, NE, e1); - check(opened && fs.gguf_mode(), "FileExpertSource opens the GGUF in place" + (opened ? "" : ": " + e1)); - if (opened) { - bool same = true, copies = true, transient = true; - std::vector buf((size_t) std::max(f0.bytes, f1.bytes)); - for (int64_t l = 0; l < 2; ++l) - for (int64_t e = 0; e < NE; ++e) { - fs.begin_layer(l, nullptr, 0); - const uint8_t* b = fs.blob(l, e); - const size_t n = (size_t) L.blob_bytes(l); - same = same && b != nullptr && std::memcmp(b, dst.data() + L.blob_offset(l, e), n) == 0; - copies = copies && fs.copy_blob(l, e, buf.data()) && - std::memcmp(buf.data(), dst.data() + L.blob_offset(l, e), n) == 0; - transient = transient && fs.transient(l, e); - } - check(same && copies && transient, "blob() and copy_blob() equal the loaded arena byte for byte (transient)"); - // a blob asked again in the same layer is the same buffer; its bytes hold through two more layers - fs.begin_layer(0, nullptr, 0); - const uint8_t* p = fs.blob(0, 1); - const uint8_t* q = fs.blob(0, 1); - fs.begin_layer(1, nullptr, 0); - (void) fs.blob(1, 0); - (void) fs.blob(1, 1); - fs.begin_layer(0, nullptr, 0); - (void) fs.blob(0, 0); - check(p == q && std::memcmp(p, dst.data() + L.blob_offset(0, 1), (size_t) L.blob_bytes(0)) == 0, - "an assembled blob stays put while it is in use"); - check(fs.file_read_bytes() > 0, "the file tier counts its bytes (" + std::to_string(fs.file_read_bytes()) + ")"); - // prefetch: a layer's experts fetched together on several threads, then the same bytes from blob() - bool pre = true; - for (int round = 0; round < 3; ++round) - for (int64_t l = 0; l < 2; ++l) { - fs.begin_layer(l, nullptr, 0); - fs.begin_layer(l == 0 ? 1 : 0, nullptr, 0); // age the buffers so the prefetch refills them - fs.begin_layer(l, nullptr, 0); - const int64_t both[2] = {1, 0}; - fs.set_fetch_threads(2); - fs.prefetch(l, both, 2); - for (int64_t e = 0; e < NE; ++e) { - const uint8_t* b = fs.blob(l, e); - pre = pre && b != nullptr && - std::memcmp(b, dst.data() + L.blob_offset(l, e), (size_t) L.blob_bytes(l)) == 0; - } - } - check(pre && fs.file_blob_bytes() > 0 && fs.file_ms() >= 0.0, - "prefetch on 2 threads, then blob(): the same bytes"); - } - fs.close(); - // with experts.bin present, the pack's file is mapped as before, whatever set_gguf says - { - std::ofstream eb(pack / "experts.bin", std::ios::binary); - eb.write((const char*) dst.data(), (std::streamsize) dst.size()); - } - strata::core::FileExpertSource fb; - fb.set_gguf(A.string()); - std::string e2; - const bool ob = fb.open(pack.string(), 2, NE, e2); - const uint8_t* b11 = ob ? fb.blob(1, 1) : nullptr; - check(ob && !fb.gguf_mode() && !fb.transient(1, 1) && b11 != nullptr && - std::memcmp(b11, dst.data() + L.blob_offset(1, 1), (size_t) L.blob_bytes(1)) == 0, - "with experts.bin the mapped file is used (unchanged behaviour)"); - fb.close(); - fs::remove(pack / "experts.bin"); - } - - auto refused = [&](const std::string& what, const std::string& needle) { - std::string e2; - const bool bad = load(pack, 2, 512, e2) && !strata::core::check_experts_gguf(A.string(), - strata::kernels::cpu::expert_layout(), e2); - check(bad && e2.find(needle) != std::string::npos, what + " (\"..." + needle + "...\")"); - }; - const std::string both = B.filename().string() + "," + B.filename().string() + ","; - write_text(pack / "native_experts.txt", text(std::to_string(std::stoull(at(wa, 3)) + 32), both)); - refused("an offset that is not the tensor's is refused", "starts at byte"); - write_text(pack / "native_experts.txt", text(at(wa, 3), "")); - refused("layer 1's gate named in the file that does not hold it is refused", "is not in it"); - write_text(pack / "native_experts.txt", text(at(wa, 3), both + ",x")); - std::string e3; - check(!load(pack, 2, 512, e3), "a malformed column is refused at load"); - write_text(pack / "native_experts.txt", text(at(wa, 3), "missing.gguf,missing.gguf,")); - refused("a shard that is not there is refused", "cannot open"); - fixture::write(B, {}, tb, /*cut=*/100); - write_text(pack / "native_experts.txt", text(at(wa, 3), both)); - refused("a truncated shard is refused before anything is read", "past the end"); - - // a type and a shape the pack does not say: Q3_K and IQ3_S are both 110 B per 256, so only the type differs - TempDir d2; - const fs::path C = d2.path / "C.gguf"; - const auto wc = fixture::write(C, {}, {{"blk.0.ffn_gate_exps.weight", {H, FF, NE}, IQ3_S, 31}, - {"blk.0.ffn_up_exps.weight", {H, FF, NE}, Q3_K, 32}, - {"blk.0.ffn_down_exps.weight", {FF, H, NE + 1}, Q5_1, 33}}); - strata::kernels::cpu::NativeFmt f2; - if (!strata::kernels::cpu::native_fmt(Q3_K, Q5_1, H, FF, f2, err)) { - check(false, "Q3_K/Q5_1 native format: " + err); - return; - } - fs::create_directories(d2.path / "pack"); - write_text(d2.path / "pack" / "native_experts.txt", - "# strata native experts v3: (n_expert 2, total " + std::to_string(f2.bytes * NE) + ")\n0 11 7 0 " + - std::to_string(f2.bytes) + " " + std::to_string(wc.data_start + wc.offsets[0]) + " " + - std::to_string(wc.data_start + wc.offsets[1]) + " " + std::to_string(wc.data_start + wc.offsets[2]) + "\n"); - ok = load(d2.path / "pack", 1, 512, err) && !strata::core::check_experts_gguf(C.string(), - strata::kernels::cpu::expert_layout(), err); - check(ok && err.find("is IQ3_S") != std::string::npos, "a gate of another type than the pack's is refused"); - // the same bytes with the pack's types, but a down tensor of three experts where the pack says two - fixture::write(C, {}, {{"blk.0.ffn_gate_exps.weight", {H, FF, NE}, Q3_K, 31}, - {"blk.0.ffn_up_exps.weight", {H, FF, NE}, Q3_K, 32}, - {"blk.0.ffn_down_exps.weight", {FF, H, NE + 1}, Q5_1, 33}}); - ok = load(d2.path / "pack", 1, 512, err) && !strata::core::check_experts_gguf(C.string(), - strata::kernels::cpu::expert_layout(), err); - check(ok && err.find("is not [640, 2560, 2]") != std::string::npos, "a down tensor of another shape is refused"); -} -} // namespace - -int main(int argc, char** argv) { - // `expert_layout_test --real PACK_DIR NATIVE_SHARD`: a real pack's native_experts.txt against its model's files - // (headers only - check_experts_gguf reads no expert byte) - if ((argc == 4 || argc == 8) && std::string(argv[1]) == "--real") { - // optional: N_LAYERS N_EXPERT N_EMBD N_FF (default Flash-Next's 48 512 2560 640; Qwen3.6 is 40 256 2048 512) - std::string err; - const int64_t nl = argc == 8 ? std::atoll(argv[4]) : 48, ne = argc == 8 ? std::atoll(argv[5]) : 512; - const int64_t nd = argc == 8 ? std::atoll(argv[6]) : 2560, nf = argc == 8 ? std::atoll(argv[7]) : 640; - if (!load(argv[2], nl, ne, nd, nf, err)) { std::printf("layout refused: %s\n", err.c_str()); return 1; } - const ExpertLayout& L = strata::kernels::cpu::expert_layout(); - const bool ok = strata::core::check_experts_gguf(argv[3], L, err); - size_t split = 0; - for (int64_t l = 0; l < L.n_layers && !L.gguf_file.empty(); ++l) - split += L.gguf_file[(size_t) (3 * l)] != L.gguf_file[(size_t) (3 * l + 2)]; - std::printf("%s: v%d, %lld layers x %lld experts, %.2f GiB, %zu layer(s) split per role: %s%s\n", argv[2], - L.version, (long long) L.n_layers, (long long) L.n_expert, (double) L.total / (1u << 30), split, - ok ? "every span is its tensor" : "REFUSED: ", ok ? "" : err.c_str()); - return ok ? 0 : 1; - } - std::printf("expert_layout_test\n"); - if (argc < 2) { - std::printf("usage: expert_layout_test \n"); - return 2; - } - real_packs(argv[1]); - qwen36(argv[1]); - columns(); - arena(); - std::printf(g_fail ? "expert_layout_test: %d FAILED\n" : "expert_layout_test: all passed\n", g_fail); - return g_fail ? 1 : 0; -} diff --git a/tests/core/expert_profile_save_test.cpp b/tests/core/expert_profile_save_test.cpp deleted file mode 100644 index 3013fd9..0000000 --- a/tests/core/expert_profile_save_test.cpp +++ /dev/null @@ -1,92 +0,0 @@ -// #477: --expert-profile-save's profile - rank_learned_profile's order (resident first, then the counted routing, then -// the profile the engine started from) and write_expert_profile's file, byte for byte tools/make_profile.py's format, -// read back by read_expert_profile. CPU only: no device is touched. -#include "strata/core/expert_cache.hpp" - -#include -#include -#include -#include -#include -#include - -namespace { -int fails = 0; -void check(bool ok, const char* what) { - if (!ok) { - std::fprintf(stderr, "FAIL: %s\n", what); - ++fails; - } -} -} // namespace - -int main() { - using Pair = std::pair; - const int64_t L = 3, E = 4; // 12 pairs, index = layer * 4 + expert - std::vector resident(12, 0); - resident[5] = 1; // (1, 1) - resident[2] = 1; // (0, 2) - std::vector heat(12, 0.0); - heat[2] = 1.0; - heat[5] = 7.0; - heat[11] = 9.0; // (2, 3): the hottest, but not resident - heat[0] = 3.0; - const std::vector prior = {{2, 0}, {1, 3}, {0, 1}}; // a profile that ranks three pairs - const std::vector r = strata::core::rank_learned_profile(L, E, resident, heat, prior); - check(r.size() == 12, "every pair is ranked"); - const std::vector head = {{1, 1}, {0, 2}, {2, 3}, {0, 0}, {2, 0}, {1, 3}, {0, 1}, {0, 3}}; - for (size_t i = 0; i < head.size() && i < r.size(); ++i) - check(r[i] == head[i], "resident by heat, then the rest by heat, then the prior, then the index"); - // no counts at all: the resident ones, then the prior's order - const std::vector r0 = strata::core::rank_learned_profile(L, E, resident, {}, prior); - check(r0.size() == 12 && r0[0] == Pair(0, 2) && r0[1] == Pair(1, 1) && r0[2] == Pair(2, 0) && - r0[3] == Pair(1, 3) && r0[4] == Pair(0, 1) && r0[5] == Pair(0, 0), "without heat: resident, then prior"); - - const std::filesystem::path dir = std::filesystem::temp_directory_path() / "strata_profile_save_test"; - std::filesystem::create_directories(dir); - const std::string path = (dir / "learned.bin").string(); - std::string err; - check(strata::core::write_expert_profile(path, L, E, r, err), "written"); - check(!std::filesystem::exists(path + ".tmp"), "no temporary file left"); - // the bytes make_profile.write_profile would write for the same ranking - std::vector want(4); - std::memcpy(want.data(), "STRP", 4); - auto u32 = [&](uint32_t v) { for (int b = 0; b < 4; ++b) want.push_back((uint8_t) (v >> (8 * b))); }; - auto u16 = [&](uint32_t v) { want.push_back((uint8_t) v); want.push_back((uint8_t) (v >> 8)); }; - for (uint32_t v : {1u, 3u, 4u, 12u, 12u}) u32(v); - for (const Pair& p : r) { u16((uint32_t) p.first); u16((uint32_t) p.second); } - std::vector table(12, -1); - for (size_t i = 0; i < r.size(); ++i) table[(size_t) (r[i].first * E + r[i].second)] = (int32_t) i; - for (int32_t v : table) u32((uint32_t) v); - std::vector got(want.size() + 1); - if (std::FILE* f = std::fopen(path.c_str(), "rb")) { - got.resize(std::fread(got.data(), 1, got.size(), f)); - std::fclose(f); - } - check(got == want, "the file is make_profile.py's format, byte for byte"); - std::vector back; - int64_t slots = 0; - check(strata::core::read_expert_profile(path, L, E, back, slots, err) && back == r && slots == 12, - "read back by the loader"); - // a second save replaces the first (the rename over an existing file) - check(strata::core::write_expert_profile(path, L, E, r0, err), "written again"); - check(strata::core::read_expert_profile(path, L, E, back, slots, err) && back == r0, "replaced"); - check(!strata::core::write_expert_profile(path, L, E, {{3, 0}}, err), "a pair out of range is refused"); - check(strata::core::read_expert_profile(path, L, E, back, slots, err) && back == r0, - "a refused save keeps the file"); - // a profile of another model is refused by its numbers: Flash-Next's 48 x 512 against Qwen3.6's 40 x 256 - // (expert_cache.cpp's header check; the Qwen3.6 port's step 2 negative test) - { - const std::string other = (dir / "flash-next.bin").string(); - check(strata::core::write_expert_profile(other, 48, 512, {{47, 511}, {0, 0}}, err), "a 48 x 512 profile written"); - const bool refused = !strata::core::read_expert_profile(other, 40, 256, back, slots, err); - check(refused && err.find("48x512") != std::string::npos && err.find("40x256") != std::string::npos && - err.find("different artifact") != std::string::npos, - "a 48 x 512 profile is refused for a 40 x 256 model, naming both"); - check(strata::core::read_expert_profile(other, 48, 512, back, slots, err) && back.size() == 2, - "the same profile reads for the 48 x 512 model"); - } - std::filesystem::remove_all(dir); - if (fails == 0) std::puts("expert_profile_save_test: OK"); - return fails == 0 ? 0 : 1; -} diff --git a/tests/core/file_expert_source_test.cpp b/tests/core/file_expert_source_test.cpp deleted file mode 100644 index 845d053..0000000 --- a/tests/core/file_expert_source_test.cpp +++ /dev/null @@ -1,360 +0,0 @@ -#include "strata/core/expert_source.hpp" -#include "strata/kernels/cpu/expert.hpp" -#include "strata/kernels/cpu/expert_layout.hpp" - -#if defined(STRATA_NATIVE_EXPERTS) -#include "strata/kernels/cpu/native_expert.hpp" -#include "ggml.h" -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fs = std::filesystem; - -namespace { - -void require(bool ok, const std::string& message) { - if (!ok) throw std::runtime_error(message); -} - -struct TempDirectory { - fs::path path; - - TempDirectory() { - const auto stamp = std::chrono::steady_clock::now().time_since_epoch().count(); - path = fs::temp_directory_path() / ("strata-file-source-test-" + std::to_string(stamp)); - fs::create_directories(path); - } - - ~TempDirectory() { - std::error_code ignored; - fs::remove_all(path, ignored); - } -}; - -void create_pack(const fs::path& dir, uint64_t bytes, const std::vector>& markers = {}) { - const fs::path file = dir / "experts.bin"; - { - std::ofstream out(file, std::ios::binary | std::ios::trunc); - require((bool) out, "could not create synthetic experts.bin"); - if (bytes > 0) { - out.seekp((std::streamoff) (bytes - 1)); - out.put('\0'); - } - require((bool) out, "could not size synthetic experts.bin"); - } - for (const auto& [offset, marker] : markers) { - require(offset < bytes, "synthetic marker lies beyond experts.bin"); - std::fstream file_out(file, std::ios::binary | std::ios::in | std::ios::out); - require((bool) file_out, "could not open synthetic experts.bin for markers"); - file_out.seekp((std::streamoff) offset); - file_out.put(marker); - require((bool) file_out, "could not write synthetic expert marker"); - } -} - -void check_file_size_rejection(strata::core::FileExpertSource& source, const fs::path& dir, int64_t layers, - int64_t experts, uint64_t expected_bytes) { - std::string err; - source.close(); - fs::resize_file(dir / "experts.bin", expected_bytes - 1); - require(!source.open(dir.string(), layers, experts, err), "a truncated expert file was accepted"); - require(!source.mapped() && !err.empty(), "truncated-file rejection left the source mapped or unreported"); - - fs::resize_file(dir / "experts.bin", expected_bytes + 1); - err.clear(); - require(!source.open(dir.string(), layers, experts, err), "an oversized expert file was accepted"); - require(!source.mapped() && !err.empty(), "oversized-file rejection left the source mapped or unreported"); -} - -void test_canonical_layout() { - using namespace strata::core; - using namespace strata::kernels::cpu; - constexpr int64_t layers = 2; - constexpr int64_t experts = 3; - const uint64_t layer_bytes = (uint64_t) experts * BLOB; - const uint64_t total = (uint64_t) layers * layer_bytes; - TempDirectory dir; - - std::string err; - const bool layout_ok = expert_layout_load(dir.path.string(), layers, experts, 2560, 640, err); - require(layout_ok, "could not load canonical layout: " + err); - create_pack(dir.path, total, {{0, 'a'}, {(uint64_t) BLOB, 'b'}, {layer_bytes, 'c'}, - {layer_bytes + (uint64_t) BLOB, 'd'}}); - - FileExpertSource source; - bool opened = source.open(dir.path.string(), layers, experts, err); - require(opened, "could not map canonical pack: " + err); - require(source.blobs() == layers * experts, "canonical blob count is wrong"); - const uint8_t* first = source.blob(0, 0); - const uint8_t* second = source.blob(0, 1); - const uint8_t* next_layer = source.blob(1, 0); - require(first && second && next_layer, "valid canonical blob lookup failed"); - require(second - first == (ptrdiff_t) BLOB && next_layer - first == (ptrdiff_t) layer_bytes, - "canonical expert or layer stride is wrong"); - require(first[0] == 'a' && second[0] == 'b' && next_layer[0] == 'c', - "canonical blob lookup returned bytes from the wrong expert"); - require(source.blob(-1, 0) == nullptr && source.blob(0, -1) == nullptr && - source.blob(layers, 0) == nullptr && source.blob(0, experts) == nullptr, - "canonical bounds check accepted an invalid layer or expert"); - require(source.reads() == 3, "invalid canonical lookups changed the read count"); - - check_file_size_rejection(source, dir.path, layers, experts, total); - create_pack(dir.path, total, {{layer_bytes, 'c'}}); - err.clear(); - opened = source.open(dir.path.string(), layers, experts, err); - require(opened, "source failed to reopen after size errors: " + err); - const uint8_t* reopened = source.blob(1, 0); - require(reopened && source.reads() == 1 && reopened[0] == 'c', "reopened canonical source kept stale state"); - source.close(); -} - -#if defined(STRATA_NATIVE_EXPERTS) -void test_native_variable_layout() { - using namespace strata::core; - using namespace strata::kernels::cpu; - constexpr int64_t layers = 2; - constexpr int64_t experts = 3; - constexpr int64_t embedding = 2560; - constexpr int64_t feed_forward = 640; - TempDirectory dir; - - NativeFmt first_fmt, second_fmt; - std::string err; - const bool first_ok = native_fmt(GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ4_NL, embedding, feed_forward, first_fmt, err); - require(first_ok, "IQ3_XXS/IQ4_NL synthetic format is unavailable: " + err); - err.clear(); - const bool second_ok = native_fmt(GGML_TYPE_IQ2_XS, GGML_TYPE_IQ4_NL, embedding, feed_forward, second_fmt, err); - require(second_ok, "IQ2_XS/IQ4_NL synthetic format is unavailable: " + err); - require(first_fmt.bytes != second_fmt.bytes, "chosen native formats do not exercise variable layer sizes"); - - const uint64_t layer0_bytes = (uint64_t) first_fmt.bytes * experts; - const uint64_t total = layer0_bytes + (uint64_t) second_fmt.bytes * experts; - { - std::ofstream metadata(dir.path / "native_experts.txt"); - require((bool) metadata, "could not create synthetic native_experts.txt"); - metadata << "0 " << GGML_TYPE_IQ3_XXS << ' ' << GGML_TYPE_IQ4_NL << " 0 " << first_fmt.bytes << '\n'; - metadata << "1 " << GGML_TYPE_IQ2_XS << ' ' << GGML_TYPE_IQ4_NL << ' ' << layer0_bytes << ' ' - << second_fmt.bytes << '\n'; - require((bool) metadata, "could not write synthetic native_experts.txt"); - } - create_pack(dir.path, total, {{0, 'a'}, {(uint64_t) first_fmt.bytes, 'b'}, - {layer0_bytes, 'c'}, {layer0_bytes + (uint64_t) second_fmt.bytes, 'd'}}); - - const bool layout_ok = expert_layout_load(dir.path.string(), layers, experts, 2560, 640, err); - require(layout_ok, "could not load synthetic native layout: " + err); - FileExpertSource source; - bool opened = source.open(dir.path.string(), layers, experts, err); - require(opened, "could not map native pack: " + err); - require(source.blobs() == layers * experts, "native blob count is wrong"); - const uint8_t* first = source.blob(0, 0); - const uint8_t* second = source.blob(0, 1); - const uint8_t* next_layer = source.blob(1, 0); - const uint8_t* next_layer_second = source.blob(1, 1); - require(first && second && next_layer && next_layer_second, "valid native blob lookup failed"); - require(second - first == (ptrdiff_t) first_fmt.bytes && next_layer - first == (ptrdiff_t) layer0_bytes && - next_layer_second - next_layer == (ptrdiff_t) second_fmt.bytes, - "native per-layer expert stride is wrong"); - require(first[0] == 'a' && second[0] == 'b' && next_layer[0] == 'c' && next_layer_second[0] == 'd', - "native blob lookup returned bytes from the wrong expert"); - require(source.blob(-1, 0) == nullptr && source.blob(0, -1) == nullptr && - source.blob(layers, 0) == nullptr && source.blob(0, experts) == nullptr, - "native bounds check accepted an invalid layer or expert"); - require(source.reads() == 4, "invalid native lookups changed the read count"); - - check_file_size_rejection(source, dir.path, layers, experts, total); - create_pack(dir.path, total, {{layer0_bytes, 'c'}}); - err.clear(); - opened = source.open(dir.path.string(), layers, experts, err); - require(opened, "source failed to reopen after size errors: " + err); - const uint8_t* reopened = source.blob(1, 0); - require(reopened && source.reads() == 1 && reopened[0] == 'c', "reopened native source kept stale state"); - source.close(); -} -#endif - -void test_complement_plan() { - using namespace strata::core::detail; - std::vector offsets; - uint64_t bytes = 0; - std::string error; - require(make_cache_complement_plan(2, 3, {3, 5}, {{0, 1}, {1, 2}}, {}, offsets, bytes, error), error); - require(bytes == 16 && offsets == std::vector{0, kNoCacheComplement, 3, 6, 11, kNoCacheComplement}, - "wrong compact offsets for variable native layer sizes"); - const uint8_t resident[16] = {}, mapped[5] = {}; - require(cache_complement_blob_or_fallback(1, offsets, resident, mapped) == mapped, - "GPU-resident expert lost mmap fallback"); - require(cache_complement_blob_or_fallback(4, offsets, resident, mapped) == resident + 11, - "CPU miss did not use resident complement"); - require(!make_cache_complement_plan(2, 3, {3, 5}, {{0, 1}, {0, 1}}, {}, offsets, bytes, error) - && offsets.empty() && bytes == 0, "duplicate pair accepted"); - require(!make_cache_complement_plan(2, 3, {3, 5}, {{0, 1}}, {{0, 1}}, offsets, bytes, error), - "overlapping tiers accepted"); - require(!make_cache_complement_plan(2, 3, {3, 5}, {{2, 0}}, {}, offsets, bytes, error), - "out-of-range pair accepted"); - require(!make_cache_complement_plan(2, 3, {0, 5}, {}, {}, offsets, bytes, error), "zero-size layer accepted"); -} - -void test_resident_lend_region() { - using namespace strata::core::detail; - // four slots (sizes 5, 3, 3, 5); the experts no slot holds take 10 bytes - const std::vector slots{5, 3, 3, 5}; - require(choose_resident_keep_from(slots, 10, 9, 1) == -1, "a base larger than the budget was accepted"); - require(choose_resident_keep_from(slots, 10, 10, 1) == 4, "no room: the lend region must stay on the file"); - require(choose_resident_keep_from(slots, 10, 15, 1) == 3, "the last slot fits and must be kept first"); - require(choose_resident_keep_from(slots, 10, 17, 1) == 3, "a slot that does not fit ends the lend region's walk"); - require(choose_resident_keep_from(slots, 10, 18, 1) == 2, "two slots fit"); - require(choose_resident_keep_from(slots, 10, 100, 1) == 1, "the walk must stop at the lend region's first slot"); - require(choose_resident_keep_from(slots, 10, 100, -1) == 4, "no lend region kept slots in RAM"); - require(choose_resident_keep_from(slots, 10, 100, 9) == 4, "an out-of-range lend region kept slots in RAM"); - require(choose_resident_keep_from({}, 0, 0, 0) == 0, "an empty cache"); -} - -void test_resident_exchange() { - using namespace strata::core; - using namespace strata::core::detail; - // 2 layers x 3 experts; the GPU holds (0,1) and (1,2): the compact copy holds the other four - std::vector offsets; - uint64_t bytes = 0; - std::string error; - require(make_cache_complement_plan(2, 3, {3, 5}, {{0, 1}, {1, 2}}, {}, offsets, bytes, error), error); - const std::vector before = offsets; - // (1,0) moves into the GPU, (1,2) leaves it: (1,2) takes (1,0)'s bytes' place - require(exchange_cache_complement(offsets, 3, 5), "a valid exchange was refused"); - require(offsets[5] == before[3] && offsets[3] == kNoCacheComplement, "the exchange did not move the place"); - for (size_t i : {0u, 1u, 2u, 4u}) require(offsets[i] == before[i], "an exchange touched another expert"); - // the copy's size and its set of places are unchanged - std::vector a, b; - for (uint64_t o : before) if (o != kNoCacheComplement) a.push_back(o); - for (uint64_t o : offsets) if (o != kNoCacheComplement) b.push_back(o); - std::sort(a.begin(), a.end()); - std::sort(b.begin(), b.end()); - require(a == b, "an exchange changed the compact copy's places"); - const std::vector after = offsets; - require(!exchange_cache_complement(offsets, 3, 0), "an `in` the copy does not hold was accepted"); - require(!exchange_cache_complement(offsets, 0, 2), "an `out` the copy holds already was accepted"); - require(!exchange_cache_complement(offsets, 0, 0), "a self-exchange was accepted"); - require(!exchange_cache_complement(offsets, 0, 6), "an out-of-range `out` was accepted"); - require(offsets == after, "a refused exchange changed the offsets"); - // and back: the copy is again what the plan makes for the original placement - require(exchange_cache_complement(offsets, 5, 3), "the reverse exchange was refused"); - require(offsets == before, "exchanging back did not restore the plan"); -} - -void test_cgroup_memory_budget() { - using namespace strata::core::detail; - constexpr uint64_t GiB = 1ull << 30; - uint64_t bytes = 0; - - CgroupMemoryStat clean_cache{40 * GiB, 32 * GiB, 0, 0, true}; - require(cgroup_available_bytes(56 * GiB, clean_cache, bytes), "valid cgroup memory.stat was rejected"); - require(bytes == 48 * GiB, "clean inactive file cache was not credited against the cgroup cap"); - - CgroupMemoryStat dirty_cache{40 * GiB, 32 * GiB, 4 * GiB, 2 * GiB, true}; - require(cgroup_available_bytes(56 * GiB, dirty_cache, bytes), "valid dirty-cache counters were rejected"); - require(bytes == 42 * GiB, "dirty/writeback pages were incorrectly counted as reclaimable"); - - CgroupMemoryStat oversized_inactive{10 * GiB, 20 * GiB, 0, 0, true}; - require(cgroup_available_bytes(12 * GiB, oversized_inactive, bytes), - "valid oversized inactive-file counter was rejected"); - require(bytes == 12 * GiB, "inactive-file accounting exceeded charged current usage"); - - const uint64_t max = std::numeric_limits::max(); - CgroupMemoryStat large_counters{max, max, max - 1, max, true}; - require(cgroup_available_bytes(max, large_counters, bytes), - "large memory.stat counters were rejected"); - require(bytes == 0, "dirty/writeback subtraction overflowed or escaped the usage cap"); - - CgroupMemoryStat usage_over_limit{60 * GiB, 0, 0, 0, true}; - require(cgroup_available_bytes(56 * GiB, usage_over_limit, bytes), - "valid over-limit memory counters were rejected"); - require(bytes == 0, "over-limit cgroup usage produced a positive budget"); - - CgroupMemoryStat missing_stat{}; - bytes = 123; - require(!cgroup_available_bytes(56 * GiB, missing_stat, bytes) && bytes == 0, - "missing memory.stat counters did not fail closed"); -} - -// #633: the host RAM probe with fake /proc and cgroup trees: v2 (a limit, "max", a missing or malformed limit), v1 -// (a limit, unlimited), and no cgroup line at all. Elsewhere than Linux it reads the machine's RAM. -void test_host_memory() { - using namespace strata::core::detail; - constexpr uint64_t GiB = 1ull << 30; - HostMemory m; -#if defined(__linux__) - TempDirectory t; - auto put = [&](const fs::path& rel, const std::string& text) { - fs::create_directories((t.path / rel).parent_path()); - std::ofstream(t.path / rel) << text; - }; - put("meminfo", "MemTotal: 134217728 kB\nMemAvailable: 104857600 kB\n"); // 100 GiB available - const std::string mi = (t.path / "meminfo").string(), cg = (t.path / "cgroup").string(), - root = (t.path / "fs").string(); - auto probe = [&](const std::string& self) { - put("cgroup", self); - return host_available_memory(m, mi, cg, root); - }; - // no cgroup line at all: MemAvailable alone (before #633: "cannot determine") - require(probe("") && m.available == 100 * GiB && m.cgroup_limit == ~0ull, "no cgroup: MemAvailable alone"); - // v2, a 48 GiB limit with 16 GiB charged, 4 GiB of it clean cache - put("fs/cgroup.controllers", "memory\n"); - put("fs/box/memory.max", std::to_string(48 * GiB) + "\n"); - put("fs/box/memory.current", std::to_string(16 * GiB) + "\n"); - put("fs/box/memory.stat", "inactive_file " + std::to_string(4 * GiB) + "\nfile_dirty 0\nfile_writeback 0\n"); - require(probe("0::/box\n") && m.available == 36 * GiB && m.cgroup_limit == 48 * GiB, "v2 limit"); - put("fs/box/memory.max", "max\n"); - require(probe("0::/box\n") && m.available == 100 * GiB && m.cgroup_limit == ~0ull, "v2 max"); - put("fs/box/memory.max", "48G\n"); - require(!probe("0::/box\n"), "v2 malformed limit accepted"); - fs::remove(t.path / "fs/box/memory.max"); - require(!probe("0::/box\n"), "v2 group without memory.max accepted"); - // v1: the memory controller's group (a hybrid line list), a 32 GiB limit with 10 GiB used - put("fs/memory/docker/abc/memory.limit_in_bytes", std::to_string(32 * GiB) + "\n"); - put("fs/memory/docker/abc/memory.usage_in_bytes", std::to_string(10 * GiB) + "\n"); - put("fs/memory/memory.limit_in_bytes", "9223372036854771712\n"); // the root: unlimited - put("fs/memory/memory.usage_in_bytes", std::to_string(50 * GiB) + "\n"); - require(probe("12:cpu,cpuacct:/docker/abc\n4:memory:/docker/abc\n1:name=systemd:/docker/abc\n") && - m.available == 22 * GiB && m.cgroup_limit == 32 * GiB, "v1 limit"); - put("fs/memory/docker/abc/memory.limit_in_bytes", "9223372036854771712\n"); - require(probe("4:memory:/docker/abc\n") && m.available == 100 * GiB && m.cgroup_limit == ~0ull, "v1 unlimited"); - // a v1 group not visible here (another namespace): MemAvailable alone - require(probe("4:memory:/elsewhere\n") && m.available == 100 * GiB, "v1 group not mounted"); -#else - require(host_available_memory(m) && m.available > 0 && m.cgroup_limit == ~0ull, "this PC's RAM"); - (void) GiB; -#endif -} - -} // namespace - -int main() { - try { - test_complement_plan(); - test_resident_lend_region(); - test_resident_exchange(); - test_cgroup_memory_budget(); - test_host_memory(); - test_canonical_layout(); -#if defined(STRATA_NATIVE_EXPERTS) - test_native_variable_layout(); -#endif - std::cout << "file_expert_source_test: PASS\n"; - return 0; - } catch (const std::exception& error) { - std::cerr << "file_expert_source_test: " << error.what() << '\n'; - return 1; - } -} diff --git a/tests/core/gguf_fixture.hpp b/tests/core/gguf_fixture.hpp deleted file mode 100644 index 75d0ea0..0000000 --- a/tests/core/gguf_fixture.hpp +++ /dev/null @@ -1,113 +0,0 @@ -// tests/core/gguf_fixture.hpp - synthetic GGUF v3 files for the loader tests (no gguf-py, no model, no GPU). -// -// A file is a header, metadata (strings and integers only), a tensor directory whose offsets are 32-byte aligned -// in the data section, and the tensors' payloads, each filled with a pattern the test can recognise. -#pragma once - -#include "strata/artifact/gguf_reader.hpp" - -#include -#include -#include -#include -#include -#include -#include - -namespace fixture { - -struct Kv { - std::string key; - uint32_t type = 8; ///< GGUF value type: 8 string, 2 u16, 4 u32, 5 i32, 6 f32, 9 array (of u32) - std::string s; - uint64_t u = 0; - float f = 0.0f; - std::vector 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& v) { return Kv{k, 9, {}, 0, 0.0f, v}; } - -struct Tensor { - std::string name; - std::vector shape; ///< GGUF order: dim 0 varies fastest - uint32_t type = 0; - uint8_t seed = 1; ///< payload byte i is (seed * 131 + i * 7 + i / 4093) & 0xff -}; - -inline uint8_t pattern(uint8_t seed, uint64_t i) { return (uint8_t) ((seed * 131u + i * 7u + i / 4093u) & 0xffu); } - -/// The split keys llama.cpp's gguf-split writes (u16 split.no / split.count, i32 split.tensors.count). -inline std::vector split_keys(uint64_t no, uint64_t count, uint64_t tensors) { - return {u16("split.no", no), u16("split.count", count), i32("split.tensors.count", tensors)}; -} - -struct Written { - uint64_t data_start = 0; - std::vector offsets; ///< per tensor, from data_start - uint64_t size = 0; -}; - -/// Writes `path`; `cut` bytes are dropped from the end (a truncated download). -inline Written write(const std::filesystem::path& path, const std::vector& kv, const std::vector& ts, - uint64_t cut = 0) { - std::vector b; - auto put = [&](const void* p, size_t n) { b.insert(b.end(), (const uint8_t*) p, (const uint8_t*) p + n); }; - auto put32 = [&](uint32_t v) { put(&v, 4); }; - auto put64 = [&](uint64_t v) { put(&v, 8); }; - auto puts = [&](const std::string& s) { put64(s.size()); put(s.data(), s.size()); }; - put32(0x46554747u); - put32(3); - put64(ts.size()); - put64(kv.size()); - for (const auto& k : kv) { - puts(k.key); - put32(k.type); - if (k.type == 8) puts(k.s); - else if (k.type == 2) { const uint16_t v = (uint16_t) k.u; put(&v, 2); } - else if (k.type == 4 || k.type == 5) { const uint32_t v = (uint32_t) k.u; put(&v, 4); } - else if (k.type == 6) put(&k.f, 4); - else if (k.type == 9) { // an array: element type u32, count, elements - put32(4); - put64(k.a.size()); - for (const uint32_t v : k.a) put32(v); - } - else throw std::runtime_error("fixture: unsupported metadata type"); - } - Written w; - std::vector bytes; - uint64_t at = 0; - for (const auto& t : ts) { - strata::TensorInfo info; - info.shape = t.shape; - info.type = t.type; - const uint64_t n = strata::tensor_payload_bytes(info); - if (n == 0) throw std::runtime_error("fixture: " + t.name + " has no whole-block byte count"); - puts(t.name); - put32((uint32_t) t.shape.size()); - for (uint64_t d : t.shape) put64(d); - put32(t.type); - put64(at); - w.offsets.push_back(at); - bytes.push_back(n); - at = (at + n + 31) / 32 * 32; - } - w.data_start = (b.size() + 31) / 32 * 32; - b.resize((size_t) w.data_start, 0); - for (size_t i = 0; i < ts.size(); ++i) { - b.resize((size_t) (w.data_start + w.offsets[i]), 0); - for (uint64_t j = 0; j < bytes[i]; ++j) b.push_back(pattern(ts[i].seed, j)); - } - if (cut > b.size()) cut = b.size(); - b.resize(b.size() - (size_t) cut); - w.size = b.size(); - std::ofstream f(path, std::ios::binary | std::ios::trunc); - f.write((const char*) b.data(), (std::streamsize) b.size()); - if (!f) throw std::runtime_error("fixture: cannot write " + path.string()); - return w; -} - -} // namespace fixture diff --git a/tests/core/gguf_split_test.cpp b/tests/core/gguf_split_test.cpp deleted file mode 100644 index 3f137cc..0000000 --- a/tests/core/gguf_split_test.cpp +++ /dev/null @@ -1,220 +0,0 @@ -// tests/core/gguf_split_test.cpp - a split model's shards (strata::gguf_split_paths) and their joint view -// (strata::GgufModel), on synthetic GGUFs: no model, no GPU. -// -// The layout is Unsloth's UD-Q4_K_XL in miniature: shard 1 holds the metadata and no tensor, shards 2-4 the -// tensors, and layer 11's down sits in shard 2 while its gate and up are in shard 3. Then the ways a real -// download goes wrong: a shard missing, a shard of another model (split keys that disagree), a tensor in two -// shards, a directory that does not add up to split.tensors.count, a truncated shard, and shard 1 opened alone. -#include "gguf_fixture.hpp" - -#include "strata/artifact/gguf_split.hpp" - -#include -#include -#include -#include -#include - -namespace fs = std::filesystem; - -namespace { -int g_fail = 0; -void check(bool ok, const std::string& what) { - std::printf(" %-78s %s\n", what.c_str(), ok ? "ok" : "FAIL"); - if (!ok) ++g_fail; -} - -struct TempDir { - fs::path path; - TempDir() { - path = fs::temp_directory_path() / - ("strata-gguf-split-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); - } -}; - -std::string shard_name(int i, int n) { - char b[64]; - std::snprintf(b, sizeof b, "Model-UD-Q4_K_XL-%05d-of-%05d.gguf", i, n); - return b; -} - -using fixture::Tensor; -const uint32_t F32 = 0, Q8_0 = 8; - -/// Writes the 4-shard model; `mutate(i, kv, tensors)` may change shard i (0-based) before it is written. -template std::vector write_model(const fs::path& dir, F mutate, uint64_t total = 7) { - std::vector paths; - for (int i = 0; i < 4; ++i) { - std::vector kv; - if (i == 0) kv.push_back(fixture::str("general.architecture", "qwen4exp")); - for (const auto& k : fixture::split_keys((uint64_t) i, 4, total)) kv.push_back(k); - std::vector ts; - if (i == 1) ts = {{"output.weight", {64, 4}, Q8_0, 1}, {"token_embd.weight", {64, 4}, Q8_0, 2}, - {"blk.11.ffn_down_exps.weight", {32, 32, 2}, F32, 3}}; - if (i == 2) ts = {{"blk.11.ffn_gate_exps.weight", {32, 32, 2}, F32, 4}, - {"blk.11.ffn_up_exps.weight", {32, 32, 2}, F32, 5}, {"blk.12.attn_q.weight", {32, 8}, F32, 6}}; - if (i == 3) ts = {{"output_norm.weight", {32}, F32, 7}}; - uint64_t cut = 0; - mutate(i, kv, ts, cut); - const fs::path p = dir / shard_name(i + 1, 4); - fixture::write(p, kv, ts, cut); - paths.push_back(p.string()); - } - return paths; -} -auto same = [](int, std::vector&, std::vector&, uint64_t&) {}; - -std::string error_of(const std::vector& paths) { - try { - strata::GgufModel m(paths); - } catch (const std::exception& e) { - return e.what(); - } - return {}; -} -} // namespace - -// `gguf_split_test --real SHARD`: the same view of a real model (headers only): its shards, the architecture -// check on the metadata shard, and where the tensors the engine reads by name live. -int real_model(const std::string& any) { - try { - const strata::GgufModel m = strata::GgufModel::open(any); - size_t tensors = 0; - for (size_t i = 0; i < m.size(); ++i) { - std::printf(" shard %zu: %s, %zu tensors, data at %llu\n", i + 1, m.shard(i).path().c_str(), - m.shard(i).tensors().size(), (unsigned long long) m.shard(i).data_start()); - tensors += m.shard(i).tensors().size(); - } - const std::string arch = strata::check_architecture(m.meta()); - std::printf(" %zu tensors; architecture check on the metadata shard: %s\n", tensors, - arch.empty() ? "ok" : arch.c_str()); - int bad = arch.empty() ? 0 : 1; - for (const char* name : {"output.weight", "token_embd.weight", "per_layer_token_embd.weight", - "blk.1.ple_key.weight", "blk.11.ffn_gate_exps.weight", "blk.11.ffn_up_exps.weight", - "blk.11.ffn_down_exps.weight"}) { - size_t s = 0; - const strata::TensorInfo* t = m.find(name, &s); - if (!t) { std::printf(" %-30s absent\n", name); continue; } - const bool ok = m.in_bounds(*t, s); - bad += !ok; - std::printf(" %-30s shard %zu, %s, %llu B, %s\n", name, s + 1, t->type_name(), - (unsigned long long) strata::tensor_payload_bytes(*t), ok ? "in bounds" : "OUT OF BOUNDS"); - } - return bad ? 1 : 0; - } catch (const std::exception& e) { - std::printf(" refused: %s\n", e.what()); - return 1; - } -} - -int main(int argc, char** argv) { - if (argc == 3 && std::string(argv[1]) == "--real") return real_model(argv[2]); - std::printf("gguf_split_test\n"); - { - TempDir d; - const auto paths = write_model(d.path, same); - // any shard names the family; the list is in split order, metadata shard first - std::vector got; - try { got = strata::gguf_split_paths(paths[2]); } catch (...) {} - check(got == paths, "gguf_split_paths from shard 3: the 4 shards in order"); - try { got = strata::gguf_split_paths(paths[0]); } catch (...) { got.clear(); } - check(got == paths, "gguf_split_paths from shard 1: the same 4 shards"); - check(strata::gguf_split_paths((d.path / "plain.gguf").string()).size() == 1, - "a name without -NNNNN-of-MMMMM is a model of one file"); - std::string err; - try { - const strata::GgufModel m(paths); - size_t s_out = 9, s_gate = 9, s_down = 9, s_up = 9; - const strata::TensorInfo* out = m.find("output.weight", &s_out); - const strata::TensorInfo* gate = m.find("blk.11.ffn_gate_exps.weight", &s_gate); - const strata::TensorInfo* up = m.find("blk.11.ffn_up_exps.weight", &s_up); - const strata::TensorInfo* down = m.find("blk.11.ffn_down_exps.weight", &s_down); - check(m.size() == 4 && m.meta().get("general.architecture") && m.meta().tensors().empty(), - "shard 1: the metadata, no tensor"); - check(out && s_out == 1 && m.in_bounds(*out, s_out), "output.weight found in shard 2, in bounds"); - check(gate && up && down && s_gate == 2 && s_up == 2 && s_down == 1, - "layer 11 per role: gate/up in shard 3, down in shard 2"); - check(m.find("blk.99.ffn_gate_exps.weight") == nullptr, "an absent tensor is nullptr"); - check(strata::check_architecture(m.meta()).find("block_count") != std::string::npos, - "the architecture guard reads the metadata shard (and wants its keys)"); - } catch (const std::exception& e) { - err = e.what(); - } - check(err.empty(), "the 4-shard model opens" + (err.empty() ? std::string() : ": " + err)); - } - { - TempDir d; - const auto paths = write_model(d.path, same); - fs::remove(paths[3]); - std::string err; - try { strata::gguf_split_paths(paths[0]); } catch (const std::exception& e) { err = e.what(); } - check(err.find("missing model shard") != std::string::npos && err.find(shard_name(4, 4)) != std::string::npos, - "a missing shard is an error that names it"); - } - { - TempDir d; - const auto paths = write_model(d.path, [](int i, auto&, auto& ts, uint64_t&) { - if (i == 3) ts.push_back({"blk.11.ffn_up_exps.weight", {32, 32, 2}, F32, 9}); - }, 8); - const std::string err = error_of(paths); - check(err.find("in two shards") != std::string::npos && err.find(shard_name(3, 4)) != std::string::npos && - err.find(shard_name(4, 4)) != std::string::npos, - "a tensor in two shards is refused, naming both"); - } - { - TempDir d; - const auto paths = write_model(d.path, [](int i, auto& kv, auto&, uint64_t&) { - if (i == 2) kv = fixture::split_keys(1, 4, 7); // says it is shard 2 - }); - check(error_of(paths).find("does not declare itself shard 3 of 4") != std::string::npos, - "a shard whose split.no disagrees with its place is refused"); - } - { - TempDir d; - const auto paths = write_model(d.path, [](int i, auto& kv, auto&, uint64_t&) { - if (i == 3) kv = fixture::split_keys(3, 4, 9); // another model's split.tensors.count - }); - check(!error_of(paths).empty(), "a shard of another model (split.tensors.count differs) is refused"); - } - { - TempDir d; - const auto paths = write_model(d.path, [](int i, auto&, auto& ts, uint64_t&) { - if (i == 3) ts.clear(); // a directory short of split.tensors.count - }); - check(error_of(paths).find("split.tensors.count is 7") != std::string::npos, - "shards that do not add up to split.tensors.count are refused"); - } - { - TempDir d; - const auto paths = write_model(d.path, [](int i, auto& kv, auto&, uint64_t&) { - if (i == 0) kv.erase(kv.begin()); // no general.architecture in shard 1 - }); - check(error_of(paths).find("general.architecture") != std::string::npos, - "a split model whose first shard has no metadata is refused"); - check(error_of({paths[0]}).find("opened as a whole model") != std::string::npos, - "shard 1 of 4 opened as a whole model is refused"); - } - { - TempDir d; - const auto paths = write_model(d.path, [](int i, auto&, auto&, uint64_t& cut) { - if (i == 2) cut = 100; // the last tensor of shard 3 is cut short - }); - bool truncated = false, first_ok = false; - try { - const strata::GgufModel m(paths); - size_t s = 0; - const strata::TensorInfo* q = m.find("blk.12.attn_q.weight", &s); - const strata::TensorInfo* g = m.find("blk.11.ffn_gate_exps.weight"); - truncated = q && !m.in_bounds(*q, s); - first_ok = g && m.in_bounds(*g, 2); - } catch (...) {} - check(truncated && first_ok, "a truncated shard: its last tensor is out of bounds, the others are not"); - } - std::printf(g_fail ? "gguf_split_test: %d FAILED\n" : "gguf_split_test: all passed\n", g_fail); - return g_fail ? 1 : 0; -} diff --git a/tests/core/model_geometry_test.cpp b/tests/core/model_geometry_test.cpp deleted file mode 100644 index 073d04f..0000000 --- a/tests/core/model_geometry_test.cpp +++ /dev/null @@ -1,273 +0,0 @@ -// tests/core/model_geometry_test.cpp - `ModelGeometry` from a model file's own metadata (no model, no GPU). -// -// model_geometry_test the synthetic qwen35moe GGUFs tools/qwen36_synth_gguf.py wrote into -// (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 -#include -#include -#include -#include -#include - -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 | --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; -} diff --git a/tests/core/native_dense_ple_key_test.cpp b/tests/core/native_dense_ple_key_test.cpp deleted file mode 100644 index e69d838..0000000 --- a/tests/core/native_dense_ple_key_test.cpp +++ /dev/null @@ -1,169 +0,0 @@ -// tests/core/native_dense_ple_key_test.cpp - #326: a native pack whose PLE key row is BF16 (iq_pack --compat-bf16 of -// OrcaRouter's IQ3_XXS key) loads with that row in the arena, and NativeDense does not upload the GGUF key over it. -// -// 1. BF16 key row + IQ3_XXS GGUF key: served_names lists the key, keep_unquantized_ple_key takes it out of the -// skip set, the arena holds the BF16 bytes, and NativeDense::load attaches no native key (0.1.25-0.1.31 refused -// the load with "incompatible matrix blk.1.ple_key.weight"). The other matrix still gets its native upload. -// 2. A quantized key row (the Q2_0 / UD-Q4_K_XL packs: a shape-only row) + a Q8_0 GGUF key: unchanged - the key -// stays skipped and is served natively. -// 3. index_code_bits on a missing row and a missing index. -// Synthetic files at small dimensions; needs a CUDA device for the arena (exits 77 without one). -#include "gguf_fixture.hpp" - -#include "strata/core/native_dense.hpp" -#include "strata/core/weights.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace fs = std::filesystem; -using strata::core::NativeDense; -using strata::core::WeightTable; - -namespace { -int g_fail = 0; -void check(bool ok, const std::string& what) { - std::printf(" %-84s %s\n", what.c_str(), ok ? "ok" : "FAIL"); - if (!ok) ++g_fail; -} - -struct TempDir { - fs::path path; - TempDir() { - path = fs::temp_directory_path() / - ("strata-ple-key-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); - } -}; - -const char* KEY = "blk.1.ple_key.weight"; -const char* QKV = "blk.0.attn_qkv.weight"; -constexpr uint64_t NE0 = 256, NE1 = 4; - -std::vector arch_keys() { - return {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)}; -} - -// A shape-only quantized row (what iq_pack writes for a tensor the GGUF serves) and, with `bf16_key`, the key as a -// raw BF16 row (index kind 4) in dense.bin. -void write_pack(const fs::path& dir, bool bf16_key) { - fs::create_directories(dir); - const uint64_t key_bytes = NE0 * NE1 * 2; - std::string idx = "# align 256 pool " + std::to_string(bf16_key ? 2048 + 256 : 256) + " tensors 2\n"; - idx += std::string(QKV) + " 0 0 0 0 0 0 256 4 8 0 32 0 0 0 0 0 0 0\n"; - if (bf16_key) - idx += std::string(KEY) + " 0 4 0 " + std::to_string(key_bytes) + " 256 " + std::to_string(key_bytes) + - " 256 4 0 0 1 0 0 0 0 0 0 0\n"; - else - idx += std::string(KEY) + " 0 0 0 0 256 0 256 4 8 0 32 0 0 0 0 0 0 0\n"; - std::ofstream(dir / "index.txt", std::ios::binary) << idx; - std::vector bytes(bf16_key ? key_bytes : 16); - for (size_t i = 0; i < bytes.size(); ++i) bytes[i] = (char) fixture::pattern(9, i); - std::ofstream(dir / "dense.bin", std::ios::binary).write(bytes.data(), (std::streamsize) bytes.size()); -} - -struct Loaded { - bool ok = false; - std::string err; - std::set skip; - WeightTable wt; - NativeDense dense; - void* arena = nullptr; - ~Loaded() { if (arena) cudaFree(arena); } -}; - -// generate.cpp's order: served_names, keep_unquantized_ple_key (native packs), pool_bytes, load, NativeDense::load. -void load(const fs::path& pack, const std::string& shard, Loaded& l) { - const std::vector shards{shard}; - if (!NativeDense::served_names(shards, true, l.skip, l.err)) return; - if (!NativeDense::keep_unquantized_ple_key(pack.string(), l.skip, l.err)) return; - uint64_t pool = 0; - if (!WeightTable::pool_bytes(pack.string(), pool, l.err, &l.skip)) return; - if (cudaMalloc(&l.arena, pool ? pool : 256) != cudaSuccess) { l.err = "cudaMalloc"; return; } - if (!l.wt.load(pack.string(), l.arena, pool ? pool : 256, l.err, &l.skip)) return; - l.ok = l.dense.load(shards, l.wt, l.err, true); -} -} // namespace - -int main() { - int devices = 0; - if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) { - std::printf("native_dense_ple_key_test: no CUDA device, skipped\n"); - return 77; - } - TempDir tmp; - - std::printf("1. BF16 key row (--compat-bf16), IQ3_XXS GGUF key\n"); - { - const fs::path pack = tmp.path / "orca"; - write_pack(pack, true); - const std::string shard = (tmp.path / "orca.gguf").string(); - fixture::write(shard, arch_keys(), {{QKV, {NE0, NE1}, 8, 1}, {KEY, {NE0, NE1}, 18, 2}}); - int bits = 99; - std::string err; - check(WeightTable::index_code_bits(pack.string(), KEY, bits, err) && bits == 0, "index_code_bits: key row is 0"); - check(WeightTable::index_code_bits(pack.string(), QKV, bits, err) && bits == 8, "index_code_bits: qkv row is 8"); - Loaded l; - load(pack, shard, l); - check(l.ok, "the pack loads (was: incompatible matrix) " + l.err); - check(!l.skip.count(KEY) && l.skip.count(QKV), "the key is not skipped, qkv is"); - const auto* k = l.wt.find(KEY); - check(k && k->resident && k->data && !k->quantized(), "the key is resident and BF16"); - check(k && !k->native_data, "no native key attached"); - if (k && k->data) { - std::vector back(NE0 * NE1 * 2); - cudaMemcpy(back.data(), k->data, back.size(), cudaMemcpyDeviceToHost); - bool same = true; - for (size_t i = 0; i < back.size(); ++i) same = same && back[i] == fixture::pattern(9, i); - check(same, "the arena holds the pack's BF16 bytes"); - } - const auto* q = l.wt.find(QKV); - check(q && q->native_data && q->native_type == 8, "qkv still served natively (Q8_0)"); - check(l.dense.tensor_count() == 1, "one native matrix"); - } - - std::printf("2. quantized key row (Q2_0 / UD-Q4_K_XL packs), Q8_0 GGUF key: unchanged\n"); - { - const fs::path pack = tmp.path / "q8"; - write_pack(pack, false); - const std::string shard = (tmp.path / "q8.gguf").string(); - fixture::write(shard, arch_keys(), {{QKV, {NE0, NE1}, 8, 1}, {KEY, {NE0, NE1}, 8, 2}}); - Loaded l; - load(pack, shard, l); - check(l.ok, "the pack loads " + l.err); - check(l.skip.count(KEY) == 1, "the key stays skipped"); - const auto* k = l.wt.find(KEY); - check(k && !k->resident && k->native_data && k->native_type == 8, "the key is served natively"); - check(l.dense.tensor_count() == 2, "two native matrices"); - } - - std::printf("3. index_code_bits edge cases\n"); - { - int bits = 0; - std::string err; - check(WeightTable::index_code_bits((tmp.path / "orca").string(), "blk.9.nothing.weight", bits, err) && - bits == -1, "a missing row is -1"); - check(!WeightTable::index_code_bits((tmp.path / "none").string(), KEY, bits, err) && !err.empty(), - "a missing index is an error"); - std::set skip{QKV}; - check(NativeDense::keep_unquantized_ple_key((tmp.path / "none").string(), skip, err) && skip.size() == 1, - "no key in the skip set: the index is not read"); - } - - std::printf(g_fail ? "native_dense_ple_key_test: %d FAILED\n" : "native_dense_ple_key_test: all passed\n", g_fail); - return g_fail ? 1 : 0; -} diff --git a/tests/core/pack_load_check.cpp b/tests/core/pack_load_check.cpp deleted file mode 100644 index 1df0dfe..0000000 --- a/tests/core/pack_load_check.cpp +++ /dev/null @@ -1,226 +0,0 @@ -// 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 - -#include -#include -#include -#include -#include -#include -#include -#include - -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(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 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 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> 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; -} diff --git a/tests/core/pool_native_widths_test.cpp b/tests/core/pool_native_widths_test.cpp deleted file mode 100644 index 61187bf..0000000 --- a/tests/core/pool_native_widths_test.cpp +++ /dev/null @@ -1,125 +0,0 @@ -// 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 -#include -#include -#include -#include -#include - -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 nd(0.f, 0.5f); - std::vector> blobs((size_t) E); - std::vector 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 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> x((size_t) T, std::vector((size_t) n_embd)); - std::vector> act((size_t) T, std::vector(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> ref((size_t) R, std::vector((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> ff; - std::vector> 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 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; -} diff --git a/tests/core/vram_plan_test.cpp b/tests/core/vram_plan_test.cpp deleted file mode 100644 index 4166b5e..0000000 --- a/tests/core/vram_plan_test.cpp +++ /dev/null @@ -1,223 +0,0 @@ -// 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 -#include -#include - -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 : 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; -} diff --git a/tests/cuda/prefill_fused_iq_test.cpp b/tests/cuda/prefill_fused_iq_test.cpp deleted file mode 100644 index 17fc0c9..0000000 --- a/tests/cuda/prefill_fused_iq_test.cpp +++ /dev/null @@ -1,642 +0,0 @@ -// prefill_fused_iq_test - #136: the fused int8 expert kernels for the native packs (moe_fused_iq.hpp, STRATA_PF_FUSED=1) -// on random native expert blobs ([gate rows | up rows | down rows], GGUF blocks) and random routing, per format pair, -// against -// - a double-precision reference: the weights dequantized by ggml's own to_float, times the FP32 activations -// (gate/up, SwiGLU, down), and -// - the MMQ path in prefill.cpp's sequence (gather_native into 16-expert groups, q8_1 of the slots' activations, -// gate/up, SwiGLU, q8_1 of H, down). -// Both round the activations and H to int8 per 32 values, differently, so this is not a bitwise test: the fused -// path's error against the reference has to be comparable to MMQ's own (at most 1.5x its RMS and 2x its worst row). -// The pairs cover every format the kernels take: gate/up IQ2_XXS IQ2_XS IQ2_S IQ3_XXS IQ3_S IQ4_XS, down Q2_0 IQ4_NL. -// Part 1 (reference), per pair: 256 tokens over 64 experts, skewed routing - experts with 0 rows, with one, with -// several 64-row tiles - an all-zero token, per-expert blobs at unrelated (2-byte aligned) addresses, three launches of -// different expert ranges. Part 2 (timing): one layer at the engine's chunks (2048, 3584, 8192 tokens; 512 experts, -// top 10) on both paths and on MMQ's products alone (no gathers), for the IQ2_XS, IQ3_XXS and IQ3_S packs' most -// common layers, with the grouping checked and a sample of rows against the reference. --no-ref, --no-timing, -// --only=NAME, --chunks=A,B. Exit 77 without a CUDA device of sm_80 or newer. -#include "strata/prefill/moe_fused_iq.hpp" -#include "strata/prefill/moe_mmq.hpp" - -#include "ggml.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { -namespace mmq = strata::prefill::mmq; -namespace fused = strata::prefill::fused; - -// 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)); -} - -struct Dev { - void* p = nullptr; - explicit Dev(size_t n) { ck(cudaMalloc(&p, n), "cudaMalloc"); } - ~Dev() { cudaFree(p); } - Dev(const Dev&) = delete; - Dev& operator=(const Dev&) = delete; - template T* as() const { return (T*) p; } -}; - -struct Pair { - ggml_type gu, d; - const char* name; -}; - -struct Geo { - size_t gu_row, d_row, up_off, down_off, bytes; - explicit Geo(const Pair& p) { - gu_row = ggml_row_size(p.gu, N); - d_row = ggml_row_size(p.d, FF); - up_off = gu_row * FF; - down_off = 2 * up_off; - bytes = down_off + d_row * N; - } - 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.n_embd = N; g.n_ff = FF; - return g; - } -}; - -// random blocks with a sane fp16 scale `d` at each block's start (every format here begins with it): scales chosen so -// that the weights' typical size is that of a 2-3 bit expert (a few hundredths) -void fill_matrix(uint8_t* m, ggml_type t, int64_t rows, int64_t cols, std::mt19937& rng) { - const size_t bs = ggml_type_size(t), nb = (size_t) rows * (size_t) (cols / ggml_blck_size(t)); - std::uniform_int_distribution byte(0, 255); - const float lo = t == GGML_TYPE_IQ3_S ? 0.0004f : t == GGML_TYPE_IQ4_XS ? 0.00005f - : t == GGML_TYPE_IQ4_NL ? 0.0002f : t == GGML_TYPE_Q2_0 ? 0.004f : 0.0008f; - std::uniform_real_distribution sc(lo, 6.0f * lo); - for (size_t i = 0; i < nb * bs; ++i) m[i] = (uint8_t) byte(rng); - for (size_t b = 0; b < nb; ++b) { - const ggml_fp16_t h = ggml_fp32_to_fp16(sc(rng)); - std::memcpy(m + b * bs, &h, 2); - } -} -std::vector make_blob(const Pair& p, const Geo& g, std::mt19937& rng) { - std::vector b(g.bytes); - fill_matrix(b.data(), p.gu, 2 * FF, N, rng); - fill_matrix(b.data() + g.down_off, p.d, N, FF, rng); - return b; -} - -// ggml's dequantized weights: gate [640][2560], up [640][2560], down [2560][640] -void dequant(const Pair& p, const Geo& g, const std::vector& b, std::vector& gu, std::vector& dn) { - const auto* tg = ggml_get_type_traits(p.gu); - const auto* td = ggml_get_type_traits(p.d); - gu.resize((size_t) 2 * FF * N); - dn.resize((size_t) N * FF); - for (int r = 0; r < 2 * FF; ++r) tg->to_float(b.data() + (size_t) r * g.gu_row, gu.data() + (size_t) r * N, N); - for (int r = 0; r < N; ++r) td->to_float(b.data() + g.down_off + (size_t) r * g.d_row, dn.data() + (size_t) r * FF, FF); -} - -// activations: N(0, 1) with a few large values (the hidden state has outliers); token `zero` all zero -std::vector make_x(int T, std::mt19937& rng, int zero) { - std::vector x((size_t) T * N); - std::normal_distribution nd(0.0f, 1.0f); - std::uniform_int_distribution pick(0, 199); - for (float& v : x) v = nd(rng) * (pick(rng) == 0 ? 12.0f : 1.0f); - if (zero >= 0) std::fill(x.begin() + (size_t) zero * N, x.begin() + (size_t) (zero + 1) * N, 0.0f); - return x; -} - -// K distinct experts per token; `hot` > 0 skews the first choices towards the lowest ids -std::vector make_ids(int T, int E, std::mt19937& rng, int hot, int unused) { - std::vector ids((size_t) T * K); - std::uniform_int_distribution any(0, E - 1 - unused); - for (int t = 0; t < T; ++t) - for (int k = 0; k < K; ++k) { - int e; - bool dup; - do { - e = (hot > 0 && k < 3 && (int) (rng() % 4) != 0) ? (int) (rng() % (unsigned) hot) : any(rng); - dup = false; - for (int j = 0; j < k; ++j) dup |= ids[(size_t) t * K + j] == e; - } while (dup); - ids[(size_t) t * K + k] = e; - } - return ids; -} - -struct Routing { - std::vector cnt, off, src; // per expert; sorted row -> token (rows in pair order within an expert) - std::vector row_of; // pair -> sorted row -}; -Routing sort_rows(const std::vector& ids, int E) { - Routing r; - r.cnt.assign((size_t) E, 0); - for (int32_t e : ids) ++r.cnt[(size_t) e]; - r.off.assign((size_t) E + 1, 0); - for (int e = 0; e < E; ++e) r.off[(size_t) e + 1] = r.off[(size_t) e] + r.cnt[(size_t) e]; - std::vector fill(r.off.begin(), r.off.end() - 1); - r.src.resize(ids.size()); - r.row_of.resize(ids.size()); - for (size_t i = 0; i < ids.size(); ++i) { - const int32_t p = fill[(size_t) ids[i]]++; - r.row_of[i] = p; - r.src[(size_t) p] = (int32_t) (i / K); - } - return r; -} - -// MMQ, as prefill.cpp runs a native layer: per group of 16 routed experts a gather, gate/up, SwiGLU (gate rows, then -// up rows), q8_1 of H, down. Returns Dm [rows][N] in sorted-row order. -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 * 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, 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 -// with rows: the timing part's layout), the cost of MMQ's own kernels alone -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& blob, int64_t rows, cudaStream_t s, - bool direct = false, size_t stride = 0) { - 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 order; - for (int e = 0; e < E; ++e) if (r.cnt[(size_t) e] > 0) order.push_back(e); - const size_t n = order.size(), ng = (n + GROUP - 1) / GROUP; - std::vector bh(n + 1 + ng * (GROUP + 1)); - for (size_t j = 0; j < n; ++j) bh[j] = r.off[(size_t) order[j]]; - bh[n] = (int32_t) rows; - for (size_t g = 0; g < ng; ++g) - for (size_t i = 0; i <= GROUP; ++i) - bh[n + 1 + g * (GROUP + 1) + i] = bh[std::min(n, g * GROUP + i)] - bh[g * GROUP]; - ck(cudaMemcpyAsync(b.bounds.p, bh.data(), bh.size() * 4, cudaMemcpyHostToDevice, s), "bounds"); - mmq::iota(b.ident.as(), rows, s); - mmq::quantize(x_dev, src_dev, b.xq.p, (int) p.gu, N, N, rows, s); - for (size_t j = 0; j < n; ++j) { - const size_t q = j % GROUP; - const uint8_t* bl = blob[(size_t) order[j]]; - if (!direct) - mmq::gather_native(bl, bl + geo.up_off, gub / 2, bl + geo.down_off, db, b.grp_gu.as() + q * gub, - b.grp_d.as() + q * db, s); - if (q + 1 < GROUP && j + 1 < n) continue; - const size_t j0 = j - q, g = j0 / GROUP; - const int ngx = (int) (q + 1); - const int64_t r0 = bh[j0], nr = bh[j + 1] - r0; - int64_t maxr = 0; - for (size_t i = j0; i <= j; ++i) maxr = std::max(maxr, r.cnt[(size_t) order[i]]); - if (!direct) { - ck(cudaMemsetAsync(b.grp_gu.as() + (size_t) ngx * gub, 0, 4096, s), "tail"); - ck(cudaMemsetAsync(b.grp_d.as() + (size_t) ngx * db, 0, 4096, s), "tail"); - } - 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 = 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() + j0; gu.ids = b.ident.as(); - gu.total_rows = rows; gu.max_rows = maxr; gu.dst = b.gu.as(); gu.ld_dst = 2 * FF; - ctx.run(gu, s); - mmq::swiglu(b.gu.as() + r0 * 2 * FF, b.h.as() + r0 * FF, nr, FF, false, s); - mmq::quantize(b.h.as() + 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; - dn.expert_bytes = direct ? stride : db; - dn.n = ngx; dn.xq = b.hq.p; dn.bounds = b.bounds.as() + n + 1 + g * (GROUP + 1); - dn.ids = b.ident.as(); dn.total_rows = nr; dn.max_rows = maxr; dn.dst = b.dm.as() + r0 * N; - dn.ld_dst = N; - ctx.run(dn, s); - } -} - -// the fused path: quantize, group on the device, then launches over expert ranges `cuts` (e.g. {0, 20, 64}) -struct FusedBufs { - Dev xa, ha, dm, scratch, slot, src, ids; - FusedBufs(int T, int64_t rows, int E) - : xa(fused::act_bytes(T, N)), ha(fused::act_bytes(rows, FF)), dm((size_t) rows * N * 4), - scratch(fused::group_bytes(rows, E)), slot((size_t) rows * 4), src((size_t) rows * 4), - ids((size_t) rows * 4) {} -}; -void run_fused(const Pair& p, const Geo& geo, FusedBufs& b, const float* x_dev, int T, int E, - const std::vector& cuts, const std::vector& blob, cudaStream_t s) { - const int64_t rows = (int64_t) T * K; - const fused::NativeGeom ng = geo.native(p); - fused::quantize_act_native(x_dev, T, N, b.xa.p, s); - fused::group(b.ids.as(), rows, K, E, b.scratch.p, b.slot.as(), b.src.as(), s); - for (size_t c = 0; c + 1 < cuts.size(); ++c) { - for (int e0 = cuts[c]; e0 < cuts[c + 1]; e0 += fused::kMaxBatch) { - fused::Batch bt; - bt.e0 = e0; - bt.e1 = std::min(cuts[c + 1], e0 + fused::kMaxBatch); - for (int e = bt.e0; e < bt.e1; ++e) bt.blob[e - bt.e0] = blob[(size_t) e]; - fused::experts_native(bt, ng, E, rows, b.scratch.p, b.xa.p, b.src.as(), b.ha.p, b.dm.as(), s); - } - } -} - -struct Err { - double rms = 0, worst = 0; // RMS error / RMS of the reference; the worst row's max |error| / its max |ref| -}; -// y_a[row_a(i)] against y_b[row_b(i)] for every pair i (rows of N values) -template -Err compare(const std::vector& a, RA row_a, const std::vector& b, RB row_b, size_t pairs) { - double e2 = 0, r2 = 0; - Err out; - for (size_t i = 0; i < pairs; ++i) { - const float* ya = a.data() + (size_t) row_a(i) * N; - const float* yb = b.data() + (size_t) row_b(i) * N; - double me = 0, mr = 0; - for (int o = 0; o < N; ++o) { - if (!std::isfinite(ya[o])) throw std::runtime_error("a non-finite output"); - const double d = (double) ya[o] - yb[o]; - e2 += d * d; - r2 += (double) yb[o] * yb[o]; - me = std::max(me, std::fabs(d)); - mr = std::max(mr, (double) std::fabs(yb[o])); - } - if (mr > 0) out.worst = std::max(out.worst, me / mr); - else if (me > 0) out.worst = 1e30; // a zero row must stay exactly zero - } - out.rms = r2 > 0 ? std::sqrt(e2 / r2) : 0; - return out; -} - -std::vector download(const Dev& d, size_t n) { - std::vector h(n); - ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download"); - return h; -} -std::vector download_i(const Dev& d, size_t n) { - std::vector h(n); - ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download"); - return h; -} - -// part 1: against the double-precision reference -void reference_part(const Pair& p, cudaStream_t s) { - constexpr int T = 256, E = 64, ZERO = 77; - const Geo geo(p); - std::mt19937 rng(136 + (unsigned) p.gu * 7 + (unsigned) p.d); - std::vector> host((size_t) E); - std::vector> dev; - std::vector blob((size_t) E); - for (int e = 0; e < E; ++e) { - host[(size_t) e] = make_blob(p, geo, rng); - dev.push_back(std::make_unique(geo.bytes + 4096 * (size_t) (e % 3) + 64)); // unrelated addresses - uint8_t* q = dev.back()->as() + 256 * (size_t) (e % 3) + 2 * (size_t) (e % 2); // 2-byte aligned - ck(cudaMemcpy(q, host[(size_t) e].data(), geo.bytes, cudaMemcpyHostToDevice), "blob"); - blob[(size_t) e] = q; - } - const std::vector x = make_x(T, rng, ZERO); - const std::vector ids = make_ids(T, E, rng, 2, 4); // experts 0, 1 hot (several tiles), 60-63 unused - const int64_t rows = (int64_t) T * K; - const Routing r = sort_rows(ids, E); - std::printf("%s - reference part: %d tokens, %d experts, rows per expert: max %d, experts without rows %d\n", p.name, - T, E, *std::max_element(r.cnt.begin(), r.cnt.end()), (int) std::count(r.cnt.begin(), r.cnt.end(), 0)); - - Dev x_dev(x.size() * 4), src_dev((size_t) rows * 4); - ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); - ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src"); - // (the uploads above are on the legacy stream and the work below on a non-blocking one: a cudaMemcpy from pageable - // memory may return before its DMA lands - on Windows it can wait in the queue until the next synchronous call) - ck(cudaDeviceSynchronize(), "uploads"); - mmq::Context ctx; - MmqBufs mb(p, rows, E); - run_mmq(p, geo, ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s); - FusedBufs fb(T, rows, E); - ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids"); - ck(cudaMemset(fb.dm.p, 0xff, (size_t) rows * N * 4), "sentinel"); // an unwritten row is NaN - ck(cudaDeviceSynchronize(), "uploads"); - run_fused(p, geo, fb, x_dev.as(), T, E, {0, 1, 20, E}, blob, s); - ck(cudaStreamSynchronize(s), "sync"); - const std::vector y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N); - const std::vector slot = download_i(fb.slot, (size_t) rows), fsrc = download_i(fb.src, (size_t) rows); - for (int64_t i = 0; i < rows; ++i) - if (fsrc[(size_t) slot[(size_t) i]] != (int32_t) (i / K)) throw std::runtime_error("group: slot/src disagree"); - - // the reference, an expert at a time on all cores - std::vector ref((size_t) rows * N); - std::vector th; - const int nth = std::max(1, std::min(16, (int) std::thread::hardware_concurrency())); - for (int w = 0; w < nth; ++w) - th.emplace_back([&, w] { - std::vector gu, dn, h(FF); - for (int e = w; e < E; e += nth) { - if (r.cnt[(size_t) e] == 0) continue; - dequant(p, geo, host[(size_t) e], gu, dn); - for (int64_t i = 0; i < rows; ++i) { - if (ids[(size_t) i] != e) continue; - const float* xr = x.data() + (size_t) (i / K) * N; - for (int f = 0; f < FF; ++f) { - double gt = 0, up = 0; - const float *wg = gu.data() + (size_t) f * N, *wu = gu.data() + (size_t) (FF + f) * N; - for (int k = 0; k < N; ++k) { gt += (double) wg[k] * xr[k]; up += (double) wu[k] * xr[k]; } - h[(size_t) f] = (float) (gt / (1.0 + std::exp(-gt)) * up); - } - for (int o = 0; o < N; ++o) { - double a = 0; - const float* wd = dn.data() + (size_t) o * FF; - for (int f = 0; f < FF; ++f) a += (double) wd[f] * h[(size_t) f]; - ref[(size_t) i * N + o] = (float) a; - } - } - } - }); - for (auto& t : th) t.join(); - - auto pair = [](size_t i) { return (int64_t) i; }; - auto mrow = [&](size_t i) { return (int64_t) r.row_of[i]; }; - auto frow = [&](size_t i) { return (int64_t) slot[i]; }; - const Err em = compare(y_mmq, mrow, ref, pair, (size_t) rows); - const Err ef = compare(y_f, frow, ref, pair, (size_t) rows); - const Err efm = compare(y_f, frow, y_mmq, mrow, (size_t) rows); - std::printf(" MMQ vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n", em.rms, em.worst); - std::printf(" fused vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n", ef.rms, ef.worst); - std::printf(" fused vs MMQ : rel RMS %.3e worst row max rel %.3e\n", efm.rms, efm.worst); - double zmax = 0; - for (int k = 0; k < K; ++k) - for (int o = 0; o < N; ++o) - zmax = std::max(zmax, (double) std::fabs(y_f[(size_t) slot[(size_t) (ZERO * K + k)] * N + o])); - if (zmax != 0) throw std::runtime_error(std::string(p.name) + ": the all-zero token's outputs are not zero"); - if (ef.rms > 1.5 * em.rms || ef.worst > 2.0 * em.worst) - throw std::runtime_error(std::string(p.name) + ": the fused path's error is not comparable to MMQ's"); -} - -// part 2: one layer at a real chunk, timed -void timing_part(const Pair& p, int T, cudaStream_t s) { - constexpr int E = 512; - const Geo geo(p); - std::mt19937 rng(1360); - const int64_t rows = (int64_t) T * K; - // 512 distinct blobs - the products read each once per tile, as the engine does - // at a stride of whole blocks of both formats (MMQ's expert stride counts blocks), + MMQ's read past the end - size_t unit = ggml_type_size(p.gu); - while (unit % ggml_type_size(p.d) != 0 || unit % 16 != 0) unit += ggml_type_size(p.gu); - const size_t stride = (geo.bytes + unit - 1) / unit * unit; - Dev blobs((size_t) E * stride + 4096); - ck(cudaMemset(blobs.p, 0, (size_t) E * stride + 4096), "zero"); - { - std::vector b = make_blob(p, geo, rng); - for (int e = 0; e < E; ++e) { - b[4 + (size_t) (e % 16)] ^= (uint8_t) e; // not all equal (inside the first block, not its scale) - ck(cudaMemcpy(blobs.as() + (size_t) e * stride, b.data(), geo.bytes, cudaMemcpyHostToDevice), - "blob"); - } - } - std::vector blob((size_t) E); - for (int e = 0; e < E; ++e) blob[(size_t) e] = blobs.as() + (size_t) e * stride; - const std::vector x = make_x(T, rng, -1); - const std::vector ids = make_ids(T, E, rng, 0, 0); - const Routing r = sort_rows(ids, E); - Dev x_dev(x.size() * 4), src_dev((size_t) rows * 4); - ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); - ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src"); - mmq::Context ctx; - MmqBufs mb(p, rows, E); - FusedBufs fb(T, rows, E); - ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids"); - ck(cudaDeviceSynchronize(), "uploads"); // (see reference_part) - cudaEvent_t a, b; - ck(cudaEventCreate(&a), "event"); - ck(cudaEventCreate(&b), "event"); - auto once = [&](auto&& f) { - ck(cudaEventRecord(a, s), "record"); - f(); - ck(cudaEventRecord(b, s), "record"); - ck(cudaEventSynchronize(b), "sync"); - float t = 0; - ck(cudaEventElapsedTime(&t, a, b), "elapsed"); - return t; - }; - auto mmq_run = [&] { run_mmq(p, geo, ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s); }; - auto fused_run = [&] { run_fused(p, geo, fb, x_dev.as(), T, E, {0, E}, blob, s); }; - const bool all_routed = std::count(r.cnt.begin(), r.cnt.end(), 0) == 0; - auto direct_run = [&] { - run_mmq(p, geo, ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s, true, stride); - }; - if (std::getenv("S20_IDSDIAG")) { // which step overwrites the routing ids on the device - auto check = [&](const char* after) { - ck(cudaStreamSynchronize(s), "sync"); - const std::vector d = download_i(fb.ids, (size_t) rows); - int64_t bad = 0; - for (size_t i = 0; i < (size_t) rows; ++i) bad += d[i] != ids[i]; - std::printf(" ids on the device after %s: %lld of %lld differ (fb.ids %p, mb.dm %p..%p, fb.dm %p..%p)\n", - after, (long long) bad, (long long) rows, fb.ids.p, mb.dm.p, - (void*) (mb.dm.as() + (size_t) rows * N * 4), fb.dm.p, - (void*) (fb.dm.as() + (size_t) rows * N * 4)); - }; - check("the upload"); - mmq_run(); - check("an MMQ run"); - fused_run(); - check("a fused run"); - if (all_routed) { - direct_run(); - check("an MMQ run without gathers"); - } - } - // ~1 s of both first (the clocks ramp up), then alternating rounds; the medians - const bool no_mmq = std::getenv("S20_NOMMQ") != nullptr; // (debug: the fused runs alone) - for (float spent = 0; spent < 1000.0f;) spent += (no_mmq ? 0.0f : once(mmq_run)) + once(fused_run); - std::vector tm, tf, td; - for (int rep = 0; rep < 8; ++rep) { - tm.push_back(no_mmq ? 1.0f : once(mmq_run)); - tf.push_back(once(fused_run)); - if (all_routed && !no_mmq) td.push_back(once(direct_run)); - } - if (td.empty()) td.push_back(0.0f); - std::sort(tm.begin(), tm.end()); - std::sort(tf.begin(), tf.end()); - std::sort(td.begin(), td.end()); - const float t_mmq = tm[tm.size() / 2], t_f = tf[tf.size() / 2]; - if (all_routed) - std::printf(" (MMQ's products alone, no gathers: %.3f ms - fused %.2fx)\n", td[td.size() / 2], - td[td.size() / 2] / t_f); - std::vector tf2; // back to back - for (int rep = 0; rep < 8; ++rep) tf2.push_back(once(fused_run)); - std::sort(tf2.begin(), tf2.end()); - std::printf(" (fused back to back: median %.3f ms, min %.3f; alternating min %.3f; MMQ min %.3f)\n", tf2[4], - tf2[0], tf[0], tm[0]); - const std::vector y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N); - const std::vector slot = download_i(fb.slot, (size_t) rows); - const Err efm = compare(y_f, [&](size_t i) { return (int64_t) slot[i]; }, y_mmq, - [&](size_t i) { return (int64_t) r.row_of[i]; }, (size_t) rows); - std::printf("%s - timing part: %d tokens x top %d over %d experts, one layer: MMQ path %.3f ms, fused %.3f ms " - "(%.2fx); fused vs MMQ rel RMS %.3e worst row %.3e\n", - p.name, T, K, E, t_mmq, t_f, t_mmq / t_f, efm.rms, efm.worst); - { // the grouping: every pair in its expert's rows (the near-identical blobs here would hide a wrong expert) - const std::vector fsrc = download_i(fb.src, (size_t) rows); - int64_t bad = 0, bad_src = 0; - for (size_t i = 0; i < (size_t) rows; ++i) { - const int e = ids[i]; - bad += slot[i] < r.off[(size_t) e] || slot[i] >= r.off[(size_t) e + 1]; - bad_src += fsrc[(size_t) slot[i]] != (int32_t) (i / K); - } - if (bad || bad_src) { - std::vector tbl((size_t) 4 * E + 2); - ck(cudaMemcpy(tbl.data(), fb.scratch.p, tbl.size() * 4, cudaMemcpyDeviceToHost), "tables"); - int64_t bad_cnt = 0, bad_off = 0, bad_ids = 0; - const std::vector d_ids = download_i(fb.ids, (size_t) rows); - for (size_t i = 0; i < (size_t) rows; ++i) bad_ids += d_ids[i] != ids[i]; - std::printf(" the routing ids on the device: %lld of %lld differ (first %d %d %d)\n", (long long) bad_ids, - (long long) rows, d_ids[0], d_ids[1], d_ids[2]); - const int32_t smin = *std::min_element(slot.begin(), slot.end()), smax = *std::max_element(slot.begin(), slot.end()); - std::printf(" slots %d..%d; off[0..3] %d %d %d %d off[E] %d; fill[0..3] %d %d %d %d; ts[0..3] %d %d %d %d " - "ts[E] %d\n", smin, smax, tbl[E], tbl[E + 1], tbl[E + 2], tbl[E + 3], tbl[2 * E], tbl[2 * E + 1], - tbl[2 * E + 2], tbl[2 * E + 3], tbl[2 * E + 4], tbl[3 * E + 1], tbl[3 * E + 2], tbl[3 * E + 3], - tbl[3 * E + 4], tbl[4 * E + 1]); - // the group again on these ids, synchronously - fused::group(fb.ids.as(), rows, K, E, fb.scratch.p, fb.slot.as(), fb.src.as(), s); - ck(cudaStreamSynchronize(s), "sync"); - std::vector t2((size_t) 4 * E + 2); - ck(cudaMemcpy(t2.data(), fb.scratch.p, t2.size() * 4, cudaMemcpyDeviceToHost), "tables"); - std::printf(" group() again, synchronized: cnt[0..3] %d %d %d %d off[E] %d\n", t2[0], t2[1], t2[2], t2[3], - t2[(size_t) 2 * E]); - for (int e = 0; e < E; ++e) { - bad_cnt += tbl[(size_t) e] != r.cnt[(size_t) e]; - bad_off += tbl[(size_t) E + e] != r.off[(size_t) e]; - } - std::printf(" GROUPING WRONG: %lld pairs outside their expert's rows, %lld src mismatches; tables: %lld counts " - "and %lld offsets differ from the host's (cnt[0..3] %d %d %d %d vs %d %d %d %d)\n", - (long long) bad, (long long) bad_src, (long long) bad_cnt, (long long) bad_off, tbl[0], tbl[1], - tbl[2], tbl[3], r.cnt[0], r.cnt[1], r.cnt[2], r.cnt[3]); - throw std::runtime_error(std::string(p.name) + ": the grouping is wrong"); - } - } - if (std::getenv("S20_ROWDIAG")) { // the pairs whose rows differ most: expert, its rows, the row's place - const std::vector fsrc = download_i(fb.src, (size_t) rows); - std::vector> worst; - for (size_t i = 0; i < (size_t) rows; ++i) { - const float* a = y_f.data() + (size_t) slot[i] * N; - const float* m = y_mmq.data() + (size_t) r.row_of[i] * N; - double me = 0, mr = 0; - for (int o = 0; o < N; ++o) { me = std::max(me, (double) std::fabs(a[o] - m[o])); mr = std::max(mr, (double) std::fabs(m[o])); } - worst.push_back({mr > 0 ? me / mr : me, i}); - } - std::sort(worst.rbegin(), worst.rend()); - for (int k = 0; k < 12; ++k) { - const size_t i = worst[(size_t) k].second; - const int e = ids[i]; - // the expert's rows start at its first fused row: the smallest slot of its pairs - int32_t first = INT32_MAX; - for (size_t j = 0; j < (size_t) rows; ++j) if (ids[j] == e) first = std::min(first, slot[j]); - std::printf(" pair %zu token %zu expert %d (%d rows) fused row %d (+%d in the expert) max rel %.3e\n", i, - i / K, e, r.cnt[(size_t) e], slot[i], slot[i] - first, worst[(size_t) k].first); - } - (void) fsrc; - } - // both against the double-precision reference on a sample of 96 pairs - { - std::vector pick; - for (size_t i = 0; i < 96; ++i) pick.push_back((i * 2654435761u) % (size_t) rows); - std::vector ref(pick.size() * N), ym(pick.size() * N), yf(pick.size() * N); - std::vector hb(geo.bytes); - std::vector gu, dn, h(FF); - for (size_t j = 0; j < pick.size(); ++j) { - const size_t i = pick[j]; - const int e = ids[i]; - ck(cudaMemcpy(hb.data(), blob[(size_t) e], geo.bytes, cudaMemcpyDeviceToHost), "blob back"); - dequant(p, geo, hb, gu, dn); - const float* xr = x.data() + (i / K) * N; - for (int f = 0; f < FF; ++f) { - double gt = 0, up = 0; - const float *wg = gu.data() + (size_t) f * N, *wu = gu.data() + (size_t) (FF + f) * N; - for (int k = 0; k < N; ++k) { gt += (double) wg[k] * xr[k]; up += (double) wu[k] * xr[k]; } - h[(size_t) f] = (float) (gt / (1.0 + std::exp(-gt)) * up); - } - for (int o = 0; o < N; ++o) { - double a = 0; - const float* wd = dn.data() + (size_t) o * FF; - for (int f = 0; f < FF; ++f) a += (double) wd[f] * h[(size_t) f]; - ref[j * N + o] = (float) a; - } - std::copy_n(y_mmq.begin() + (ptrdiff_t) ((size_t) r.row_of[i] * N), N, ym.begin() + (ptrdiff_t) (j * N)); - std::copy_n(y_f.begin() + (ptrdiff_t) ((size_t) slot[i] * N), N, yf.begin() + (ptrdiff_t) (j * N)); - } - auto id = [](size_t j) { return (int64_t) j; }; - const Err em = compare(ym, id, ref, id, pick.size()), ef = compare(yf, id, ref, id, pick.size()); - std::printf(" sample of %zu pairs vs FP32 reference: MMQ rel RMS %.3e worst %.3e, fused rel RMS %.3e worst " - "%.3e\n", pick.size(), em.rms, em.worst, ef.rms, ef.worst); - if (ef.rms > 1.5 * em.rms || ef.worst > 2.0 * em.worst) - throw std::runtime_error(std::string(p.name) + ": the fused path's error is not comparable to MMQ's (timing)"); - } - cudaEventDestroy(a); - cudaEventDestroy(b); - if (efm.rms > 0.05) throw std::runtime_error(std::string(p.name) + ": the paths disagree at the real shape"); -} -} // namespace - -int main(int argc, char** argv) { - try { -#ifdef _WIN32 - _putenv_s("STRATA_PF_FUSED", "1"); -#else - setenv("STRATA_PF_FUSED", "1", 1); -#endif - int n = 0; - if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { std::printf("no CUDA device: skipped\n"); return 77; } - if (!fused::available()) { std::printf("the fused kernels need sm_80 or newer: skipped\n"); return 77; } - if (!mmq::built()) { std::printf("no MMQ in this build\n"); return 1; } - const std::vector pairs = { - {GGML_TYPE_IQ2_S, GGML_TYPE_Q2_0, "IQ2_S / Q2_0"}, {GGML_TYPE_IQ2_XXS, GGML_TYPE_Q2_0, "IQ2_XXS / Q2_0"}, - {GGML_TYPE_IQ2_XS, GGML_TYPE_IQ4_NL, "IQ2_XS / IQ4_NL"}, {GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ4_NL, "IQ3_XXS / IQ4_NL"}, - {GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL, "IQ3_S / IQ4_NL"}, {GGML_TYPE_IQ4_XS, GGML_TYPE_Q2_0, "IQ4_XS / Q2_0"}}; - const char* only = nullptr; // --only=NAME: the pairs whose name contains NAME - for (int i = 1; i < argc; ++i) - if (std::strncmp(argv[i], "--only=", 7) == 0) only = argv[i] + 7; - bool timing = true, ref = true; // --no-timing, --no-ref: skip a part - std::vector chunks = {2048, 3584, 8192}; // --chunks=A,B: the timing part's chunk sizes - for (int i = 1; i < argc; ++i) { - if (std::strcmp(argv[i], "--no-timing") == 0) timing = false; - if (std::strcmp(argv[i], "--no-ref") == 0) ref = false; - if (std::strncmp(argv[i], "--chunks=", 9) == 0) { - chunks.clear(); - for (const char* c = argv[i] + 9; *c;) { - chunks.push_back(std::atoi(c)); - while (*c && *c != ',') ++c; - if (*c == ',') ++c; - } - } - } - cudaStream_t s = nullptr; - ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream"); - 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]}) { - if (only && std::string(p.name).find(only) == std::string::npos) continue; - for (int T : chunks) timing_part(p, T, s); - } - } - ck(cudaStreamDestroy(s), "destroy"); - std::printf("prefill fused MoE (native formats) parity passed\n"); - return 0; - } catch (const std::exception& e) { - std::fprintf(stderr, "prefill fused MoE (native formats) parity failed: %s\n", e.what()); - return 1; - } -} diff --git a/tests/cuda/prefill_fused_moe_test.cpp b/tests/cuda/prefill_fused_moe_test.cpp deleted file mode 100644 index 991b663..0000000 --- a/tests/cuda/prefill_fused_moe_test.cpp +++ /dev/null @@ -1,420 +0,0 @@ -// prefill_fused_moe_test - #136: the fused int8 expert kernels of the prompt path (moe_fused.hpp, STRATA_PF_FUSED=1) -// on random Strata Q2_0 expert blobs and random routing, against -// - a double-precision reference: the dequantized weights times the FP32 activations (gate/up, SwiGLU, down), and -// - the MMQ path in prefill.cpp's sequence (gather_strata_q2 into 16-expert groups, q8_1 of the slots' activations, -// gate/up, SwiGLU, q8_1 of H, down). -// Both round the activations and H to int8 per 32 values, differently, so this is not a bitwise test: the fused -// path's error against the reference has to be comparable to MMQ's own (at most 1.5x its RMS and 2x its worst row). -// Part 1 (reference): 256 tokens over 64 experts, skewed routing - experts with 0 rows, with one, with several 64-row -// tiles - an all-zero token, per-expert blobs at unrelated addresses, three launches of different expert ranges. -// Part 2 (timing): one layer at a real chunk (2048 tokens, 512 experts, top 10) on both paths, with their agreement. -// Exit 77 without a CUDA device of sm_80 or newer. -#include "strata/prefill/moe_fused.hpp" -#include "strata/prefill/moe_mmq.hpp" - -#include "ggml.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { -namespace mmq = strata::prefill::mmq; -namespace fused = strata::prefill::fused; - -constexpr int N = 2560, FF = 640, K = 10, GROUP = 16, Q2 = 42; // GGML_TYPE_Q2_0 -constexpr size_t BLOB = 1382400, O_D_CODES = (size_t) 1280 * 640, O_GU_SC = O_D_CODES + (size_t) 2560 * 160, - O_D_SC = O_GU_SC + (size_t) 1280 * 40 * 2; - -void ck(cudaError_t e, const char* what) { - if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e)); -} - -struct Dev { - void* p = nullptr; - explicit Dev(size_t n) { ck(cudaMalloc(&p, n), "cudaMalloc"); } - ~Dev() { cudaFree(p); } - Dev(const Dev&) = delete; - Dev& operator=(const Dev&) = delete; - template T* as() const { return (T*) p; } -}; - -// a Strata Q2_0 blob: random codes, scales in [0.004, 0.03] (a 2-bit expert's range) -std::vector make_blob(std::mt19937& rng) { - std::vector b(BLOB); - std::uniform_int_distribution byte(0, 255); - std::uniform_real_distribution sc(0.004f, 0.03f); - for (size_t i = 0; i < O_GU_SC; ++i) b[i] = (uint8_t) byte(rng); - for (size_t i = O_GU_SC; i < BLOB; i += 2) { - const ggml_fp16_t h = ggml_fp32_to_fp16(sc(rng)); - std::memcpy(&b[i], &h, 2); - } - return b; -} - -// the blob's weights as floats: gate/up [1280][2560] (interleaved rows), down [2560][640] -void dequant(const std::vector& b, std::vector& gu, std::vector& dn) { - auto row = [&](size_t codes, size_t ld, size_t scales, int nb, int r, float* out) { - for (int k = 0; k < nb * 64; ++k) { - ggml_fp16_t h; - std::memcpy(&h, &b[scales + ((size_t) r * nb + k / 64) * 2], 2); - const int q = (b[codes + (size_t) r * ld + k / 4] >> (2 * (k % 4))) & 3; - out[k] = ggml_fp16_to_fp32(h) * (float) (q - 1); - } - }; - gu.resize((size_t) 1280 * N); - dn.resize((size_t) N * FF); - for (int r = 0; r < 1280; ++r) row(0, 640, O_GU_SC, 40, r, gu.data() + (size_t) r * N); - for (int r = 0; r < N; ++r) row(O_D_CODES, 160, O_D_SC, 10, r, dn.data() + (size_t) r * FF); -} - -// activations: N(0, 1) with a few large values (the hidden state has outliers); token `zero` all zero -std::vector make_x(int T, std::mt19937& rng, int zero) { - std::vector x((size_t) T * N); - std::normal_distribution nd(0.0f, 1.0f); - std::uniform_int_distribution pick(0, 199); - for (float& v : x) v = nd(rng) * (pick(rng) == 0 ? 12.0f : 1.0f); - if (zero >= 0) std::fill(x.begin() + (size_t) zero * N, x.begin() + (size_t) (zero + 1) * N, 0.0f); - return x; -} - -// K distinct experts per token; `hot` > 0 skews the first choices towards the lowest ids -std::vector make_ids(int T, int E, std::mt19937& rng, int hot, int unused) { - std::vector ids((size_t) T * K); - std::uniform_int_distribution any(0, E - 1 - unused); - for (int t = 0; t < T; ++t) - for (int k = 0; k < K; ++k) { - int e; - bool dup; - do { - e = (hot > 0 && k < 3 && (int) (rng() % 4) != 0) ? (int) (rng() % (unsigned) hot) : any(rng); - dup = false; - for (int j = 0; j < k; ++j) dup |= ids[(size_t) t * K + j] == e; - } while (dup); - ids[(size_t) t * K + k] = e; - } - return ids; -} - -struct Routing { - std::vector cnt, off, src; // per expert; sorted row -> token (rows in pair order within an expert) - std::vector row_of; // pair -> sorted row -}; -Routing sort_rows(const std::vector& ids, int E) { - Routing r; - r.cnt.assign((size_t) E, 0); - for (int32_t e : ids) ++r.cnt[(size_t) e]; - r.off.assign((size_t) E + 1, 0); - for (int e = 0; e < E; ++e) r.off[(size_t) e + 1] = r.off[(size_t) e] + r.cnt[(size_t) e]; - std::vector fill(r.off.begin(), r.off.end() - 1); - r.src.resize(ids.size()); - r.row_of.resize(ids.size()); - for (size_t i = 0; i < ids.size(); ++i) { - const int32_t p = fill[(size_t) ids[i]]++; - r.row_of[i] = p; - r.src[(size_t) p] = (int32_t) (i / K); - } - return r; -} - -// MMQ, as prefill.cpp runs it: per group of 16 routed experts a gather, gate/up, SwiGLU, q8_1 of H, down. Returns -// Dm [rows][N] in sorted-row order. -struct MmqBufs { - Dev xq, gu, h, hq, dm, ident, bounds, grp_gu, grp_d; - MmqBufs(int64_t rows, int E) - : xq(mmq::q8_bytes(rows, N)), gu((size_t) rows * 1280 * 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(Q2, 1280, N) + 4096), grp_d(GROUP * mmq::matrix_bytes(Q2, N, FF) + 4096) {} -}; -void run_mmq(mmq::Context& ctx, MmqBufs& b, const Routing& r, const float* x_dev, const int32_t* src_dev, - const std::vector& blob, int64_t rows, cudaStream_t s) { - const size_t gub = mmq::matrix_bytes(Q2, 1280, N), db = mmq::matrix_bytes(Q2, N, FF); - const int E = (int) r.cnt.size(); - std::vector order; - for (int e = 0; e < E; ++e) if (r.cnt[(size_t) e] > 0) order.push_back(e); - const size_t n = order.size(), ng = (n + GROUP - 1) / GROUP; - std::vector bh(n + 1 + ng * (GROUP + 1)); - for (size_t j = 0; j < n; ++j) bh[j] = r.off[(size_t) order[j]]; - bh[n] = (int32_t) rows; - for (size_t g = 0; g < ng; ++g) - for (size_t i = 0; i <= GROUP; ++i) - bh[n + 1 + g * (GROUP + 1) + i] = bh[std::min(n, g * GROUP + i)] - bh[g * GROUP]; - ck(cudaMemcpyAsync(b.bounds.p, bh.data(), bh.size() * 4, cudaMemcpyHostToDevice, s), "bounds"); - mmq::iota(b.ident.as(), rows, s); - mmq::quantize(x_dev, src_dev, b.xq.p, Q2, N, N, rows, s); - for (size_t j = 0; j < n; ++j) { - const size_t q = j % GROUP; - mmq::gather_strata_q2(blob[(size_t) order[j]], b.grp_gu.as() + q * gub, b.grp_d.as() + q * db, - s); - if (q + 1 < GROUP && j + 1 < n) continue; - const size_t j0 = j - q, g = j0 / GROUP; - const int ngx = (int) (q + 1); - const int64_t r0 = bh[j0], nr = bh[j + 1] - r0; - int64_t maxr = 0; - for (size_t i = j0; i <= j; ++i) maxr = std::max(maxr, r.cnt[(size_t) order[i]]); - ck(cudaMemsetAsync(b.grp_gu.as() + (size_t) ngx * gub, 0, 4096, s), "tail"); - ck(cudaMemsetAsync(b.grp_d.as() + (size_t) ngx * db, 0, 4096, s), "tail"); - mmq::Product gu; - gu.w = b.grp_gu.p; gu.type = Q2; gu.w_rows = 1280; gu.w_cols = N; gu.expert_bytes = gub; - gu.n = ngx; gu.xq = b.xq.p; gu.bounds = b.bounds.as() + j0; gu.ids = b.ident.as(); - gu.total_rows = rows; gu.max_rows = maxr; gu.dst = b.gu.as(); gu.ld_dst = 1280; - ctx.run(gu, s); - mmq::swiglu(b.gu.as() + r0 * 1280, b.h.as() + r0 * FF, nr, FF, true, s); - mmq::quantize(b.h.as() + r0 * FF, nullptr, b.hq.p, Q2, FF, FF, nr, s); - mmq::Product dn; - dn.w = b.grp_d.p; dn.type = Q2; dn.w_rows = N; dn.w_cols = FF; dn.expert_bytes = db; - dn.n = ngx; dn.xq = b.hq.p; dn.bounds = b.bounds.as() + n + 1 + g * (GROUP + 1); - dn.ids = b.ident.as(); dn.total_rows = nr; dn.max_rows = maxr; dn.dst = b.dm.as() + r0 * N; - dn.ld_dst = N; - ctx.run(dn, s); - } -} - -// the fused path: quantize, group on the device, then launches over expert ranges `cuts` (e.g. {0, 20, 64}) -struct FusedBufs { - Dev xa, ha, dm, scratch, slot, src, ids; - FusedBufs(int T, int64_t rows, int E) - : xa(fused::act_bytes(T, N)), ha(fused::act_bytes(rows, FF)), dm((size_t) rows * N * 4), - scratch(fused::group_bytes(rows, E)), slot((size_t) rows * 4), src((size_t) rows * 4), - ids((size_t) rows * 4) {} -}; -void run_fused(FusedBufs& b, const float* x_dev, int T, int E, const std::vector& cuts, - const std::vector& blob, cudaStream_t s) { - const int64_t rows = (int64_t) T * K; - fused::quantize_act(x_dev, T, N, b.xa.p, s); - fused::group(b.ids.as(), rows, K, E, b.scratch.p, b.slot.as(), b.src.as(), s); - for (size_t c = 0; c + 1 < cuts.size(); ++c) { - for (int e0 = cuts[c]; e0 < cuts[c + 1]; e0 += fused::kMaxBatch) { - fused::Batch bt; - bt.e0 = e0; - bt.e1 = std::min(cuts[c + 1], e0 + fused::kMaxBatch); - for (int e = bt.e0; e < bt.e1; ++e) bt.blob[e - bt.e0] = blob[(size_t) e]; - fused::experts(bt, E, rows, b.scratch.p, b.xa.p, b.src.as(), b.ha.p, b.dm.as(), s); - } - } -} - -struct Err { - double rms = 0, worst = 0; // RMS error / RMS of the reference; the worst row's max |error| / its max |ref| -}; -// y_a[row_a(i)] against y_b[row_b(i)] for every pair i (rows of N values) -template -Err compare(const std::vector& a, RA row_a, const std::vector& b, RB row_b, size_t pairs) { - double e2 = 0, r2 = 0; - Err out; - for (size_t i = 0; i < pairs; ++i) { - const float* ya = a.data() + (size_t) row_a(i) * N; - const float* yb = b.data() + (size_t) row_b(i) * N; - double me = 0, mr = 0; - for (int o = 0; o < N; ++o) { - if (!std::isfinite(ya[o])) throw std::runtime_error("a non-finite output"); - const double d = (double) ya[o] - yb[o]; - e2 += d * d; - r2 += (double) yb[o] * yb[o]; - me = std::max(me, std::fabs(d)); - mr = std::max(mr, (double) std::fabs(yb[o])); - } - if (mr > 0) out.worst = std::max(out.worst, me / mr); - else if (me > 0) out.worst = 1e30; // a zero row must stay exactly zero - } - out.rms = r2 > 0 ? std::sqrt(e2 / r2) : 0; - return out; -} - -std::vector download(const Dev& d, size_t n) { - std::vector h(n); - ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download"); - return h; -} -std::vector download_i(const Dev& d, size_t n) { - std::vector h(n); - ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download"); - return h; -} - -// part 1: against the double-precision reference -void reference_part(cudaStream_t s) { - constexpr int T = 256, E = 64, ZERO = 77; - std::mt19937 rng(136); - std::vector> host((size_t) E); - std::vector> dev; - std::vector blob((size_t) E); - for (int e = 0; e < E; ++e) { - host[(size_t) e] = make_blob(rng); - dev.push_back(std::make_unique(BLOB + 4096 * (size_t) (e % 3))); // unrelated addresses - uint8_t* p = dev.back()->as() + 256 * (size_t) (e % 3); // 16-byte aligned, not 512 - ck(cudaMemcpy(p, host[(size_t) e].data(), BLOB, cudaMemcpyHostToDevice), "blob"); - blob[(size_t) e] = p; - } - const std::vector x = make_x(T, rng, ZERO); - const std::vector ids = make_ids(T, E, rng, 2, 4); // experts 0, 1 hot (several tiles), 60-63 unused - const int64_t rows = (int64_t) T * K; - const Routing r = sort_rows(ids, E); - std::printf("reference part: %d tokens, %d experts, rows per expert: max %d, experts without rows %d\n", T, E, - *std::max_element(r.cnt.begin(), r.cnt.end()), (int) std::count(r.cnt.begin(), r.cnt.end(), 0)); - - Dev x_dev(x.size() * 4), src_dev((size_t) rows * 4); - ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); - ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src"); - mmq::Context ctx; - MmqBufs mb(rows, E); - // the uploads (legacy stream) must land before the non-blocking stream reads them (S20 found the kernels could run - // on all-zero routing otherwise - every pair on one expert: fast and wrong) - ck(cudaDeviceSynchronize(), "uploads"); - run_mmq(ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s); - FusedBufs fb(T, rows, E); - ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids"); - ck(cudaMemset(fb.dm.p, 0xff, (size_t) rows * N * 4), "sentinel"); // an unwritten row is NaN - ck(cudaDeviceSynchronize(), "uploads"); - run_fused(fb, x_dev.as(), T, E, {0, 1, 20, E}, blob, s); - ck(cudaStreamSynchronize(s), "sync"); - const std::vector y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N); - const std::vector slot = download_i(fb.slot, (size_t) rows), fsrc = download_i(fb.src, (size_t) rows); - for (int64_t i = 0; i < rows; ++i) - if (fsrc[(size_t) slot[(size_t) i]] != (int32_t) (i / K)) throw std::runtime_error("group: slot/src disagree"); - - // the reference, an expert at a time on all cores - std::vector ref((size_t) rows * N); - std::vector th; - const int nth = std::max(1, std::min(16, (int) std::thread::hardware_concurrency())); - for (int w = 0; w < nth; ++w) - th.emplace_back([&, w] { - std::vector gu, dn, h(FF); - for (int e = w; e < E; e += nth) { - if (r.cnt[(size_t) e] == 0) continue; - dequant(host[(size_t) e], gu, dn); - for (int64_t i = 0; i < rows; ++i) { - if (ids[(size_t) i] != e) continue; - const float* xr = x.data() + (size_t) (i / K) * N; - for (int f = 0; f < FF; ++f) { - double gt = 0, up = 0; - const float *wg = gu.data() + (size_t) (2 * f) * N, *wu = wg + N; - for (int k = 0; k < N; ++k) { gt += (double) wg[k] * xr[k]; up += (double) wu[k] * xr[k]; } - h[(size_t) f] = (float) (gt / (1.0 + std::exp(-gt)) * up); - } - for (int o = 0; o < N; ++o) { - double a = 0; - const float* wd = dn.data() + (size_t) o * FF; - for (int f = 0; f < FF; ++f) a += (double) wd[f] * h[(size_t) f]; - ref[(size_t) i * N + o] = (float) a; - } - } - } - }); - for (auto& t : th) t.join(); - - auto pair = [](size_t i) { return (int64_t) i; }; - auto mrow = [&](size_t i) { return (int64_t) r.row_of[i]; }; - auto frow = [&](size_t i) { return (int64_t) slot[i]; }; - const Err em = compare(y_mmq, mrow, ref, pair, (size_t) rows); - const Err ef = compare(y_f, frow, ref, pair, (size_t) rows); - const Err efm = compare(y_f, frow, y_mmq, mrow, (size_t) rows); - std::printf(" MMQ vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n", em.rms, em.worst); - std::printf(" fused vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n", ef.rms, ef.worst); - std::printf(" fused vs MMQ : rel RMS %.3e worst row max rel %.3e\n", efm.rms, efm.worst); - double zmax = 0; - for (int k = 0; k < K; ++k) - for (int o = 0; o < N; ++o) - zmax = std::max(zmax, (double) std::fabs(y_f[(size_t) slot[(size_t) (ZERO * K + k)] * N + o])); - if (zmax != 0) throw std::runtime_error("the all-zero token's outputs are not zero"); - if (ef.rms > 1.5 * em.rms || ef.worst > 2.0 * em.worst) - throw std::runtime_error("the fused path's error is not comparable to MMQ's"); -} - -// part 2: one layer at a real chunk, timed -void timing_part(cudaStream_t s) { - constexpr int T = 2048, E = 512; - std::mt19937 rng(1360); - const int64_t rows = (int64_t) T * K; - // 512 distinct blobs (708 MB) - the products read each once per tile, as the engine does - Dev blobs((size_t) E * BLOB); - { - std::vector b = make_blob(rng); - for (int e = 0; e < E; ++e) { - b[(size_t) e * 7919 % O_GU_SC] ^= (uint8_t) e; // not all equal - ck(cudaMemcpy(blobs.as() + (size_t) e * BLOB, b.data(), BLOB, cudaMemcpyHostToDevice), "blob"); - } - } - std::vector blob((size_t) E); - for (int e = 0; e < E; ++e) blob[(size_t) e] = blobs.as() + (size_t) e * BLOB; - const std::vector x = make_x(T, rng, -1); - const std::vector ids = make_ids(T, E, rng, 0, 0); - const Routing r = sort_rows(ids, E); - Dev x_dev(x.size() * 4), src_dev((size_t) rows * 4); - ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); - ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src"); - mmq::Context ctx; - MmqBufs mb(rows, E); - FusedBufs fb(T, rows, E); - ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids"); - ck(cudaDeviceSynchronize(), "uploads"); // the legacy-stream uploads before the timed non-blocking stream - cudaEvent_t a, b; - ck(cudaEventCreate(&a), "event"); - ck(cudaEventCreate(&b), "event"); - auto time = [&](auto&& f) { - std::vector ms; - for (int rep = 0; rep < 6; ++rep) { - ck(cudaEventRecord(a, s), "record"); - f(); - ck(cudaEventRecord(b, s), "record"); - ck(cudaEventSynchronize(b), "sync"); - float t = 0; - ck(cudaEventElapsedTime(&t, a, b), "elapsed"); - if (rep > 0) ms.push_back(t); // the first is the warm-up - } - std::sort(ms.begin(), ms.end()); - return ms[ms.size() / 2]; - }; - // the engine's batches: up to 128 experts per launch (the streamed ring decides; 4 launches here) - const float t_mmq = time([&] { run_mmq(ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s); }); - const float t_f = time([&] { run_fused(fb, x_dev.as(), T, E, {0, E}, blob, s); }); - const float t_f1 = time([&] { // one launch per 16 experts, MMQ's group size - std::vector cuts; - for (int e = 0; e <= E; e += 16) cuts.push_back(e); - run_fused(fb, x_dev.as(), T, E, cuts, blob, s); - }); - const std::vector y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N); - const std::vector slot = download_i(fb.slot, (size_t) rows); - const Err efm = compare(y_f, [&](size_t i) { return (int64_t) slot[i]; }, y_mmq, - [&](size_t i) { return (int64_t) r.row_of[i]; }, (size_t) rows); - std::printf("timing part: %d tokens x top %d over %d experts (%.1f rows per expert), one layer:\n", T, K, E, - (double) rows / E); - std::printf(" MMQ path (gathers, q8_1, products, SwiGLU, 32 groups): %.3f ms\n", t_mmq); - std::printf(" fused path (quantize, group, 4 launches of 128): %.3f ms (%.2fx)\n", t_f, t_mmq / t_f); - std::printf(" fused path, launches of 16 experts: %.3f ms\n", t_f1); - std::printf(" fused vs MMQ: rel RMS %.3e worst row max rel %.3e\n", efm.rms, efm.worst); - cudaEventDestroy(a); - cudaEventDestroy(b); - if (efm.rms > 0.05) throw std::runtime_error("the paths disagree at the real shape"); -} -} // namespace - -int main(int argc, char** argv) { - try { - int n = 0; - if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { std::printf("no CUDA device: skipped\n"); return 77; } - if (!fused::available()) { std::printf("the fused kernels need sm_80 or newer: skipped\n"); return 77; } - if (!mmq::built()) { std::printf("no MMQ in this build\n"); return 1; } - cudaStream_t s = nullptr; - ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream"); - reference_part(s); - if (!(argc > 1 && std::strcmp(argv[1], "--no-timing") == 0)) timing_part(s); - ck(cudaStreamDestroy(s), "destroy"); - std::printf("prefill fused MoE parity passed\n"); - return 0; - } catch (const std::exception& e) { - std::fprintf(stderr, "prefill fused MoE parity failed: %s\n", e.what()); - return 1; - } -} diff --git a/tests/cuda/prefill_mmq_kquant_test.cpp b/tests/cuda/prefill_mmq_kquant_test.cpp deleted file mode 100644 index cd976df..0000000 --- a/tests/cuda/prefill_mmq_kquant_test.cpp +++ /dev/null @@ -1,209 +0,0 @@ -// prefill_mmq_kquant_test - the prompt path's MMQ products for the expert formats of Unsloth's UD-Q4_K_XL (Q4_K and -// Q5_K gate/up at 1280 x 2560, Q5_1 and Q8_0 down at 2560 x 640), on synthetic weights quantized by ggml's own -// 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. 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" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { -namespace mmq = strata::prefill::mmq; - -void ck(cudaError_t e, const char* what) { - if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e)); -} - -struct Dev { - void* p = nullptr; - explicit Dev(size_t n) { ck(cudaMalloc(&p, n), "cudaMalloc"); } - ~Dev() { cudaFree(p); } - Dev(const Dev&) = delete; - Dev& operator=(const Dev&) = delete; -}; - -std::vector 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 out((size_t) rows * rb); - std::vector row((size_t) cols); - for (int64_t r = 0; r < rows; ++r) { - for (int64_t k = 0; k < cols; ++k) { - const int code = (int) ((k * 37 + r * 19 + expert * 23 + trial * 11) % 101) - 50; - row[(size_t) k] = 0.025f * std::sin(0.013f * (float) (k + 1) + 0.17f * (float) r + 0.31f * (float) expert) + - 0.0015f * (float) code; - } - tr->from_float_ref(row.data(), out.data() + (size_t) r * rb, cols); - } - return out; -} - -std::vector make_x(int rows, int64_t cols, int trial) { - std::vector x((size_t) rows * (size_t) cols); - for (int r = 0; r < rows; ++r) - for (int64_t k = 0; k < cols; ++k) - x[(size_t) r * (size_t) cols + (size_t) k] = - 0.45f * std::sin(0.009f * (float) (k + 1) + 0.23f * (float) r + 0.07f * (float) trial) + - 0.17f * std::cos(0.021f * (float) (k + 3) - 0.19f * (float) r) + - 0.002f * (float) (((k * 7 + r * 13 + trial * 5) % 19) - 9); - std::fill(x.end() - cols, x.end(), 0.0f); // an all-zero row: exactly zero out - return x; -} - -std::vector perm(int n, int shift, bool reverse) { - std::vector p((size_t) n); - for (int i = 0; i < n; ++i) p[(size_t) i] = (int32_t) (((reverse ? n - 1 - i : i) + shift) % n); - return p; -} - -// one grouped product: experts side by side at one stride (a zeroed tail after them, as prefill.cpp stages them) -void product(mmq::Context& ctx, cudaStream_t s, const char* name, ggml_type t, int64_t out_rows, int64_t cols, - const std::vector& counts, int trial) { - if (!mmq::supported((int) t)) throw std::runtime_error(std::string(name) + ": not covered by this build"); - const int n = (int) counts.size(), rows = std::accumulate(counts.begin(), counts.end(), 0); - std::vector bounds((size_t) n + 1, 0); - for (int e = 0; e < n; ++e) bounds[(size_t) e + 1] = bounds[(size_t) e] + counts[(size_t) e]; - const auto src = perm(rows, trial + 1, false), dst = perm(rows, trial + 2, true); - const std::vector x = make_x(rows, cols, trial); - const size_t eb = mmq::matrix_bytes((int) t, out_rows, cols); - if (eb != (size_t) out_rows * ggml_row_size(t, cols)) throw std::runtime_error(std::string(name) + ": matrix_bytes"); - std::vector> ws; - std::vector w((size_t) n * eb + 4096, 0); - for (int e = 0; e < n; ++e) { - ws.push_back(make_matrix(t, out_rows, cols, e, trial)); - std::copy(ws.back().begin(), ws.back().end(), w.begin() + (ptrdiff_t) ((size_t) e * eb)); - } - Dev dx(x.size() * 4), dsrc((size_t) rows * 4), ddst((size_t) rows * 4), db(bounds.size() * 4), dw(w.size()), - dxq(mmq::q8_bytes(rows, cols)), dy((size_t) rows * (size_t) out_rows * 4); - ck(cudaMemcpy(dx.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); - ck(cudaMemcpy(dsrc.p, src.data(), src.size() * 4, cudaMemcpyHostToDevice), "src"); - ck(cudaMemcpy(ddst.p, dst.data(), dst.size() * 4, cudaMemcpyHostToDevice), "dst"); - 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; - p.xq = dxq.p; p.bounds = (const int32_t*) db.p; p.ids = (const int32_t*) ddst.p; p.total_rows = rows; - p.max_rows = *std::max_element(counts.begin(), counts.end()); p.dst = (float*) dy.p; p.ld_dst = out_rows; - ctx.run(p, s); - ck(cudaGetLastError(), "launch"); - ck(cudaStreamSynchronize(s), "sync"); - std::vector got((size_t) rows * (size_t) out_rows); - ck(cudaMemcpy(got.data(), dy.p, got.size() * 4, cudaMemcpyDeviceToHost), "y"); - - const auto* tr = ggml_get_type_traits(t); - std::vector ref(got.size(), 0.0f), wd((size_t) out_rows * (size_t) cols); - for (int e = 0; e < n; ++e) { - const size_t rb = ggml_row_size(t, cols); - for (int64_t o = 0; o < out_rows; ++o) - tr->to_float(ws[(size_t) e].data() + (size_t) o * rb, wd.data() + (size_t) o * (size_t) cols, cols); - for (int r = bounds[(size_t) e]; r < bounds[(size_t) e + 1]; ++r) { - const float* xr = x.data() + (size_t) src[(size_t) r] * (size_t) cols; - for (int64_t o = 0; o < out_rows; ++o) { - double acc = 0; - const float* wr = wd.data() + (size_t) o * (size_t) cols; - for (int64_t k = 0; k < cols; ++k) acc += (double) wr[k] * xr[k]; - ref[(size_t) dst[(size_t) r] * (size_t) out_rows + (size_t) o] = (float) acc; - } - } - } - 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) { - 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)); - } - for (int r = 0; r < rows; ++r) - if (src[(size_t) r] == rows - 1) // the zero row - for (int64_t o = 0; o < out_rows; ++o) - zero_max = std::max(zero_max, (double) std::fabs(got[(size_t) dst[(size_t) r] * (size_t) out_rows + (size_t) o])); - const double rms = std::sqrt(ref2 / (double) ref.size()), rel = std::sqrt(err2 / (double) ref.size()) / rms; - std::printf("%-22s rows %2d experts %d ref_rms %.4g rel_l2 %.5f max/rms %.4f zero row %.3g\n", name, rows, n, rms, - rel, max_abs / rms, zero_max); - if (rel > 0.04 || max_abs / rms > 0.35 || zero_max > std::max(1e-5, 1e-4 * rms)) - throw std::runtime_error(std::string(name) + ": outside the screen"); -} -} // namespace - -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_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> batches{{1, 3, 3}, {4, 1, 2}, {2, 3}, {17}}; - int trial = 0; - for (const auto& counts : batches) { - const std::string tag = "-" + std::to_string(trial); - product(ctx, s, ("Q4_K gate/up" + tag).c_str(), GGML_TYPE_Q4_K, 1280, 2560, counts, trial); - 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; - } - } - ck(cudaStreamDestroy(s), "destroy"); - std::printf("prefill MMQ K-quant screen passed\n"); - return 0; - } catch (const std::exception& e) { - std::fprintf(stderr, "prefill MMQ K-quant screen failed: %s\n", e.what()); - return 1; - } -} diff --git a/tests/cuda/prefill_qwen36_test.cpp b/tests/cuda/prefill_qwen36_test.cpp deleted file mode 100644 index 4ee0a34..0000000 --- a/tests/cuda/prefill_qwen36_test.cpp +++ /dev/null @@ -1,483 +0,0 @@ -// 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 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 /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 - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -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 T* dalloc(size_t n) { - void* p = nullptr; - ck(cudaMalloc(&p, n * sizeof(T) + 256), "cudaMalloc"); - return (T*) p; -} -template T* upload(const void* host, size_t bytes) { - T* d = dalloc(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 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 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> 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 owned; - HostExperts experts; - std::vector 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 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(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 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(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(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& 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 stats; // "-" - std::vector 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 scratch; - std::map> cache; - const std::vector& 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& 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& o = dump("ffn_moe_topk-" + std::to_string(layer)); - const std::vector& 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& 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& tokens, - std::string& err, cudaStream_t cs) { - strata::prefill::Prefill pf; - if (!pf.init(fx.wt, fx.g, ss, const_cast(&fx.experts), nullptr, nullptr, chunk, cs, err)) return false; - std::vector 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 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 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; -} diff --git a/tests/cuda/qwen36_block_test.cpp b/tests/cuda/qwen36_block_test.cpp deleted file mode 100644 index debcee3..0000000 --- a/tests/cuda/qwen36_block_test.cpp +++ /dev/null @@ -1,531 +0,0 @@ -// tests/cuda/qwen36_block_test.cpp - the plain block (hc = 1, Qwen3.6) composed by the engine, held to the oracle. -// -// qwen36_block_test -// -// holds tools/qwen36_synth_gguf.py's toy.gguf (CMake's qwen36_synth_fixtures); 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 - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -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: .f32 in C order of the numpy array, shapes from manifest.txt (`stem kind ne0,ne1,..`) -struct Dumps { - fs::path dir; - std::map> 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 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 std::vector 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 v((size_t) n / sizeof(T)); - f.read((char*) v.data(), n); - return v; - } - std::vector f(const std::string& stem) const { return read(stem); } - /// the "i32" dumps (`ffn_moe_topk-N`) are written as float32 like every other (the oracle's Dump casts to F32) - std::vector i(const std::string& stem) const { - const std::vector v = read(stem); - std::vector 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 down(const float* d, size_t n) { std::vector v(n); CUDA_OK(cudaMemcpy(v.data(), d, n * 4, cudaMemcpyDeviceToHost)); return v; } -std::vector down_i(const int32_t* d, size_t n) { std::vector 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 bytes; int64_t ne0, ne1; }; -void write_pack(const fs::path& dir, const std::vector& rows) { - fs::create_directories(dir); - std::vector 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 \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 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 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 x_in = l == 0 ? x0 : d.f("l_out-" + std::to_string(l - 1)); - const std::vector 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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; -} diff --git a/tests/cuda/qwen36_mtp_test.cpp b/tests/cuda/qwen36_mtp_test.cpp deleted file mode 100644 index 5425322..0000000 --- a/tests/cuda/qwen36_mtp_test.cpp +++ /dev/null @@ -1,622 +0,0 @@ -// tests/cuda/qwen36_mtp_test.cpp - the Qwen3.6 drafter (the -MTP file's nextn block through core/mtp.cpp) held to the -// oracle's `--mtp` dumps, seam by seam and position by position (docs/qwen36-port/step4-drafter.md). -// -// qwen36_mtp_test -// tests/python/qwen36_mtp_fixture.py --out : mtp5.gguf (the prompt-path fixture's full4 trunk plus -// the nextn block blk.4, Q8_0 projections / experts / head / embedding), the oracle's dumps for 76 tokens (o, -// o_mtp: faithful; o_q8, o_q8_mtp: --act-quant q8) and the draft pack cut from it (pack/). -// qwen36_mtp_test --real --gguf FILE --pack DIR --dump D --mtp-dump D_mtp --tokens t,t,... -// the real file: `tools/qwen36_dump_llama.cpp FILE D t,t,... 0 mtp` wrote the trunk's `l_out-` (every token's -// final residual) to D and llama.cpp's own MTP graph (token k with the hidden of k-1, at position k) to D_mtp; -// the drafter's top-1 at every position against llama.cpp's MTP top-1 and against the prompt's next token. -// -// The synthetic case, per position k = 1..75 (token k with the trunk's final residual of k-1, the oracle's pairing): -// 1. `MtpDrafter::debug_row` (the one-row forward outside any graph) hands every seam to the test, which holds it -// to the Q8 oracle's row k-1 by llama.cpp's cb() name (relative L2 per row, the worst over the positions, against -// the gates below; the F32 oracle's figure is reported beside it), the router's top-8 identical as a set, the -// draft equal to the oracle's argmax at every position; -// 2. the negative cases (upstream-tooling.md section 3): concat(hnorm, enorm) (the hidden state first) must move -// `mtp_eh_proj` by more than 5 % relative L1, hnorm skipped must move `mtp_hnorm`, and the drafter paired with -// position k (the hidden of k instead of k-1) must move `mtp_hnorm` and `result_output`; -// 3. the captured graph path (`draft_first`): draft 0 equals the uncaptured forward's draft at the same cell; -// 4. the prompt-side pass (`Prefill::draft_kv`, 64 cells through the prompt path's GEMMs) in place of the drafter's -// own K/V for cells 0..63, then positions 65.. through the forward again, held to the same gates. -// -// Tolerances: the Q8 oracle rounds activations as ggml does before each quantized matmul; the engine's MMVQ and the -// native expert kernels take q8_1 activations (the same rounding, integer dot products), so the per-seam figures are -// oracle-crosscheck.md's Q8 column with its 4x margin (`attn_out` 6.7e-4 -> 3e-3, `moe_out` / `ffn_out` 5.3e-3 -> 2e-2, -// `l_out` 1.4e-3 -> 6e-3), the norms of forced inputs 1e-5 (the CUDA rsqrtf), the fp16 K/V pool 2.2e-4 at the attention -// (step3-attn.md) inside the attn_out class. Exit 77 without a CUDA device or the fixtures, 1 on a failure. -#include "strata/artifact/gguf_reader.hpp" -#include "strata/core/expert_source.hpp" -#include "strata/core/layer.hpp" -#include "strata/core/model_geometry.hpp" -#include "strata/core/mtp.hpp" -#include "strata/core/native_head.hpp" -#include "strata/core/session.hpp" -#include "strata/core/weights.hpp" -#include "strata/kernels/cpu/expert_layout.hpp" -#include "strata/prefill/prefill.hpp" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fs = std::filesystem; -namespace core = strata::core; - -namespace { -int g_fail = 0; -void check(bool ok, const std::string& what) { - std::printf(" %-110s %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; } -[[noreturn]] void die(const std::string& what) { std::fprintf(stderr, "qwen36_mtp_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 T* upload(const void* src, size_t bytes) { - void* d = nullptr; - ck(cudaMalloc(&d, bytes ? bytes : 1), "cudaMalloc"); - if (bytes) ck(cudaMemcpy(d, src, bytes, cudaMemcpyHostToDevice), "upload"); - return (T*) d; -} - -std::vector read_f32(const fs::path& path) { - std::ifstream f(path, std::ios::binary); - if (!f) die("missing dump " + path.string()); - f.seekg(0, std::ios::end); - const std::streamoff n = f.tellg(); - f.seekg(0); - std::vector v((size_t) n / 4); - f.read((char*) v.data(), n); - return v; -} - -// ---- one named seam's errors over the positions: relative L2 per row (the worst), relative L1 over all rows -struct Stat { - double worst_l2 = 0.0, l1_num = 0.0, l1_den = 0.0; - int rows = 0; - void add(const float* e, const float* o, int64_t n) { - double d2 = 0.0, o2 = 0.0; - for (int64_t i = 0; i < n; ++i) { - const double d = (double) e[i] - o[i]; - d2 += d * d; o2 += (double) o[i] * o[i]; - l1_num += std::fabs(d); l1_den += std::fabs((double) o[i]); - } - worst_l2 = std::max(worst_l2, o2 > 0 ? std::sqrt(d2 / o2) : (d2 > 0 ? INFINITY : 0.0)); - ++rows; - } - double l1() const { return l1_den > 0 ? l1_num / l1_den : (l1_num > 0 ? INFINITY : 0.0); } -}; - -// ---- the oracle's dumps of the nextn block: .f32 in C order; row t of a (.., T) tensor -struct Dumps { - fs::path dir; - std::map> cache; - const std::vector& get(const std::string& stem) { - auto it = cache.find(stem); - if (it == cache.end()) it = cache.emplace(stem, read_f32(dir / (stem + ".f32"))).first; - return it->second; - } - bool has(const std::string& stem) const { return fs::exists(dir / (stem + ".f32")); } -}; - -const char* const kSeams[] = {"mtp_tok_embd", "mtp_enorm", "mtp_hnorm", "mtp_concat", "mtp_eh_proj", "mtp_attn_norm", - "mtp_Vcur", "mtp_Kcur_normed", "mtp_Qcur_full", "mtp_Qcur_normed", "mtp_attn_pregate", - "mtp_attn_out", "mtp_attn_residual", "mtp_attn_post_norm", "ffn_moe_logits", - "ffn_moe_weights_norm", "mtp_ffn_shexp_gated", "mtp_ffn_out", "mtp_post_ffn", - "mtp_shared_head_norm", "result_output"}; -bool layer_seam(const std::string& s) { return s != "mtp_shared_head_norm" && s != "result_output"; } -// Relative L2 per row against the Q8 oracle. The first product after the forced inputs (eh_proj) measures 2.3e-4 on -// both cards; every product after it sees an input that differs from the oracle's by that much, and the oracle's own -// q8 rounding of a slightly different input flips about 1 % of the int8 codes by one step (2e-4 x rms/amax x 127), which -// is 2e-3 of the output: the measured 2.0-2.2e-3 at the Q/K/V projections. So the gates past eh_proj are the measured -// figures (step4-drafter.md, both cards) with a 2-3x margin, inside the policy's Q8 classes with their 4x margin -// (attn_out 6.7e-4 -> 2.7e-3 per forced layer; here four products compound), and the real checks are the router's -// picks and the argmax, which are exact. -double gate_for(const std::string& s) { - if (s == "mtp_tok_embd") return 1e-6; // an exact dequantization - if (s == "mtp_enorm" || s == "mtp_hnorm" || s == "mtp_concat") return 1e-5; // norms of forced inputs - if (s == "mtp_eh_proj" || s == "mtp_attn_norm") return 1e-3; // one q8_1 x Q8_0 product (2.3e-4) - if (s == "mtp_Vcur" || s == "mtp_Kcur_normed" || s == "mtp_Qcur_full" || s == "mtp_Qcur_normed") return 5e-3; // 2.1e-3 - if (s == "mtp_attn_pregate") return 5e-3; // 1.6e-3 (the fp16 pool inside) - if (s == "mtp_attn_out") return 1e-2; // 5.4e-3 - if (s == "mtp_attn_residual" || s == "mtp_attn_post_norm" || s == "ffn_moe_logits") return 5e-3; // 1.1-1.2e-3 - if (s == "ffn_moe_weights_norm") return 1e-2; // 1.7e-3: near-ties move the softmax - if (s == "mtp_ffn_shexp_gated" || s == "mtp_ffn_out") return 3e-2; // 1.1-1.2e-2 (moe_out class) - if (s == "mtp_post_ffn" || s == "mtp_shared_head_norm") return 1.5e-2; // 5.3e-3 (l_out class) - return 3e-2; // result_output: the logits -} - -// ---- the trunk's weights and experts for Prefill::init (the fixture's 4 Q8_0 layers), as prefill_qwen36_test loads them -struct HostExperts : core::ExpertSource { - std::vector> blobs; - 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(); } -}; -uint16_t bf16_of(float f) { uint32_t u; std::memcpy(&u, &f, 4); return (uint16_t) (u >> 16); } -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; } - -struct Trunk { - core::WeightTable wt; - std::vector owned; - HostExperts experts; - int64_t n_vocab = 0; - void load(const strata::GgufFile& gguf, const core::ModelGeometry& g, bool with_experts) { - experts.n_expert = g.n_expert; - experts.blobs.resize((size_t) (g.n_layers * g.n_expert)); - std::map exp_t; - for (const auto& t : gguf.tensors()) { - int64_t blk = -1; - if (t.name.rfind("blk.", 0) == 0) blk = std::atoll(t.name.c_str() + 4); - if (blk >= g.n_layers) continue; // the nextn block: the drafter's pack - 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; } - 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.name == "output.weight") n_vocab = r.ne1; - if (t.name == "output.weight" || t.name == "token_embd.weight") { // shape only: the native head / embedding - r.resident = false; - r.native_type = (int) t.type; - } else if (t.type == 8) { // Q8_0: served natively - r.native_data = upload(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")) { - std::vector 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]); - r.kind = core::WeightKind::Bf16InF32; - r.data = upload(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(src, bytes); - owned.push_back((void*) r.data); - } - wt.set(t.name, r); - } - if (!with_experts) return; - 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 trunk's 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; - for (int64_t e = 0; e < g.n_expert; ++e) { - std::vector& 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); - } - } - } - void write_layout(const core::ModelGeometry& g, 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"; - } - ~Trunk() { for (void* p : owned) cudaFree(p); } -}; - -struct TempDir { - fs::path path; - TempDir() { - path = fs::temp_directory_path() / ("strata-qwen36-mtp-test-" + std::to_string((long long) getpid())); - fs::create_directories(path); - } - ~TempDir() { std::error_code ignored; fs::remove_all(path, ignored); } -}; - -// ---- the drafter's forward at one position, every seam against the oracle's row -struct Compare { - Dumps *q8 = nullptr, *f32 = nullptr; - int64_t il = 0; - std::map st_q8, st_f32; - std::vector host; - int topk_bad = 0, topk_rows = 0; - int row = 0; // the oracle's row (position - 1) - std::vector ids; - std::vector last_logits; // the row's result_output - std::string stem(const std::string& s) const { return layer_seam(s) ? s + "-" + std::to_string(il) : s; } - void on_seam(const char* seam, const float* dev, int64_t n) { - const std::string s(seam); - host.resize((size_t) n); - ck(cudaMemcpy(host.data(), dev, (size_t) n * 4, cudaMemcpyDeviceToHost), "seam copy"); - if (s == "ffn_moe_topk") { // int32 ids behind the float pointer: identical as a set - ids.assign((const int32_t*) host.data(), (const int32_t*) host.data() + n); - const std::vector& o = q8->get(stem(s)); - std::set es(ids.begin(), ids.end()), os; - for (int64_t j = 0; j < n; ++j) os.insert((int32_t) std::lround(o[(size_t) (row * n + j)])); - ++topk_rows; - if (es != os) ++topk_bad; - return; - } - if (s == "result_output") last_logits = host; - if (s == "ffn_moe_weights_norm") { // matched by expert id (the oracle's order is by rank) - const std::vector& o = q8->get(stem(s)); - const std::vector& oi = q8->get(stem("ffn_moe_topk")); - std::vector matched((size_t) n, 0.0f); - for (int64_t j = 0; j < n; ++j) - for (int64_t i = 0; i < n; ++i) - if ((int32_t) std::lround(oi[(size_t) (row * n + i)]) == ids[(size_t) j]) matched[(size_t) j] = o[(size_t) (row * n + i)]; - st_q8[s].add(host.data(), matched.data(), n); - return; - } - for (Dumps* d : {q8, f32}) { - if (d == nullptr) continue; - const std::vector& o = d->get(stem(s)); - if (o.size() < (size_t) ((row + 1) * n)) die("dump " + stem(s) + " is too short for row " + std::to_string(row)); - (d == q8 ? st_q8 : st_f32)[s].add(host.data(), o.data() + (size_t) row * n, n); - } - } -}; - -int argmax(const float* v, int64_t n) { - int b = 0; - for (int64_t i = 1; i < n; ++i) if (v[i] > v[b]) b = (int) i; - return b; -} - -int run_synthetic(const std::string& dir) { - if (std::ifstream skip(dir + "/SKIP"); skip) { - std::string why; - std::getline(skip, why); - std::printf("qwen36_mtp_test: the fixtures were not generated (%s/SKIP: %s): skip\n", dir.c_str(), why.c_str()); - return 77; - } - const std::string gguf_path = dir + "/mtp5.gguf", pack = dir + "/pack"; - if (!fs::exists(gguf_path) || !fs::exists(pack + "/dense.txt")) { std::printf("qwen36_mtp_test: no fixture in %s: skip\n", dir.c_str()); return 77; } - strata::GgufFile gguf(gguf_path); - core::ModelGeometry g; - std::string err; - if (!core::read_model_geometry(gguf, g, err)) die("geometry: " + err); - if (g.arch != core::ModelArch::Qwen35Moe || g.nextn_layers != 1) die("the fixture is not a qwen35moe file with one nextn block"); - std::printf("fixture %s: %lld trunk layers + the nextn block blk.%lld, n_embd %lld, attention %lld/%lld x %lld, %lld experts top-%lld of %lld\n", - gguf_path.c_str(), (long long) g.n_layers, (long long) g.n_layers, (long long) g.n_embd, (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); - Trunk trunk; - trunk.load(gguf, g, true); - const int64_t n_vocab = trunk.n_vocab; - core::NativeHead head; - if (!head.load({gguf_path}, g.n_embd, n_vocab, err)) die("native head: " + err); - core::NativeEmbed embed; - if (!embed.load({gguf_path}, g.n_embd, n_vocab, err)) die("native embedding: " + err); - core::set_native_embed(&embed); - // the tokens and the trunk's final residual rows (the oracle's l_out-: what the verify window hands the drafter) - Dumps o, o_mtp, q8, q8_mtp; - o.dir = dir + "/o"; o_mtp.dir = dir + "/o_mtp"; q8.dir = dir + "/o_q8"; q8_mtp.dir = dir + "/o_q8_mtp"; - const std::string text = "the quick brown fox jumps over the lazy dog while the cat sleeps on the mat "; - std::vector tokens; - for (char c : text) tokens.push_back((int32_t) (unsigned char) c); - const int n_tok = (int) tokens.size(); - const int64_t N = g.n_embd; - // the Q8 oracle's trunk: its nextn dumps (the primary reference) were computed from these rows - const std::vector& R_all = q8.get("l_out-" + std::to_string(g.n_layers - 1)); - if (R_all.size() != (size_t) n_tok * N) die("l_out dump: " + std::to_string(R_all.size()) + " floats for " + std::to_string(n_tok) + " tokens"); - float* R_dev = upload(R_all.data(), R_all.size() * 4); - // the session (the drafter borrows the primary attention state's RoPE tables) and the drafter - const int64_t max_cells = 128, max_t = 4; - core::SessionState ss; - void* sbase = nullptr; - ck(cudaMalloc(&sbase, core::session_bytes(g, max_cells, g.n_expert_used)), "session"); - if (core::session_init(g, max_cells, g.n_expert_used, sbase, ss) == 0) die("session_init failed"); - ss.k = g.n_expert_used; - core::MtpDrafter mtp; - if (!mtp.load(pack, g, ss, (int) max_t, err, 0)) die("mtp load: " + err); - float* window_R = nullptr; - ck(cudaMalloc((void**) &window_R, (size_t) max_t * N * 4), "window_R"); - if (!mtp.bind(trunk.wt, &head, window_R, err)) die("mtp bind: " + err); - std::printf("drafter: %s, experts %d/%d blob %lld B, %.0f MiB of VRAM\n", mtp.qwen36() ? "qwen35moe" : "?", - mtp.expert_gu_type(), mtp.expert_d_type(), (long long) mtp.expert_blob_bytes(), (double) mtp.vram_bytes() / 1048576.0); - - // ---- 1. the forward at every position, seam by seam - const int n_pos = n_tok - 1; - Compare cmp; - cmp.q8 = &q8_mtp; cmp.f32 = nullptr; cmp.il = g.n_layers; - const std::vector& o_logits = q8_mtp.get("result_output"); - std::vector top1((size_t) n_pos, -1); - int argmax_bad = 0; - auto hook = [&](const char* s, const float* d, int64_t n) { cmp.on_seam(s, d, n); }; - for (int k = 1; k <= n_pos; ++k) { - cmp.row = k - 1; - int32_t t1 = -1; - // the engine's convention: RoPE at the cell (the hidden state's position); the oracle rotates at k, one more, - // which the attention cannot see (RoPE is relative), so the comparison holds to float rounding - if (!mtp.debug_row(R_dev + (size_t) (k - 1) * N, tokens[(size_t) k], k - 1, k - 1, core::MtpDrafter::DebugOpts{}, hook, &t1, err)) - die("debug_row at position " + std::to_string(k) + ": " + err); - top1[(size_t) (k - 1)] = t1; - if (t1 != argmax(o_logits.data() + (size_t) (k - 1) * n_vocab, n_vocab)) { - // a flip is a near tie when the oracle's gap between its pick and the engine's is within a few times the - // row's largest per-logit error (the logits class is 1e-2 relative); anything wider is a failure - const float* o = o_logits.data() + (size_t) (k - 1) * n_vocab; - const float gap = o[argmax(o, n_vocab)] - o[t1]; - float worst = 0.0f; - for (int64_t i = 0; i < n_vocab; ++i) worst = std::max(worst, std::fabs(cmp.last_logits[(size_t) i] - o[i])); - std::printf(" position %d: the draft %d, the Q8 oracle's argmax %d, oracle gap %.3e, largest logit error %.3e%s\n", k, t1, - argmax(o, n_vocab), gap, worst, gap <= 3.0f * worst ? " (near tie)" : " *** NOT A TIE ***"); - if (gap > 3.0f * worst) ++argmax_bad; - } - } - // the same positions from the F32 oracle's trunk rows against its own nextn dumps (reported: the F32 oracle does - // not round activations, so its column is the engine's q8_1 rounding itself, the 1e-2 class) - Compare cmp32; - cmp32.q8 = &o_mtp; cmp32.f32 = nullptr; cmp32.il = g.n_layers; - { - const std::vector& R32 = o.get("l_out-" + std::to_string(g.n_layers - 1)); - float* R32_dev = upload(R32.data(), R32.size() * 4); - auto hook32 = [&](const char* s, const float* d, int64_t n) { cmp32.on_seam(s, d, n); }; - for (int k = 1; k <= n_pos; ++k) { - cmp32.row = k - 1; - int32_t t1 = -1; - if (!mtp.debug_row(R32_dev + (size_t) (k - 1) * N, tokens[(size_t) k], k - 1, k - 1, core::MtpDrafter::DebugOpts{}, hook32, &t1, err)) - die("debug_row (F32 rows) at position " + std::to_string(k) + ": " + err); - } - cudaFree(R32_dev); - } - std::printf("the forward at %d positions (token k with the hidden of k-1), relative L2 per row, worst over the positions:\n", n_pos); - std::printf(" %-28s %12s %12s %12s\n", "seam", "vs Q8 oracle", "gate", "vs F32 oracle"); - for (const char* s : kSeams) { - const Stat& a = cmp.st_q8[s]; - const double f = cmp32.st_q8.count(s) ? cmp32.st_q8[s].worst_l2 : 0.0; - const double gate = gate_for(s); - std::printf(" %-28s %12s %12s %12s\n", s, fmt(a.worst_l2).c_str(), fmt(gate).c_str(), fmt(f).c_str()); - check(a.rows == n_pos && a.worst_l2 <= gate, std::string(s) + " within " + fmt(gate)); - } - check(cmp.topk_rows == n_pos && cmp.topk_bad == 0, "ffn_moe_topk: the router's top-8 identical as a set at every position (" + std::to_string(cmp.topk_bad) + " of " + std::to_string(cmp.topk_rows) + " differ)"); - check(argmax_bad == 0, "the draft equals the Q8 oracle's argmax at every position but near ties (" + std::to_string(argmax_bad) + " of " + std::to_string(n_pos) + " differ beyond the logits' error)"); - { - int f32_bad = 0; - const std::vector& ol = o_mtp.get("result_output"); - for (int k = 1; k <= n_pos; ++k) if (top1[(size_t) (k - 1)] != argmax(ol.data() + (size_t) (k - 1) * n_vocab, n_vocab)) ++f32_bad; - std::printf(" (the draft against the F32 oracle's argmax: %d of %d differ, reported)\n", f32_bad, n_pos); - } - - // ---- 2. the negative cases: each rival reading must sit more than 5 % (relative L1) from the oracle - auto rival = [&](const char* what, const core::MtpDrafter::DebugOpts& opts, int shift, const char* seam_name, const char* seam2) { - Compare neg; - neg.q8 = &q8_mtp; neg.f32 = nullptr; neg.il = g.n_layers; - for (int k = 1; k <= n_pos - shift; ++k) { - neg.row = k - 1; - int32_t t1 = -1; - auto h = [&](const char* s, const float* d, int64_t n) { neg.on_seam(s, d, n); }; - if (!mtp.debug_row(R_dev + (size_t) (k - 1 + shift) * N, tokens[(size_t) k], k - 1, k - 1, opts, h, &t1, err)) - die(std::string("debug_row (") + what + "): " + err); - } - for (const char* sn : {seam_name, seam2}) { - if (sn == nullptr) continue; - const double l1 = neg.st_q8[sn].l1(); - check(l1 > 0.05, std::string("negative: ") + what + " moves " + sn + " by " + fmt(l1) + " relative L1 (> 0.05)"); - } - }; - core::MtpDrafter::DebugOpts hidden_first, skip_hnorm; - hidden_first.hidden_first = true; - skip_hnorm.skip_hnorm = true; - rival("concat(hnorm, enorm), the hidden state first", hidden_first, 0, "mtp_eh_proj", "result_output"); - rival("hnorm skipped", skip_hnorm, 0, "mtp_hnorm", "mtp_eh_proj"); - rival("paired with position k instead of k-1", core::MtpDrafter::DebugOpts{}, 1, "mtp_hnorm", "result_output"); - - // ---- 3. the captured graph (draft_first: the round graph's catch-up and full layer at cell 0) agrees with the - // uncaptured forward at the same cell - { - std::vector drafts((size_t) max_t, -1); - if (!mtp.draft_first((int) max_t, R_dev, tokens[1], 0, drafts.data(), err)) die("draft_first: " + err); - std::printf(" draft_first at cell 0: drafts %d %d %d; the forward's draft at position 1: %d\n", drafts[0], drafts[1], drafts[2], top1[0]); - check(drafts[0] == top1[0], "the captured round graph's draft 0 equals the uncaptured forward's at cell 0"); - } - - // ---- 4. the prompt-side pass: cells 0..63 through Prefill::draft_kv, then the forward at the positions after - { - TempDir tmp; - trunk.write_layout(g, tmp.path.string()); - if (!strata::kernels::cpu::expert_layout_load(tmp.path.string(), g.n_layers, g.n_expert, g.n_embd, g.n_ff, err)) die("expert layout: " + err); - cudaStream_t cs = nullptr; - ck(cudaStreamCreateWithFlags(&cs, cudaStreamNonBlocking), "stream"); - { // the Prefill is destroyed (its release syncs the stream) before the stream is - strata::prefill::Prefill pf; - if (!pf.init(trunk.wt, g, ss, &trunk.experts, nullptr, nullptr, 64, cs, err)) die("Prefill::init: " + err); - const int64_t n_kv = 64; - core::qsa_state_zero(mtp.kv_state_rw(), g, nullptr); - ck(cudaDeviceSynchronize(), "zero"); - err.clear(); - const bool batched = pf.draft_kv(mtp, R_dev, tokens.data() + 1, n_kv, 0, err); - check(batched && err.empty(), "Prefill::draft_kv took the 64 cells (" + (err.empty() ? std::string(batched ? "batched" : "declined") : err) + ")"); - if (batched) { - Compare after; - after.q8 = &q8_mtp; after.f32 = nullptr; after.il = g.n_layers; - int bad = 0; - auto h = [&](const char* s, const float* d, int64_t n) { after.on_seam(s, d, n); }; - for (int k = (int) n_kv + 1; k <= n_pos; ++k) { - after.row = k - 1; - int32_t t1 = -1; - if (!mtp.debug_row(R_dev + (size_t) (k - 1) * N, tokens[(size_t) k], k - 1, k - 1, core::MtpDrafter::DebugOpts{}, h, &t1, err)) - die("debug_row after draft_kv at position " + std::to_string(k) + ": " + err); - if (t1 != top1[(size_t) (k - 1)]) ++bad; // the drafter's own pass's draft at that position - } - std::printf(" after draft_kv's 64 cells, positions %lld..%d: attn_pregate %s, attn_out %s, ffn_out %s, head norm %s, logits %s (vs Q8 oracle)\n", - (long long) n_kv + 1, n_pos, fmt(after.st_q8["mtp_attn_pregate"].worst_l2).c_str(), fmt(after.st_q8["mtp_attn_out"].worst_l2).c_str(), - fmt(after.st_q8["mtp_ffn_out"].worst_l2).c_str(), fmt(after.st_q8["mtp_shared_head_norm"].worst_l2).c_str(), - fmt(after.st_q8["result_output"].worst_l2).c_str()); - for (const char* s : {"mtp_attn_pregate", "mtp_attn_out", "mtp_ffn_out", "mtp_shared_head_norm", "result_output"}) - check(after.st_q8[s].worst_l2 <= gate_for(s), std::string("after draft_kv: ") + s + " within " + fmt(gate_for(s))); - check(bad == 0, "after draft_kv: the drafts at the later positions equal the drafter's own pass's (" + std::to_string(bad) + " differ)"); - } - } - cudaStreamDestroy(cs); - } - core::set_native_embed(nullptr); - cudaFree(window_R); - cudaFree(R_dev); - cudaFree(sbase); - return g_fail ? 1 : 0; -} - -// ---- the real file: the drafter's top-1 per position against llama.cpp's MTP arm and the prompt's next token -int run_real(const std::string& gguf_path, const std::string& pack, const std::string& dump, const std::string& mtp_dump, - const std::vector& tokens) { - strata::GgufFile gguf(gguf_path); - core::ModelGeometry g; - std::string err; - if (!core::read_model_geometry(gguf, g, err)) die("geometry: " + err); - if (g.arch != core::ModelArch::Qwen35Moe) die("not a qwen35moe file"); - const int64_t N = g.n_embd; - // the trunk's output norm (F32 from the file), the head and embedding rows (shape only: native) - core::WeightTable wt; - int64_t n_vocab = 0; - for (const auto& t : gguf.tensors()) { - if (t.name != "output_norm.weight" && t.name != "output.weight" && t.name != "token_embd.weight") 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 = strata::tensor_payload_bytes(t); - if (t.name == "output_norm.weight") { - if (t.type != 0) die("output_norm.weight is not F32"); - r.kind = core::WeightKind::F32; - r.data = upload(gguf.tensor_data(t), r.bytes); - } else { - r.resident = false; - r.native_type = (int) t.type; - if (t.name == "output.weight") n_vocab = r.ne1; - } - wt.set(t.name, r); - } - core::NativeHead head; - if (!head.load({gguf_path}, N, n_vocab, err)) die("native head: " + err); - core::NativeEmbed embed; - if (!embed.load({gguf_path}, N, n_vocab, err)) die("native embedding: " + err); - core::set_native_embed(&embed); - const int n_tok = (int) tokens.size(), n_pos = n_tok - 1; - Dumps d, dm; - d.dir = dump; dm.dir = mtp_dump; - const std::vector& R_all = d.get("l_out-" + std::to_string(g.n_layers - 1)); - if (R_all.size() != (size_t) n_tok * N) die("l_out-" + std::to_string(g.n_layers - 1) + ": " + std::to_string(R_all.size()) + " floats for " + std::to_string(n_tok) + " tokens"); - float* R_dev = upload(R_all.data(), R_all.size() * 4); - const std::vector& ll = dm.get("result_output"); // llama.cpp's MTP logits, every position (the dumper asks for all) - if (ll.size() != (size_t) n_pos * n_vocab) die("the MTP dump's result_output holds " + std::to_string(ll.size() / (size_t) n_vocab) + " rows, expected " + std::to_string(n_pos)); - const std::vector& lh = dm.get("mtp_shared_head_norm"); - const int64_t max_cells = 256, max_t = 4; - core::SessionState ss; - void* sbase = nullptr; - ck(cudaMalloc(&sbase, core::session_bytes(g, max_cells, g.n_expert_used)), "session"); - if (core::session_init(g, max_cells, g.n_expert_used, sbase, ss) == 0) die("session_init failed"); - ss.k = g.n_expert_used; - core::MtpDrafter mtp; - if (!mtp.load(pack, g, ss, (int) max_t, err, 0)) die("mtp load: " + err); - float* window_R = nullptr; - ck(cudaMalloc((void**) &window_R, (size_t) max_t * N * 4), "window_R"); - if (!mtp.bind(wt, &head, window_R, err)) die("mtp bind: " + err); - std::printf("drafter from %s: experts %d/%d blob %lld B, %.0f MiB of VRAM; %d positions\n", pack.c_str(), mtp.expert_gu_type(), - mtp.expert_d_type(), (long long) mtp.expert_blob_bytes(), (double) mtp.vram_bytes() / 1048576.0, n_pos); - std::vector host; - Stat s_head, s_eh, s_attn, s_ffn; - std::vector logits; - int agree_llama = 0, agree_next = 0, llama_next = 0, n_next = 0; - std::printf(" %4s %8s %8s %8s %s\n", "pos", "engine", "llama", "next", "head-norm relL2"); - for (int k = 1; k <= n_pos; ++k) { - int32_t t1 = -1; - double hn_err = 0.0; - auto hook = [&](const char* s, const float* dev, int64_t n) { - const std::string sn(s); - if (sn != "mtp_shared_head_norm" && sn != "mtp_eh_proj" && sn != "mtp_attn_out" && sn != "mtp_ffn_out" && sn != "result_output") return; - host.resize((size_t) n); - ck(cudaMemcpy(host.data(), dev, (size_t) n * 4, cudaMemcpyDeviceToHost), "seam copy"); - if (sn == "result_output") { logits = host; return; } - const std::string stem = sn == "mtp_shared_head_norm" ? sn : sn + "-" + std::to_string(g.n_layers); - if (!dm.has(stem)) return; - Stat& st = sn == "mtp_shared_head_norm" ? s_head : sn == "mtp_eh_proj" ? s_eh : sn == "mtp_attn_out" ? s_attn : s_ffn; - const std::vector& o = dm.get(stem); - Stat one; - one.add(host.data(), o.data() + (size_t) (k - 1) * n, n); - st.add(host.data(), o.data() + (size_t) (k - 1) * n, n); - if (sn == "mtp_shared_head_norm") hn_err = one.worst_l2; - }; - if (!mtp.debug_row(R_dev + (size_t) (k - 1) * N, tokens[(size_t) k], k - 1, k - 1, core::MtpDrafter::DebugOpts{}, hook, &t1, err)) - die("debug_row at position " + std::to_string(k) + ": " + err); - const int lt = argmax(ll.data() + (size_t) (k - 1) * n_vocab, n_vocab); - const int nx = k + 1 < n_tok ? tokens[(size_t) k + 1] : -1; - agree_llama += t1 == lt; - if (nx >= 0) { ++n_next; agree_next += t1 == nx; llama_next += lt == nx; } - std::printf(" %4d %8d %8d %8d %s%s%s\n", k, t1, lt, nx, fmt(hn_err).c_str(), t1 == lt ? "" : " (differs from llama.cpp)", - nx >= 0 && t1 == nx ? " accepted" : ""); - } - std::printf("top-1 agreement with llama.cpp's MTP arm: %d of %d (%.1f%%)\n", agree_llama, n_pos, 100.0 * agree_llama / n_pos); - std::printf("top-1 equal to the prompt's next token (teacher-forced acceptance): engine %d of %d (%.1f%%), llama.cpp's MTP %d of %d (%.1f%%)\n", - agree_next, n_next, 100.0 * agree_next / std::max(1, n_next), llama_next, n_next, 100.0 * llama_next / std::max(1, n_next)); - std::printf("seams vs llama.cpp (relative L2 per row, worst over positions; relative L1 over all): eh_proj %s / %s, attn_out %s / %s, ffn_out %s / %s, shared_head_norm %s / %s\n", - fmt(s_eh.worst_l2).c_str(), fmt(s_eh.l1()).c_str(), fmt(s_attn.worst_l2).c_str(), fmt(s_attn.l1()).c_str(), - fmt(s_ffn.worst_l2).c_str(), fmt(s_ffn.l1()).c_str(), fmt(s_head.worst_l2).c_str(), fmt(s_head.l1()).c_str()); - (void) lh; - core::set_native_embed(nullptr); - cudaFree(window_R); - cudaFree(R_dev); - cudaFree(sbase); - return 0; -} -} // namespace - -int main(int argc, char** argv) { - if (argc < 2) { - std::fprintf(stderr, "usage: qwen36_mtp_test \n qwen36_mtp_test --real --gguf FILE --pack DIR --dump D --mtp-dump D_mtp --tokens t,t,...\n"); - return 2; - } - std::setvbuf(stdout, nullptr, _IOLBF, 0); // the lines reach a log as they are printed - int ndev = 0; - if (cudaGetDeviceCount(&ndev) != cudaSuccess || ndev < 1) { std::printf("qwen36_mtp_test: no CUDA device (skip)\n"); return 77; } - cudaDeviceProp p{}; - ck(cudaGetDeviceProperties(&p, 0), "device"); - std::printf("qwen36_mtp_test on %s (sm_%d%d)\n", p.name, p.major, p.minor); - if (std::strcmp(argv[1], "--real") == 0) { - std::string gguf, pack, dump, mtp_dump, toks; - for (int i = 2; i + 1 < argc; i += 2) { - const std::string a = argv[i]; - if (a == "--gguf") gguf = argv[i + 1]; - else if (a == "--pack") pack = argv[i + 1]; - else if (a == "--dump") dump = argv[i + 1]; - else if (a == "--mtp-dump") mtp_dump = argv[i + 1]; - else if (a == "--tokens") toks = argv[i + 1]; - else die("unknown option " + a); - } - if (gguf.empty() || pack.empty() || dump.empty() || mtp_dump.empty() || toks.empty()) die("--real needs --gguf, --pack, --dump, --mtp-dump and --tokens"); - std::vector tokens; - std::istringstream is(toks); - std::string t; - while (std::getline(is, t, ',')) tokens.push_back((int32_t) std::atoi(t.c_str())); - return run_real(gguf, pack, dump, mtp_dump, tokens); - } - const int rc = run_synthetic(argv[1]); - std::printf("%s\n", rc == 0 ? "qwen36_mtp_test: all checks passed" : rc == 77 ? "qwen36_mtp_test: skipped" : "qwen36_mtp_test: FAILURES"); - return rc; -} diff --git a/tests/cuda/qwen36_verify_test.cpp b/tests/cuda/qwen36_verify_test.cpp deleted file mode 100644 index 45de120..0000000 --- a/tests/cuda/qwen36_verify_test.cpp +++ /dev/null @@ -1,511 +0,0 @@ -// tests/cuda/qwen36_verify_test.cpp - the verify window on a qwen35moe NATIVE PACK, held to the oracle and to the -// single-token path (Qwen3.6 port, step 4; docs/qwen36-port/step4-runner.md). -// -// qwen36_verify_test (tests/python/qwen36_runner_fixture.py: full4.gguf, pack/, o8, o11, o40) -// -// The step-3 review's HIGH finding: no test drove `Verifier` on a qwen35moe geometry, and the window's hand-written -// attention shapes would have exited on the first attention layer. This drives it the way `strata generate` does on -// the pack (the load order of docs/qwen36-port/step4-pack.md section 6, `check_all` included; the session at hc = 1 -// with no PLE and no indexer; an expert cache holding every expert of the 4 x 16 fixture), and holds -// -// 1. one window of 8 tokens ("hello wo"): every row's residual after every layer (the stage hand-off of a verifier -// ending at that layer) against the oracle's `l_out-N`, and every row's head logits against `result_output_all`; -// 2. the same rows from eight one-token windows (commit after each): BIT FOR BIT the 8-row window's (verify.hpp's -// discipline: row t of a T-row window is the single-token path after token t); -// 3. two windows of 8 + 3 ("hello world", a commit between them) against the 11-token dumps; -// 4. the 40-token sequence one token per window (the oracle's `base_ar` case through the decode path) against -// `result_output_all` and `l_out-3` at every position, with the engine's argmax against the oracle's. -// -// Tolerances: the oracle is F32 weights x F32 activations; the engine runs Q8_0 projections (FP16 dequantized GEMV -// with q8_1 activations) and Q8_0 experts on int8 dot products, so the per-position gates are the prompt-path -// harness's measured classes with margin (step3-prefill.md 2.2): `l_out` 1e-2 relative L2 per row, the logits 2e-2; -// the window-vs-single-token comparison is exact. Exit 77 without a CUDA device or when the fixture was not written -// (no numpy), 1 on a failure. -#include "strata/artifact/gguf_reader.hpp" -#include "strata/artifact/gguf_split.hpp" -#include "strata/core/expert_cache.hpp" -#include "strata/core/expert_source.hpp" -#include "strata/core/layer.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/session.hpp" -#include "strata/core/verify.hpp" -#include "strata/core/weights.hpp" -#include "strata/kernels/cpu/expert_layout.hpp" -#include "strata/kernels/native_gdn.hpp" -#include "strata/kernels/native_moe.hpp" -#include "strata/kernels/native_qsa.hpp" -#include "strata/kernels/native_qsa_indexer.hpp" -#include "strata/kernels/native_rope.hpp" -#include "strata/kernels/native_router.hpp" -#include "strata/kernels/rope_scaling.hpp" -#include "strata/kernels/shared_expert.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fs = std::filesystem; -namespace core = strata::core; - -namespace { -int g_fail = 0; -void check(bool ok, const std::string& what) { - std::printf(" %-108s %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; } -[[noreturn]] void die(const std::string& what) { - std::fprintf(stderr, "qwen36_verify_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)); } - -// ---- the oracle's dumps: .f32 in C order, shapes from manifest.txt (GGUF order, ne0 fastest) -struct Dumps { - fs::path dir; - std::map> ne; - 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 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(); - } - std::vector f(const std::string& stem) const { - std::ifstream in(dir / (stem + ".f32"), std::ios::binary); - if (!in) die("missing dump " + (dir / (stem + ".f32")).string()); - in.seekg(0, std::ios::end); - const std::streamoff n = in.tellg(); - in.seekg(0); - std::vector v((size_t) n / 4); - in.read((char*) v.data(), n); - return v; - } -}; -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); -} -size_t argmax(const float* v, size_t n) { return (size_t) (std::max_element(v, v + n) - v); } -std::vector down(const float* dev, size_t n) { - std::vector h(n); - ck(cudaMemcpy(h.data(), dev, n * 4, cudaMemcpyDeviceToHost), "download"); - return h; -} - -// the CPU pool for a window: every expert of the fixture is resident in VRAM, so the pool has nothing to compute -// (the window's own hit path serves them); zeroing keeps a stray call from reading uninitialised rows -int64_t g_n_embd = 0; -void pool_none(void*, const float*, const int32_t*, int64_t n_tok, int64_t k, float* out, int64_t) { - std::memset(out, 0, (size_t) (n_tok * k) * (size_t) g_n_embd * sizeof(float)); -} - -/// The engine's loads, in generate.cpp's order after the plan (docs/qwen36-port/step4-pack.md section 6). -struct Engine { - std::string gguf, pack; - std::vector shards; - core::ModelGeometry g; - core::WeightTable wt; - void* arena = nullptr; - core::NativeDense dense; - core::NativeHead head; - core::NativeEmbed embed; - std::vector> profile; - int64_t n_vocab = 0; - // the experts: the GGUF in place through the engine's arena source, every blob in a VRAM slot - core::ArenaExpertSource src; - core::ExpertCache cache; - std::vector host_res; - int32_t* d_res = nullptr; - core::VerifyHits hits; - - void load(const std::string& gguf_in, const std::string& pack_in) { - gguf = gguf_in; - pack = pack_in; - std::string err; - if (!core::read_model_geometry(gguf, g, err)) die("read_model_geometry: " + err); - if (g.arch != core::ModelArch::Qwen35Moe) die("the fixture is not a qwen35moe file"); - g_n_embd = g.n_embd; - shards = strata::gguf_split_paths(gguf); - { - const strata::GgufModel model(shards); - if (!core::check_model_tensor_forms(model, g, err)) die("check_model_tensor_forms: " + err); - } - if (!strata::kernels::cpu::expert_layout_load(pack, g.n_layers, g.n_expert, g.n_embd, g.n_ff, err)) - die("expert_layout_load: " + err); - const auto& lay = strata::kernels::cpu::expert_layout(); - if (!lay.native) die("not a native pack"); - std::set skip; - if (!core::NativeDense::served_names(shards, false, skip, err)) die("served_names: " + err); - skip.insert("output.weight"); - skip.insert("token_embd.weight"); - uint64_t pool = 0; - if (!core::WeightTable::pool_bytes(pack, pool, err, &skip)) die("pool_bytes: " + err); - ck(cudaMalloc(&arena, pool), "arena"); - if (!wt.load(pack, arena, pool, err, &skip)) die("WeightTable::load: " + err); - if (!dense.load(shards, wt, err, false, 0, g.n_layers)) die("NativeDense::load: " + err); - if (!core::check_all(wt, g, err)) die("check_all: " + err); - const core::WeightRef* wo = wt.find("output.weight"); - if (wo == nullptr) die("output.weight missing"); - n_vocab = wo->ne1; - if (!head.load(shards, g.n_embd, n_vocab, err)) die("NativeHead::load: " + err); - if (!embed.load(shards, g.n_embd, n_vocab, err)) die("NativeEmbed::load: " + err); - core::set_native_embed(&embed); - int64_t slots = 0; - if (!core::read_expert_profile(pack + "/expert-profile.bin", g.n_layers, g.n_expert, profile, slots, err)) - die("read_expert_profile: " + err); - std::printf("loaded %s with %s: %lld layers, n_embd %lld, %lld experts top-%lld, n_vocab %lld, arena %llu B, " - "%zu native projections, head %s, embedding %s, profile %zu pairs\n", gguf.c_str(), pack.c_str(), - (long long) g.n_layers, (long long) g.n_embd, (long long) g.n_expert, (long long) g.n_expert_used, - (long long) n_vocab, (unsigned long long) pool, dense.tensor_count(), - strata::ggml_type_name((uint32_t) head.type()), strata::ggml_type_name((uint32_t) embed.type()), - profile.size()); - // the decode configuration the window reproduces (generate.cpp's --native defaults) - core::layer_set_native_bf16(true); - core::layer_set_fused_gdn(true); - core::layer_set_fast_attn(true); - core::layer_set_fast_select(true); - core::layer_set_fused_gr(false); // hc = 1: no hyper-connection read exists to fuse - strata::kernels::native_gdn_set_enabled(true); - strata::kernels::native_router_set_enabled(true); - strata::kernels::native_qsa_set_enabled(true); - strata::kernels::native_qsa_indexer_set_enabled(true); - strata::kernels::native_rope_set_enabled(true); - strata::kernels::native_moe_combine_set_enabled(true); - strata::kernels::shared_expert_set_native_bf16(true); - strata::kernels::RopeScaling rope; - rope.freq_base = g.rope_base; - strata::kernels::rope_scaling_set(rope); - core::qsa_set_kv_resident(0); - std::string why; - if (!core::layer_verify_compatible(g, why)) die("layer_verify_compatible: " + why); - // the experts: every (layer, expert) pair in its own slot, from the GGUF in place - src.set_gguf(gguf); - if (!src.open(pack, g.n_layers, g.n_expert, 2, err)) die("ArenaExpertSource::open: " + err); - const int64_t n_pairs = g.n_layers * g.n_expert; - if (!cache.open(n_pairs, g.n_layers, g.n_expert, (int64_t) lay.max_blob, err)) die("ExpertCache::open: " + err); - host_res.assign((size_t) n_pairs, core::kNotResident); - for (int64_t l = 0; l < g.n_layers; ++l) - for (int64_t e = 0; e < g.n_expert; ++e) { - const int32_t slot = cache.admit(l, e); - if (slot == core::kNotResident) die("the cache refused a slot"); - const uint8_t* b = src.blob(l, e); - if (b == nullptr || !cache.fill_slot_blocking(slot, b, err, (int64_t) lay.blob_bytes(l))) - die("fill_slot: " + err); - host_res[(size_t) (l * g.n_expert + e)] = slot; - } - if (!cache.verify_slot(cache.slot_of(0, 0), src.blob(0, 0), err, (int64_t) lay.blob_bytes(0))) - die("verify_slot: " + err); - ck(cudaMalloc((void**) &d_res, host_res.size() * 4), "d_res"); - ck(cudaMemcpy(d_res, host_res.data(), host_res.size() * 4, cudaMemcpyHostToDevice), "d_res upload"); - hits.d_res = d_res; - hits.h_res = host_res.data(); - hits.cache_base = cache.device_slot(0); - hits.blob = (int64_t) lay.max_blob; - hits.slot_off = cache.slot_offsets(); - hits.n_slots = cache.slots(); - std::printf("expert cache: %lld slots of %llu B, every expert resident (slot 0 verified against the file)\n", - (long long) cache.slots(), (unsigned long long) lay.max_blob); - } -}; - -/// A session and a verifier over layers [lb, le) of it. lb > 0: the rows' residuals come from the hand-in (the -/// oracle's `l_out-(lb-1)`, teacher forcing a layer); le < n_layers: the residual after layer le - 1 lands in the -/// hand-out, per row; le = n_layers: the whole tail with the head. -struct Window { - const Engine& en; - core::SessionState ss{}; - void* sbuf = nullptr; - float* in_h = nullptr; // mapped host hand-in and its device alias - float* in_d = nullptr; - float* out_h = nullptr; // mapped host hand-out and its device alias - float* out_d = nullptr; - int64_t lb = 0, le = 0; - int max_t = 0; - core::Verifier ver; - Window(const Engine& e, int64_t layer_begin, int64_t layer_end, int max_tokens, int64_t max_cells = 64) - : en(e), lb(layer_begin), le(layer_end), max_t(max_tokens) { - std::string err; - const int64_t K = en.g.n_expert_used; - ck(cudaMalloc(&sbuf, core::session_bytes(en.g, max_cells, K, 0, -1)), "session"); - if (core::session_init(en.g, max_cells, K, sbuf, ss, 0, -1) == 0) die("session_init failed"); - const size_t hb = (size_t) max_t * (size_t) core::Verifier::handoff_floats(en.g) * sizeof(float); - if (lb > 0) { - ck(cudaHostAlloc((void**) &in_h, hb, cudaHostAllocMapped | cudaHostAllocPortable), "hand-in"); - ck(cudaHostGetDevicePointer((void**) &in_d, in_h, 0), "hand-in device pointer"); - std::memset(in_h, 0, hb); - } - if (le < en.g.n_layers) { - ck(cudaHostAlloc((void**) &out_h, hb, cudaHostAllocMapped | cudaHostAllocPortable), "hand-out"); - ck(cudaHostGetDevicePointer((void**) &out_d, out_h, 0), "hand-out device pointer"); - std::memset(out_h, 0, hb); - } - if (lb > 0 || le < en.g.n_layers) ver.set_stage(lb, le, in_d, out_d); - if (!ver.init(en.wt, en.g, ss, en.hits, le == en.g.n_layers ? &en.head : nullptr, max_t, err)) - die("Verifier::init (layers " + std::to_string(lb) + ".." + std::to_string(le) + "): " + err); - } - /// teacher forcing: the T rows' residuals before layer lb (the hand-in holds every row's R first, then every - /// row's pending write and inject, both zero: the plain block has no pending write) - void force_in(const float* rows, int T) { - std::memcpy(in_h, rows, (size_t) T * (size_t) en.g.n_embd * sizeof(float)); - } - bool run(int T, const int32_t* toks, int64_t pos0, int32_t* out, std::string& err) { - return ver.run(T, toks, pos0, &pool_none, nullptr, out, err); - } - /// row t's residual after the last layer this window runs - std::vector residual(int t) const { - const int64_t N = en.g.n_embd; - if (le < en.g.n_layers) { - ck(cudaDeviceSynchronize(), "hand-off sync"); - const float* r = out_h + (size_t) t * (size_t) en.g.hc * (size_t) N; - return std::vector(r, r + N); - } - return down(ver.final_R(t), (size_t) N); - } - std::vector logits(int t) const { - std::vector row((size_t) en.n_vocab); - if (!ver.copy_logits(t, row.data())) die("copy_logits failed"); - return row; - } -}; - -/// the worst relative L2 over rows [0, T) of `got` (row stride n) against rows p0.. of `ref` -double worst_rows(const std::vector>& got, const std::vector& ref, int p0, size_t n) { - double w = 0; - for (size_t t = 0; t < got.size(); ++t) w = std::max(w, rel_l2(got[t].data(), ref.data() + ((size_t) p0 + t) * n, n)); - return w; -} -int argmax_equal(const std::vector>& got, const std::vector& ref, int p0, size_t n, std::string& miss) { - int eq = 0; - for (size_t t = 0; t < got.size(); ++t) { - const bool same = argmax(got[t].data(), n) == argmax(ref.data() + ((size_t) p0 + t) * n, n); - eq += same; - if (!same) miss += (miss.empty() ? "" : ", ") + std::to_string(p0 + (int) t); - } - return eq; -} - -} // namespace - -int main(int argc, char** argv) { - if (argc < 2) { std::fprintf(stderr, "usage: qwen36_verify_test \n"); return 2; } - const fs::path fx = argv[1]; - if (fs::exists(fx / "SKIP") || !fs::exists(fx / "full4.gguf") || !fs::exists(fx / "pack" / "index.txt") || - !fs::exists(fx / "o8" / "manifest.txt")) { - std::fprintf(stderr, "qwen36_verify_test: no fixture in %s (tests/python/qwen36_runner_fixture.py): skipped\n", argv[1]); - return 77; - } - int devices = 0; - if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) { - std::fprintf(stderr, "qwen36_verify_test: no CUDA device: skipped\n"); - return 77; - } - // the F32 oracle (the reference the real file was cross-checked with) and its Q8 mode (the activations rounded - // to Q8 before every quantized matmul, as ggml and this engine's int8 paths do): the policy's reference for a - // path that rounds (oracle-crosscheck.md, "Tolerance policy", items 3 and 4) - Dumps o8, o8q, o11, o11q, o40, o40q; - if (!o8.open(fx / "o8") || !o8q.open(fx / "o8_q8") || !o11.open(fx / "o11") || !o11q.open(fx / "o11_q8") || - !o40.open(fx / "o40") || !o40q.open(fx / "o40_q8")) - die("the oracle dumps are incomplete (o8, o8_q8, o11, o11_q8, o40, o40_q8)"); - Engine en; - en.load((fx / "full4.gguf").string(), (fx / "pack").string()); - const int64_t L = en.g.n_layers, N = en.g.n_embd, V = en.n_vocab; - // the gates, against the Q8 oracle: one layer with its input forced is the policy's per-layer protocol (the Q8 - // column's l_out class 1.4e-3 max on the real file; this fixture's 16-expert MoE spreads more: 1e-2 is 4x its - // measured worst); a whole sequence accumulates over the 4 layers and the recurrence (5e-2); the argmax must agree - const double kForced = 1.5e-2, kAccum = 5e-2; - std::string err, miss; - const std::string lo_last = "l_out-" + std::to_string(L - 1); - - // ================================ 1. one window of 8 tokens, every layer, every row ================================ - std::printf("1. one window of 8 tokens: the residual after every layer per row, against the oracle (F32 | Q8)\n"); - const std::vector t8 = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o'}; - std::vector out8(8); - std::vector> win_R(8), win_logits(8), rows(8); - std::printf(" 1a. the layers from the embedding (accumulated):\n"); - for (int64_t l = 0; l < L; ++l) { - Window w(en, 0, l + 1, 8); - if (!w.run(8, t8.data(), 0, out8.data(), err)) { check(false, "window of 8 through layers 0.." + std::to_string(l) + ": " + err); continue; } - ck(cudaDeviceSynchronize(), "window sync"); - for (int t = 0; t < 8; ++t) rows[(size_t) t] = w.residual(t); - const std::string lo = "l_out-" + std::to_string(l); - const double e32 = worst_rows(rows, o8.f(lo), 0, (size_t) N), eq8 = worst_rows(rows, o8q.f(lo), 0, (size_t) N); - check(eq8 <= kAccum, lo + " per row: worst rel L2 F32 " + fmt(e32) + " | Q8 " + fmt(eq8) + " (Q8 <= " + fmt(kAccum) + ")"); - if (l == L - 1) { win_R = rows; for (int t = 0; t < 8; ++t) win_logits[(size_t) t] = w.logits(t); } - } - // The per-layer protocol (oracle-crosscheck.md "Tolerance policy", item 2): start each layer from the oracle's - // own l_out of the layer before, so each seam's error is that layer's own. The reference must match the forced - // input: a path that rounds activations to Q8 is forced from, and compared to, the Q8 oracle. - std::printf(" 1b. each layer alone, its input rows forced to the Q8 oracle's l_out of the layer before:\n"); - for (int64_t l = 1; l < L; ++l) { - Window w(en, l, l + 1, 8); - const std::vector prevq = o8q.f("l_out-" + std::to_string(l - 1)); - w.force_in(prevq.data(), 8); - if (!w.run(8, t8.data(), 0, out8.data(), err)) { check(false, "layer " + std::to_string(l) + " forced: " + err); continue; } - ck(cudaDeviceSynchronize(), "window sync"); - for (int t = 0; t < 8; ++t) rows[(size_t) t] = w.residual(t); - const std::string lo = "l_out-" + std::to_string(l); - const double eq8 = worst_rows(rows, o8q.f(lo), 0, (size_t) N); - check(eq8 <= kForced, lo + " forced from the Q8 oracle, per row: worst rel L2 " + fmt(eq8) + " (<= " + fmt(kForced) + ")"); - } - { - const std::vector ro = o8.f("result_output_all"), roq = o8q.f("result_output_all"); - const double e32 = worst_rows(win_logits, ro, 0, (size_t) V), eq8 = worst_rows(win_logits, roq, 0, (size_t) V); - check(eq8 <= kAccum, "result_output_all per row: worst rel L2 F32 " + fmt(e32) + " | Q8 " + fmt(eq8) + " (Q8 <= " + fmt(kAccum) + ")"); - miss.clear(); - const int eq = argmax_equal(win_logits, roq, 0, (size_t) V, miss); - std::string m32; - const int eq32 = argmax_equal(win_logits, ro, 0, (size_t) V, m32); - check(eq == 8, "argmax per row equals the Q8 oracle's: " + std::to_string(eq) + " of 8" + (miss.empty() ? "" : " (differs at " + miss + ")") + - "; the F32 oracle's: " + std::to_string(eq32) + " of 8"); - for (int t = 0; t < 8; ++t) - if ((size_t) out8[(size_t) t] != argmax(win_logits[(size_t) t].data(), (size_t) V)) - check(false, "row " + std::to_string(t) + ": the window's pick is not its own logits' argmax"); - } - - // ================================ 2. the single-token path: eight windows of one token ================================ - std::printf("2. eight one-token windows (commit after each) against the 8-row window: bit for bit\n"); - { - Window one(en, 0, L, 2); - int32_t out1 = 0; - double worst_R = 0, worst_lg = 0; - bool bit_R = true, bit_lg = true; - for (int t = 0; t < 8; ++t) { - if (!one.run(1, &t8[(size_t) t], t, &out1, err)) { check(false, "one-token window at " + std::to_string(t) + ": " + err); break; } - ck(cudaDeviceSynchronize(), "sync"); - const std::vector r = one.residual(0), lg = one.logits(0); - bit_R = bit_R && std::memcmp(r.data(), win_R[(size_t) t].data(), (size_t) N * 4) == 0; - bit_lg = bit_lg && std::memcmp(lg.data(), win_logits[(size_t) t].data(), (size_t) V * 4) == 0; - worst_R = std::max(worst_R, rel_l2(r.data(), win_R[(size_t) t].data(), (size_t) N)); - worst_lg = std::max(worst_lg, rel_l2(lg.data(), win_logits[(size_t) t].data(), (size_t) V)); - if (!one.ver.commit(1, err)) die("commit: " + err); - } - if (!one.ver.wait_commit(err)) die("wait_commit: " + err); - check(bit_R, "residual after layer " + std::to_string(L - 1) + ": the single-token rows equal the window's rows bitwise (rel L2 " + fmt(worst_R) + ")"); - check(bit_lg, "head logits: the single-token rows equal the window's rows bitwise (rel L2 " + fmt(worst_lg) + ")"); - } - - // ================================ 3. 8 + 3: two windows with a commit between them ================================ - std::printf("3. \"hello world\": a window of 8, commit, a window of 3 at position 8, against the 11-token dumps\n"); - { - const std::vector t11 = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'}; - Window w(en, 0, L, 8); - std::vector out(8); - std::vector> R11, lg11; - if (!w.run(8, t11.data(), 0, out.data(), err)) die("window 1: " + err); - ck(cudaDeviceSynchronize(), "sync"); - for (int t = 0; t < 8; ++t) { R11.push_back(w.residual(t)); lg11.push_back(w.logits(t)); } - if (!w.ver.commit(8, err)) die("commit 8: " + err); - if (!w.run(3, t11.data() + 8, 8, out.data(), err)) die("window 2: " + err); - ck(cudaDeviceSynchronize(), "sync"); - for (int t = 0; t < 3; ++t) { R11.push_back(w.residual(t)); lg11.push_back(w.logits(t)); } - if (!w.ver.commit(3, err) || !w.ver.wait_commit(err)) die("commit 3: " + err); - const double r32 = worst_rows(R11, o11.f(lo_last), 0, (size_t) N), rq8 = worst_rows(R11, o11q.f(lo_last), 0, (size_t) N); - const double l32 = worst_rows(lg11, o11.f("result_output_all"), 0, (size_t) V), lq8 = worst_rows(lg11, o11q.f("result_output_all"), 0, (size_t) V); - check(rq8 <= kAccum, lo_last + " per position (11): worst rel L2 F32 " + fmt(r32) + " | Q8 " + fmt(rq8) + " (Q8 <= " + fmt(kAccum) + ")"); - check(lq8 <= kAccum, "result_output_all per position (11): worst rel L2 F32 " + fmt(l32) + " | Q8 " + fmt(lq8) + " (Q8 <= " + fmt(kAccum) + ")"); - miss.clear(); - const int eq = argmax_equal(lg11, o11q.f("result_output_all"), 0, (size_t) V, miss); - std::string m32; - const int eq32 = argmax_equal(lg11, o11.f("result_output_all"), 0, (size_t) V, m32); - check(eq == 11, "argmax per position equals the Q8 oracle's: " + std::to_string(eq) + " of 11" + (miss.empty() ? "" : " (differs at " + miss + ")") + - "; the F32 oracle's: " + std::to_string(eq32) + " of 11"); - } - - // ================================ 4. 40 tokens, one per window: the autoregressive case ================================ - std::printf("4. 40 tokens one per window (the oracle's base_ar shape) against result_output_all and %s at every position\n", lo_last.c_str()); - { - const std::string text = "the quick brown fox jumps over the lazy "; - std::vector t40(text.begin(), text.end()); - if (t40.size() != 40) die("the 40-token text"); - Window w(en, 0, L, 2); - int32_t out = 0; - std::vector> R40, lg40; - const std::vector lo = o40.f(lo_last), ro = o40.f("result_output_all"), loq = o40q.f(lo_last), roq = o40q.f("result_output_all"); - std::printf(" pos: rel L2 of %s and the logits against the F32 oracle | the Q8 oracle\n", lo_last.c_str()); - for (int t = 0; t < 40; ++t) { - if (!w.run(1, &t40[(size_t) t], t, &out, err)) die("window at " + std::to_string(t) + ": " + err); - ck(cudaDeviceSynchronize(), "sync"); - R40.push_back(w.residual(0)); - lg40.push_back(w.logits(0)); - const float* r = R40.back().data(); - const float* lg = lg40.back().data(); - const bool same = argmax(lg, (size_t) V) == argmax(roq.data() + (size_t) t * V, (size_t) V); - std::printf(" %2d: %s %s | %s %s%s\n", t, fmt(rel_l2(r, lo.data() + (size_t) t * N, (size_t) N)).c_str(), - fmt(rel_l2(lg, ro.data() + (size_t) t * V, (size_t) V)).c_str(), - fmt(rel_l2(r, loq.data() + (size_t) t * N, (size_t) N)).c_str(), - fmt(rel_l2(lg, roq.data() + (size_t) t * V, (size_t) V)).c_str(), - same ? "" : " (argmax differs from the Q8 oracle)"); - if (!w.ver.commit(1, err)) die("commit: " + err); - } - if (!w.ver.wait_commit(err)) die("wait_commit: " + err); - const double r32 = worst_rows(R40, lo, 0, (size_t) N), rq8 = worst_rows(R40, loq, 0, (size_t) N); - const double l32 = worst_rows(lg40, ro, 0, (size_t) V), lq8 = worst_rows(lg40, roq, 0, (size_t) V); - check(rq8 <= kAccum, lo_last + " per position (40): worst rel L2 F32 " + fmt(r32) + " | Q8 " + fmt(rq8) + " (Q8 <= " + fmt(kAccum) + ")"); - check(lq8 <= kAccum, "result_output_all per position (40): worst rel L2 F32 " + fmt(l32) + " | Q8 " + fmt(lq8) + " (Q8 <= " + fmt(kAccum) + ")"); - miss.clear(); - const int eq = argmax_equal(lg40, roq, 0, (size_t) V, miss); - std::string m32; - const int eq32 = argmax_equal(lg40, ro, 0, (size_t) V, m32); - // A near tie cannot discriminate the engine: a position where the two references disagree with each other - // (the runner check, qwen36_runner_check.py, excludes the same positions), or where the Q8 oracle's top-two - // margin, (top1 - top2) / |top1|, is below the engine row's own rel L2 error against that oracle (a flip - // inside the measured error; on the 4090 position 4 of this fixture flips between runs with a 0.4% margin - // under a 1.4% row error). The gate runs over the other positions and reports the ties with their margins. - std::string ties; - int unambiguous = 0, eq_un = 0; - for (int t = 0; t < 40; ++t) { - const float* rq = roq.data() + (size_t) t * V; - const size_t a32 = argmax(ro.data() + (size_t) t * V, (size_t) V), aq8 = argmax(rq, (size_t) V); - float top1 = rq[aq8], top2 = -INFINITY; - for (size_t i = 0; i < (size_t) V; ++i) if (i != aq8 && rq[i] > top2) top2 = rq[i]; - const double margin = (top1 - top2) / std::max(1e-30, (double) std::fabs(top1)); - const double row_err = rel_l2(lg40[(size_t) t].data(), rq, (size_t) V); - if (a32 != aq8 || margin < row_err) { - ties += (ties.empty() ? "" : ", ") + std::to_string(t) + (a32 != aq8 ? " (oracles disagree" : " (margin ") + - (a32 != aq8 ? std::string() : fmt(margin) + " < row error " + fmt(row_err)) + ")"; - continue; - } - ++unambiguous; - eq_un += argmax(lg40[(size_t) t].data(), (size_t) V) == aq8; - } - check(eq_un == unambiguous, "argmax per position equals the Q8 oracle's at " + std::to_string(eq_un) + " of " + std::to_string(unambiguous) + - " unambiguous positions (all 40: Q8 " + std::to_string(eq) + (miss.empty() ? "" : ", differs at " + miss) + - "; F32 " + std::to_string(eq32) + (m32.empty() ? "" : ", differs at " + m32) + ")" + - (ties.empty() ? "" : "; near ties, not gated: [" + ties + "]")); - } - - std::printf("%s: %d failure(s)\n", g_fail == 0 ? "PASS" : "FAIL", g_fail); - return g_fail == 0 ? 0 : 1; -} diff --git a/tests/data/native_experts/coder-iq1_m.txt b/tests/data/native_experts/coder-iq1_m.txt deleted file mode 100644 index bf0c408..0000000 --- a/tests/data/native_experts/coder-iq1_m.txt +++ /dev/null @@ -1,49 +0,0 @@ -# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] (n_expert 256, total 25146163200; absolute offsets in Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00001-of-00002.gguf, or in the named shard beside it) -0 18 20 0 2176000 1150562336 1313362976 913711136 -1 22 42 557056000 1510400 1664626592 1801161632 1545740192 -2 22 20 943718400 1971200 2308902688 2445488928 2072051488 -3 22 20 1448345600 1971200 2885763232 3022298272 2648912032 -4 22 20 1952972800 1971200 3458564256 3595572896 3221713056 -5 22 20 2457600000 1971200 4038269472 4174804512 3801418272 -6 22 20 2962227200 1971200 4613172128 4750180768 4376320928 -7 18 20 3466854400 2176000 5193708832 5356458272 4956857632 -8 22 42 4023910400 1510400 5696376096 5832911136 5577489696 -9 22 20 4410572800 1971200 6271347872 6407934112 6034496672 -10 22 42 4915200000 1510400 6732983328 6869569568 6614096928 -11 22 20 5301862400 1971200 7314285472 7450871712 7077434272 -12 18 42 5806489600 1715200 7761567136 7924790176 7642680736 -13 22 42 6245580800 1510400 8269195552 8405781792 8150309152 -14 18 20 6632243200 2176000 8850188448 9012937888 8613337248 -15 22 20 7189299200 1971200 9478952992 9615961632 9242101792 -16 18 20 7693926400 2176000 10047629856 10210430496 9810778656 -17 21 20 8250982400 2329600 10683191712 10865601952 10446340512 -18 18 20 8847360000 2176000 11353477408 11516482848 11116626208 -19 22 20 9404416000 1971200 11989461152 12126469792 11752609952 -20 18 42 9909043200 1715200 12445193376 12607942816 12326306976 -21 21 42 10348134400 1868800 12962739232 13145200672 12843852832 -22 18 20 10826547200 2176000 13631427488 13794650528 13394576288 -23 22 20 11383603200 1971200 14269635872 14406426912 14032784672 -24 22 20 11888230400 1971200 14842897696 14979432736 14606046496 -25 21 20 12392857600 2329600 15426184352 15608594592 15189333152 -26 22 20 12989235200 1971200 16097957408 16234966048 15861106208 -27 21 20 13493862400 2329600 16682121632 16864531872 16445270432 -28 21 20 14090240000 2329600 17346621856 17529505696 17109770656 -29 21 20 14686617600 2329600 18018868512 18201534752 17782017312 -30 18 42 15282995200 1715200 18571885728 18734635168 18452999328 -31 18 20 15722086400 2176000 19213849632 19376599072 18976998432 -32 22 20 16279142400 1971200 19837195296 19974203936 19600344096 -33 18 20 16783769600 2176000 20413173152 20575922592 20176321952 -34 22 20 17340825600 1971200 21040655648 21177241888 20803804448 -35 21 20 17845452800 2329600 21630446752 21812856992 21393595552 -36 22 42 18441830400 1510400 22173400736 22310409376 22054514336 -37 18 20 18828492800 2176000 22753323552 22916546592 22516472352 -38 18 20 19385548800 2176000 23383942048 23546742688 23147090848 -39 22 20 19942604800 1971200 24025905952 24162492192 23789054752 -40 21 20 20447232000 2329600 24598758176 24781424416 24361906976 -41 18 20 21043609600 2176000 25262981792 25425782432 25026130592 -42 18 20 21600665600 2176000 25890515488 26053738528 25653664288 -43 18 20 22157721600 2176000 26532901792 26696124832 26296050592 -44 21 20 22714777600 2329600 27151490976 27333952416 26914639776 -45 21 20 23311155200 2329600 27818796832 28001258272 27581945632 -46 18 20 23907532800 2176000 28488532128 28651332768 28251680928 -47 23 20 24464588800 2662400 29129699872 29354759712 28892029472 diff --git a/tests/data/native_experts/iq2_xs.txt b/tests/data/native_experts/iq2_xs.txt deleted file mode 100644 index 61c34b8..0000000 --- a/tests/data/native_experts/iq2_xs.txt +++ /dev/null @@ -1,49 +0,0 @@ -# strata native experts v2: layer gu_type d_type offset blob_bytes gate_off up_off down_off (n_expert 512, total 35454976000; the last three are absolute offsets in Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf) -0 22 42 0 1510400 957139232 1229167392 720288032 -1 16 42 773324800 1305600 1791743648 2011983008 1554892448 -2 22 42 1441792000 1510400 2589468704 2861663264 2352617504 -3 22 42 2215116800 1510400 3429617568 3701812128 3191947168 -4 16 42 2988441600 1305600 4258654112 4478419872 4021802912 -5 22 42 3656908800 1510400 4988400928 5260595488 4751549728 -6 22 42 4430233600 1510400 5824781984 6096976544 5588391584 -7 22 42 5203558400 1510400 6665627168 6938295328 6429236768 -8 29 42 5976883200 1177600 7496734752 7683732512 7259883552 -9 16 42 6579814400 1305600 8161931168 8381530528 7924260768 -10 16 42 7248281600 1305600 8893109024 9112874784 8656257824 -11 16 42 7916748800 1305600 9628172448 9847938208 9391782048 -12 22 42 8585216000 1510400 10354422432 10627090592 10117571232 -13 29 42 9358540800 1177600 11191917088 11378748448 10954246688 -14 16 42 9961472000 1305600 11856780704 12076546464 11619110304 -15 22 42 10629939200 1510400 12596884768 12868912928 12360033568 -16 22 42 11403264000 1510400 13428645152 13701313312 13190974752 -17 22 42 12176588800 1510400 14264363168 14536557728 14027511968 -18 16 42 12949913600 1305600 15100731424 15320330784 14863880224 -19 16 42 13618380800 1305600 15836089248 16055855008 15599238048 -20 22 42 14286848000 1510400 16562518432 16834712992 16324848032 -21 22 42 15060172800 1510400 17398108448 17670303008 17160438048 -22 22 42 15833497600 1510400 18230654624 18502849184 17994264224 -23 22 42 16606822400 1510400 19071581728 19343609888 18834730528 -24 22 42 17380147200 1510400 19906595872 20178790432 19669744672 -25 22 42 18153472000 1510400 20745913248 21017941408 20509062048 -26 22 42 18926796800 1510400 21580517664 21852712224 21343666464 -27 16 42 19700121600 1305600 22420899488 22641138848 22184048288 -28 22 42 20368588800 1510400 23146983072 23419011232 22910131872 -29 16 42 21141913600 1305600 23983658528 24203424288 23746807328 -30 16 42 21810380800 1305600 24713110944 24932876704 24476720544 -31 22 42 22478848000 1510400 25449180448 25721375008 25212329248 -32 22 42 23252172800 1510400 26279648032 26551842592 26042796832 -33 22 42 24025497600 1510400 27114892448 27387087008 26878041248 -34 22 42 24798822400 1510400 27955807264 28228001824 27718956064 -35 22 42 25572147200 1510400 28793160608 29065355168 28556309408 -36 22 42 26345472000 1510400 29623794592 29896462752 29386943392 -37 29 42 27118796800 1177600 30459512608 30646510368 30222661408 -38 22 42 27721728000 1510400 31125320864 31397515424 30888469664 -39 22 42 28495052800 1510400 31966247968 32238442528 31729396768 -40 22 42 29268377600 1510400 32794219552 33066414112 32557368352 -41 22 42 30041702400 1510400 33628823968 33901018528 33391972768 -42 22 42 30815027200 1510400 34464068384 34736736544 34227217184 -43 22 42 31588352000 1510400 35305090208 35577118368 35068239008 -44 22 42 32361676800 1510400 36135557792 36408225952 35898706592 -45 22 42 33135001600 1510400 36976946208 37249140768 36740095008 -46 22 42 33908326400 1510400 37813148064 38085342624 37576296864 -47 22 42 34681651200 1510400 38654454048 38926648608 38417602848 diff --git a/tests/data/native_experts/iq3_s.txt b/tests/data/native_experts/iq3_s.txt deleted file mode 100644 index 85164ba..0000000 --- a/tests/data/native_experts/iq3_s.txt +++ /dev/null @@ -1,49 +0,0 @@ -# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] (n_expert 512, total 50292326400; absolute offsets in Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf, or in the named shard beside it) -0 18 20 0 2176000 1386491904 1711166464 913711104 -1 22 42 1114112000 1510400 2340958080 2613152640 2104106880 -2 22 20 1887436800 1971200 3491172096 3763417856 3018391296 -3 22 20 2896691200 1971200 4573970560 4846165120 4101189760 -4 22 20 3905945600 1971200 5652709504 5925377664 5179928704 -5 22 20 4915200000 1971200 6738352640 7010547200 6265571840 -6 22 20 5924454400 1971200 7819193216 8091861376 7346412416 -7 18 20 6933708800 2176000 8905667840 9230291200 8432887040 -8 22 42 8047820800 1510400 9848737024 10120931584 9611885824 -9 22 20 8821145600 1971200 10929646720 11201892480 10456865920 -10 22 42 9830400000 1510400 11779255296 12051501056 11542404096 -11 22 20 10603724800 1971200 12866495360 13138741120 12393714560 -12 18 42 11612979200 1715200 13701750144 14026847104 13464898944 -13 22 42 12491161600 1510400 14649780480 14922026240 14412929280 -14 18 20 13264486400 2176000 15736711296 16061334656 15263930496 -15 22 20 14378598400 1971200 16923842560 17196510720 16451061760 -16 18 20 15387852800 2176000 17998457344 18323131904 17525676544 -17 21 20 16501964800 2329600 19192385920 19556330880 18719605120 -18 18 20 17694720000 2176000 20460359936 20785239296 19987579136 -19 22 20 18808832000 1971200 21654710400 21927378560 21181929600 -20 18 42 19818086400 1715200 22498415744 22823039104 22261564544 -21 21 42 20696268800 1868800 23456363520 23820359680 23219512320 -22 18 20 21653094400 2176000 24722740096 25047837056 24249959296 -23 22 20 22767206400 1971200 25919315200 26191765760 25446534400 -24 22 20 23776460800 1971200 26998514944 27270709504 26525734144 -25 21 20 24785715200 2329600 28087739520 28451684480 27614958720 -26 22 20 25978470400 1971200 29357200896 29629869056 28884420096 -27 21 20 26987724800 2329600 30447303040 30811248000 29974522240 -28 21 20 28180480000 2329600 31709491584 32073910144 31236710784 -29 21 20 29373235200 2329600 32979426560 33343627520 32506645760 -30 18 42 30565990400 1715200 34012167296 34336790656 33775316096 -31 18 20 31444172800 2176000 35212497920 35537121280 34739717120 -32 22 20 32558284800 1971200 36394210304 36666878464 35921429504 -33 18 20 33567539200 2176000 37476126080 37800749440 37003345280 -34 22 20 34681651200 1971200 38661975296 38934221056 38189194496 -35 21 20 35690905600 2329600 39757704320 40121649280 39284923520 -36 22 42 36883660800 1510400 40780381824 41053049984 40543530624 -37 18 20 37656985600 2176000 41866242560 42191339520 41393461760 -38 18 20 38771097600 2176000 43055227776 43379902336 42582446976 -39 22 20 39885209600 1971200 44255558400 44527804160 43782777600 -40 21 20 40894464000 2329600 45334348544 45698549504 44861567744 -41 18 20 42087219200 2176000 46596260480 46920935040 46123479680 -42 18 20 43201331200 2176000 47782160896 48107257856 47309380096 -43 18 20 44315443200 2176000 48982913920 49308010880 48510133120 -44 21 20 45429555200 2329600 50159869824 50523865984 49687089024 -45 21 20 46622310400 2329600 51424864000 51788860160 50952083200 -46 18 20 47815065600 2176000 52692287616 53016962176 52219506816 -47 23 20 48929177600 2662400 53891822080 54341015040 53418222080 diff --git a/tests/data/native_experts/iq3_xxs.txt b/tests/data/native_experts/iq3_xxs.txt deleted file mode 100644 index 42f0ed5..0000000 --- a/tests/data/native_experts/iq3_xxs.txt +++ /dev/null @@ -1,49 +0,0 @@ -# strata native experts v2: layer gu_type d_type offset blob_bytes gate_off up_off down_off (n_expert 512, total 42912972800; the last three are absolute offsets in Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf) -0 17 20 0 1868800 1227833216 1473813376 755052416 -1 16 42 956825600 1305600 2016152832 2235918592 1779301632 -2 17 20 1625292800 1868800 3045972608 3292003968 2573191808 -3 16 42 2582118400 1305600 3839355392 4059172352 3602964992 -4 17 20 3250585600 1868800 4806683136 5052663296 4334363136 -5 17 42 4207411200 1408000 5596436352 5842416512 5359585152 -6 16 42 4928307200 1305600 6379748608 6599514368 6143358208 -7 16 42 5596774400 1305600 7121247872 7340847232 6884396672 -8 21 42 6265241600 1868800 7846857856 8210636416 7610006656 -9 17 42 7222067200 1408000 8873971712 9120003072 8637120512 -10 17 42 7942963200 1408000 9669920128 9915733888 9433068928 -11 16 42 8663859200 1305600 10465942272 10685759232 10229091072 -12 22 42 9332326400 1510400 11190582016 11462610176 10954191616 -13 16 42 10105651200 1305600 12031522432 12251121792 11795132032 -14 17 42 10774118400 1408000 12768096768 13014332928 12531706368 -15 22 42 11495014400 1510400 13563906432 13836152192 13327055232 -16 16 42 12268339200 1305600 14398521216 14618338176 14161670016 -17 22 42 12936806400 1510400 15134954752 15407149312 14898103552 -18 21 42 13710131200 1868800 15976688768 16340467328 15739837568 -19 17 42 14666956800 1408000 17010020352 17256000512 16773629952 -20 21 42 15387852800 1868800 17787815936 18151812096 17551425536 -21 22 42 16344678400 1510400 18811338112 19083532672 18574486912 -22 21 42 17118003200 1868800 19652089088 20016034048 19415237888 -23 21 42 18074828800 1868800 20682407552 21046352512 20445556352 -24 21 42 19031654400 1868800 21704611456 22068390016 21467760256 -25 17 42 19988480000 1408000 22734674432 22980654592 22497823232 -26 22 42 20709376000 1510400 23524471168 23796716928 23287619968 -27 16 42 21482700800 1305600 24379793152 24599558912 24142941952 -28 21 20 22151168000 2329600 25345879296 25709657856 24873098496 -29 22 20 23343923200 1971200 26610479232 26882673792 26137698432 -30 21 20 24353177600 2329600 27695226368 28059171328 27222445568 -31 16 20 25545932800 1766400 28974200192 29193965952 28501419392 -32 21 20 26450329600 2329600 29937050496 30301046656 29464269696 -33 21 42 27643084800 1868800 30959753472 31323698432 30722902272 -34 21 20 28599910400 2329600 32230185088 32594181248 31757404288 -35 18 20 29792665600 2176000 33501048832 33825672192 33028268032 -36 18 42 30906777600 1715200 34444591616 34769048576 34207740416 -37 21 20 31784960000 2329600 35626780032 35990776192 35153999232 -38 22 20 32977715200 1971200 36892498688 37164526848 36419717888 -39 17 20 33986969600 1868800 37987587712 38233567872 37514806912 -40 22 42 34943795200 1510400 38771773056 39043967616 38534921856 -41 18 42 35717120000 1715200 39610924032 39935598592 39374072832 -42 22 20 36595302400 1971200 40796033408 41068061568 40323252608 -43 21 20 37604556800 2329600 41891114752 42254893312 41418333952 -44 18 20 38797312000 2176000 43148423936 43472880896 42675643136 -45 18 42 39911424000 1715200 44098627712 44423724672 43861776512 -46 22 20 40789606400 1971200 45285101568 45557296128 44812320768 -47 18 20 41798860800 2176000 46363501952 46688125312 45890721152 diff --git a/tests/data/native_experts/q2_0.txt b/tests/data/native_experts/q2_0.txt deleted file mode 100644 index 7b2cbd4..0000000 --- a/tests/data/native_experts/q2_0.txt +++ /dev/null @@ -1,49 +0,0 @@ -# strata native experts v2: layer gu_type d_type offset blob_bytes gate_off up_off down_off (n_expert 512, total 33973862400; the last three are absolute offsets in Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf) -0 42 42 0 1382400 994197792 1233624352 757141792 -1 42 42 707788800 1382400 1766860448 2005877408 1530470048 -2 42 42 1415577600 1382400 2558049824 2797476384 2321198624 -3 42 42 2123366400 1382400 3325351328 3564368288 3088500128 -4 42 42 2831155200 1382400 4087571872 4326588832 3851181472 -5 42 42 3538944000 1382400 4853325088 5092342048 4616473888 -6 42 42 4246732800 1382400 5619500704 5858517664 5383110304 -7 42 42 4954521600 1382400 6384631328 6623648288 6148240928 -8 42 42 5662310400 1382400 7144855072 7383872032 6907799072 -9 42 42 6370099200 1382400 7903921568 8143348128 7667531168 -10 42 42 7077888000 1382400 8666152224 8905169184 8429301024 -11 42 42 7785676800 1382400 9441479328 9680905888 9205088928 -12 42 42 8493465600 1382400 10199355552 10438615712 9962965152 -13 42 42 9201254400 1382400 10964891168 11204368928 10728500768 -14 42 42 9909043200 1382400 11732659104 11971919264 11494988704 -15 42 42 10616832000 1382400 12510902048 12749919008 12273846048 -16 42 42 11324620800 1382400 13268829472 13508089632 13031978272 -17 42 42 12032409600 1382400 14035560608 14274577568 13798709408 -18 42 42 12740198400 1382400 14801313824 15040330784 14564462624 -19 42 42 13447987200 1382400 15573612448 15812629408 15336761248 -20 42 42 14155776000 1382400 16333413792 16572673952 16097023392 -21 42 42 14863564800 1382400 17099410208 17338427168 16862559008 -22 42 42 15571353600 1382400 17865654944 18104671904 17629264544 -23 42 42 16279142400 1382400 18638086688 18877564448 18401235488 -24 42 42 16986931200 1382400 19401894432 19641154592 19164838432 -25 42 42 17694720000 1382400 20168095648 20407112608 19931705248 -26 42 42 18402508800 1382400 20937573664 21176590624 20700722464 -27 42 42 19110297600 1382400 21715358368 21954618528 21478967968 -28 42 42 19818086400 1382400 22475620512 22715520672 22238769312 -29 42 42 20525875200 1382400 23242704928 23481721888 23005648928 -30 42 42 21233664000 1382400 24010902944 24250163104 23774512544 -31 42 42 21941452800 1382400 24790715168 25030192928 24553863968 -32 42 42 22649241600 1382400 25553857312 25792874272 25317006112 -33 42 42 23357030400 1382400 26319610528 26558870688 26083220128 -34 42 42 24064819200 1382400 27088512544 27327990304 26851661344 -35 42 42 24772608000 1382400 27864292768 28103309728 27627902368 -36 42 42 25480396800 1382400 28626756512 28866234272 28390366112 -37 42 42 26188185600 1382400 29397609248 29637035808 29160553248 -38 42 42 26895974400 1382400 30166895264 30406321824 29930044064 -39 42 42 27603763200 1382400 30946134048 31185394208 30709282848 -40 42 42 28311552000 1382400 31708403232 31947880992 31471552032 -41 42 42 29019340800 1382400 32478833568 32718093728 32241982368 -42 42 42 29727129600 1382400 33249046304 33488063264 33012195104 -43 42 42 30434918400 1382400 34028407968 34267424928 33791556768 -44 42 42 31142707200 1382400 34791498912 35030759072 34554647712 -45 42 42 31850496000 1382400 35567241248 35806501408 35330185248 -46 42 42 32558284800 1382400 36338232224 36577914784 36101381024 -47 42 42 33266073600 1382400 37117686048 37356946208 36880015648 diff --git a/tests/data/native_experts/qwen36-iq3_xxs.txt b/tests/data/native_experts/qwen36-iq3_xxs.txt deleted file mode 100644 index f75dfcd..0000000 --- a/tests/data/native_experts/qwen36-iq3_xxs.txt +++ /dev/null @@ -1,41 +0,0 @@ -# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] (n_expert 256, total 11108614144; absolute offsets in Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf, or in the named shard beside it) -0 22 18 0 1073152 969626080 1058574816 866005472 -1 22 18 274726912 1073152 1277236448 1366185184 1173615840 -2 22 18 549453824 1073152 1584846816 1673795552 1481226208 -3 22 18 824180736 1073152 1894179552 1983128288 1790558944 -4 22 18 1098907648 1073152 2194252512 2283201248 2090631904 -5 22 18 1373634560 1073152 2501862880 2590811616 2398242272 -6 22 18 1648361472 1073152 2809473248 2898421984 2705852640 -7 22 18 1923088384 1073152 3118805984 3207754720 3015185376 -8 22 18 2197815296 1073152 3418878944 3507827680 3315258336 -9 22 18 2472542208 1073152 3726489312 3815438048 3622868704 -10 22 18 2747269120 1073152 4034099680 4123048416 3930479072 -11 22 18 3021996032 1073152 4343432416 4432381152 4239811808 -12 22 18 3296722944 1073152 4643505376 4732454112 4539884768 -13 22 18 3571449856 1073152 4951115744 5040064480 4847495136 -14 22 18 3846176768 1073152 5258726112 5347674848 5155105504 -15 22 18 4120903680 1073152 5568058848 5657007584 5464438240 -16 22 18 4395630592 1073152 5868131808 5957080544 5764511200 -17 22 18 4670357504 1073152 6175742176 6264690912 6072121568 -18 22 18 4945084416 1073152 6483352544 6572301280 6379731936 -19 22 18 5219811328 1073152 6792685280 6881634016 6689064672 -20 22 18 5494538240 1073152 7092758240 7181706976 6989137632 -21 22 18 5769265152 1073152 7400368608 7489317344 7296748000 -22 22 18 6043992064 1073152 7707978976 7796927712 7604358368 -23 22 18 6318718976 1073152 8017311712 8106260448 7913691104 -24 22 18 6593445888 1073152 8317384672 8406333408 8213764064 -25 22 18 6868172800 1073152 8624995040 8713943776 8521374432 -26 22 18 7142899712 1073152 8932605408 9021554144 8828984800 -27 22 18 7417626624 1073152 9241938144 9330886880 9138317536 -28 22 18 7692353536 1073152 9542011104 9630959840 9438390496 -29 22 18 7967080448 1073152 9849621472 9938570208 9746000864 -30 22 18 8241807360 1073152 10157231840 10246180576 10053611232 -31 22 18 8516534272 1073152 10466564576 10555513312 10362943968 -32 22 18 8791261184 1073152 10766637536 10855586272 10663016928 -33 22 18 9065988096 1073152 11074247904 11163196640 10970627296 -34 22 23 9340715008 1228800 11421704160 11510652896 11278237664 -35 22 18 9655287808 1073152 11731036896 11819985632 11627416288 -36 22 18 9930014720 1073152 12031109856 12120058592 11927489248 -37 22 18 10204741632 1073152 12338720224 12427668960 12235099616 -38 22 23 10479468544 1228800 12686176480 12775125216 12542709984 -39 22 23 10794041344 1228800 13035355104 13124303840 12891888608 diff --git a/tests/data/native_experts/qwen36-q4_k_xl.txt b/tests/data/native_experts/qwen36-q4_k_xl.txt deleted file mode 100644 index 0ffb4d4..0000000 --- a/tests/data/native_experts/qwen36-q4_k_xl.txt +++ /dev/null @@ -1,41 +0,0 @@ -# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] (n_expert 256, total 19635634176; absolute offsets in Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf, or in the named shard beside it) -0 12 13 0 1900544 1304098592 1458312992 1118435104 -1 12 13 486539264 1900544 1832409632 1986624032 1646746144 -2 12 13 973078528 1900544 2360720672 2514935072 2175057184 -3 12 13 1459617792 1900544 2891261984 3045476384 2705598496 -4 12 13 1946157056 1900544 3410004000 3564218400 3224340512 -5 12 13 2432696320 1900544 3938315040 4092529440 3752651552 -6 12 13 2919235584 1900544 4466626080 4620840480 4280962592 -7 12 13 3405774848 1900544 4997167392 5151381792 4811503904 -8 12 13 3892314112 1900544 5515909408 5670123808 5330245920 -9 12 13 4378853376 1900544 6044220448 6198434848 5858556960 -10 12 13 4865392640 1900544 6572531488 6726745888 6386868000 -11 12 13 5351931904 1900544 7103072800 7257287200 6917409312 -12 12 13 5838471168 1900544 7621814816 7776029216 7436151328 -13 12 13 6325010432 1900544 8150125856 8304340256 7964462368 -14 12 13 6811549696 1900544 8678436896 8832651296 8492773408 -15 12 13 7298088960 1900544 9208978208 9363192608 9023314720 -16 12 13 7784628224 1900544 9727720224 9881934624 9542056736 -17 12 13 8271167488 1900544 10256031264 10410245664 10070367776 -18 12 13 8757706752 1900544 10784342304 10938556704 10598678816 -19 12 13 9244246016 1900544 11314883616 11469098016 11129220128 -20 12 13 9730785280 1900544 11833625632 11987840032 11647962144 -21 12 13 10217324544 1900544 12361936672 12516151072 12176273184 -22 12 13 10703863808 1900544 12890247712 13044462112 12704584224 -23 12 13 11190403072 1900544 13420789024 13575003424 13235125536 -24 12 13 11676942336 1900544 13939531040 14093745440 13753867552 -25 12 13 12163481600 1900544 14467842080 14622056480 14282178592 -26 12 13 12650020864 1900544 14996153120 15150367520 14810489632 -27 12 13 13136560128 1900544 15526694432 15680908832 15341030944 -28 12 13 13623099392 1900544 16045436448 16199650848 15859772960 -29 12 13 14109638656 1900544 16573747488 16727961888 16388084000 -30 12 13 14596177920 1900544 17102058528 17256272928 16916395040 -31 12 13 15082717184 1900544 17632599840 17786814240 17446936352 -32 12 13 15569256448 1900544 18151341856 18305556256 17965678368 -33 12 13 16055795712 1900544 18679652896 18833867296 18493989408 -34 12 14 16542334976 2039808 19243615520 19397829920 19022300448 -35 12 13 17064525824 1900544 19774156832 19928371232 19588493344 -36 12 13 17551065088 1900544 20292898848 20447113248 20107235360 -37 12 13 18037604352 1900544 20821209888 20975424288 20635546400 -38 12 14 18524143616 2039808 21385172512 21539386912 21163857440 -39 13 14 19046334464 2301952 21951365408 22139134240 21730050336 diff --git a/tests/data/native_experts/swift-iq2_xs.txt b/tests/data/native_experts/swift-iq2_xs.txt deleted file mode 100644 index 0da3e8f..0000000 --- a/tests/data/native_experts/swift-iq2_xs.txt +++ /dev/null @@ -1,49 +0,0 @@ -# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] (n_expert 512, total 35454976000; absolute offsets in Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf, or in the named shard beside it) -0 22 42 0 1510400 29757220608 30031875328 29520369408 -1 16 42 773324800 1305600 30594451584 30817317504 30357600384 -2 22 42 1441792000 1510400 31394803200 31669624320 31157952000 -3 22 42 2215116800 1510400 32237578624 32512399744 31999908224 -4 16 42 2988441600 1305600 33069241728 33291634048 32832390528 -5 22 42 3656908800 1510400 33801615104 34076436224 33564763904 -6 22 42 4430233600 1510400 34640622720 34915443840 34404232320 -7 22 42 5203558400 1510400 35484094464 35759389184 35247704064 -8 29 42 5976883200 1177600 36317828608 36507452928 36080977408 -9 16 42 6579814400 1305600 36985651584 37207877504 36747981184 -10 16 42 7248281600 1305600 37719456000 37941848320 37482604800 -11 16 42 7916748800 1305600 38457145984 38679538304 38220755584 -12 22 42 8585216000 1510400 39186022528 39461317248 38949171328 -13 29 42 9358540800 1177600 237726720 427184640 56320 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -14 16 42 9961472000 1305600 905216896 1127609216 667546496 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -15 22 42 10629939200 1510400 1647947520 1922602240 1411096320 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -16 22 42 11403264000 1510400 2482334464 2757629184 2244664064 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -17 22 42 12176588800 1510400 3320679040 3595500160 3083827840 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -18 16 42 12949913600 1305600 4159673856 4381899776 3922822656 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -19 16 42 13618380800 1305600 4897658240 5120050560 4660807040 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -20 22 42 14286848000 1510400 5626713984 5901535104 5389043584 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -21 22 42 15060172800 1510400 6464930560 6739751680 6227260160 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -22 22 42 15833497600 1510400 7300103296 7574924416 7063712896 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -23 22 42 16606822400 1510400 8143656960 8418311680 7906805760 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -24 22 42 17380147200 1510400 8981297664 9256118784 8744446464 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -25 22 42 18153472000 1510400 9823241600 10097896320 9586390400 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -26 22 42 18926796800 1510400 10660472576 10935293696 10423621376 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -27 16 42 19700121600 1305600 11503480960 11726346880 11266629760 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -28 22 42 20368588800 1510400 12232191104 12506845824 11995339904 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -29 16 42 21141913600 1305600 13071493120 13293885440 12834641920 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -30 16 42 21810380800 1305600 13803572096 14025964416 13567181696 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -31 22 42 22478848000 1510400 14542268160 14817089280 14305416960 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -32 22 42 23252172800 1510400 15375362304 15650183424 15138511104 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -33 22 42 24025497600 1510400 16213233280 16488054400 15976382080 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -34 22 42 24798822400 1510400 17056774656 17331595776 16819923456 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -35 22 42 25572147200 1510400 17896754560 18171575680 17659903360 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -36 22 42 26345472000 1510400 18730015104 19005309824 18493163904 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -37 29 42 27118796800 1177600 19568359680 19757984000 19331508480 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -38 22 42 27721728000 1510400 20236794496 20511615616 19999943296 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -39 22 42 28495052800 1510400 21080348160 21355169280 20843496960 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -40 22 42 29268377600 1510400 21910946304 22185767424 21674095104 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -41 22 42 30041702400 1510400 22748177280 23022998400 22511326080 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -42 22 42 30815027200 1510400 23586048256 23861342976 23349197056 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -43 22 42 31588352000 1510400 24429696640 24704351360 24192845440 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -44 22 42 32361676800 1510400 25262790784 25538085504 25025939584 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -45 22 42 33135001600 1510400 26106805760 26381626880 25869954560 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -46 22 42 33908326400 1510400 26945634176 27220455296 26708782976 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf -47 22 42 34681651200 1510400 27789566720 28064387840 27552715520 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf diff --git a/tests/platform/direct_file_async.cpp b/tests/platform/direct_file_async.cpp deleted file mode 100644 index f046b31..0000000 --- a/tests/platform/direct_file_async.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include "strata/platform/direct_file.hpp" -#include -#include -#include -#include -#include -#include -#include -#include -#include -using strata::platform::DirectFile; -using strata::platform::Completion; -static void check(bool ok, const char* why) { if (!ok) throw std::runtime_error(why); } -int main() { - char name[] = "/tmp/strata-direct-test-XXXXXX"; - int fd = mkstemp(name); - if (fd < 0) return 1; - close(fd); - void* memory = DirectFile::alloc_aligned(4096 * 18); - try { - check(memory != nullptr, "buffer allocation"); - { std::ofstream f(name, std::ios::binary); std::string bytes(4096 * 16 + 17, 'x'); f.write(bytes.data(), bytes.size()); } - DirectFile f; - std::string error; - setenv("STRATA_IO_THREADS", "4", 1); // the pool's size (out-of-range values are clamped to 1..64) - check(f.open(name, error), error.c_str()); - check(!f.submit(1, memory, 4096, 0, error), "unaligned request accepted"); - for (unsigned i = 0; i < 17; ++i) - check(f.submit(i * 4096, static_cast(memory) + i * 4096, 4096, i, error), error.c_str()); - std::vector seen(17); - unsigned count = 0; - while (count < 17) { - Completion c[17]; int n = f.wait(c, 17, 5000); - check(n > 0, "completion timeout"); - for (int i = 0; i < n; ++i) { - check(c[i].tag < 17 && !seen[c[i].tag], "wrong or repeated completion"); - seen[c[i].tag] = true; ++count; - check(c[i].ok && c[i].bytes == (c[i].tag == 16 ? 17u : 4096u), "incorrect full/EOF completion"); - check(static_cast(memory)[c[i].tag * 4096] == 'x', "read data mismatch"); - } - } - std::jthread waker([&] { f.wake(); }); - Completion c; check(f.wait(&c, 1, 5000) == 1 && c.tag == DirectFile::WAKE_TAG, "wake lost"); - waker.join(); - check(f.submit(0, memory, 4096, 99, error), error.c_str()); - f.close(); // Must drain outstanding buffer writes before returning. - std::memset(memory, 0, 4096); - check(f.open(name, error), error.c_str()); - check(f.wait(&c, 1, 0) == 0, "stale completion on reopen"); - check(f.submit(0, memory, 4096, 100, error), error.c_str()); - check(f.wait(&c, 1, 5000) == 1 && c.ok && c.tag == 100, "reopened read failed"); - f.close(); - DirectFile::free_aligned(memory); unlink(name); - std::cout << "direct_file_async: passed queued reads, short EOF, wake, close drain, reopen\n"; - return 0; - } catch (const std::exception& e) { - DirectFile::free_aligned(memory); unlink(name); - std::cerr << e.what() << '\n'; return 1; - } -} diff --git a/tests/python/qwen36_mtp_fixture.py b/tests/python/qwen36_mtp_fixture.py deleted file mode 100644 index ab9e697..0000000 --- a/tests/python/qwen36_mtp_fixture.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/env python3 -"""The Qwen3.6 drafter harness's fixture: a synthetic qwen35moe GGUF with a nextn block at the model's per-layer -geometry, the oracle's `--mtp` dumps for it, and the draft pack cut from it (docs/qwen36-port/step4-drafter.md). - - python3 -I tests/python/qwen36_mtp_fixture.py --out - -The drafter's kernels are built for the real widths (n_embd 2048, attention 16 heads / 2 KV heads of 256, experts of -512), so this is tests/python/qwen36_prefill_fixture.py's `full4` trunk (three DeltaNet layers, layer 3 full attention, -16 experts top-8) plus the nextn block `blk.4` (tools/qwen36_synth_gguf.py's: an attention + MoE block, `nextn.eh_proj` -[2 n_embd, n_embd], `nextn.enorm` / `hnorm` / `shared_head_norm`). Every projection, `nextn.eh_proj`, the experts, the -head and the token embedding are Q8_0 (what the engine's native paths take: MMVQ, the native expert kernels, the native -head and embedding); the routers, `ssm_alpha` / `ssm_beta` and the shared-expert gates are F32 values rounded to BF16 -(the pack writes them as BF16 exactly); the norms, conv, dt bias and ssm_a F32. The oracle (ref/qwen36.py) dequantizes -with gguf-py, bit-identical to ggml, so every difference the harness sees is the engine's arithmetic. - -Writes /mtp5.gguf; the oracle's dumps for 76 tokens in /o and /o_mtp (the faithful -reading: the trunk, then the nextn block on (tokens[1:], h_nextn[:-1]) at positions 1..75), /o_q8 and -/o_q8_mtp (`--act-quant q8`: the activations rounded as ggml does before a quantized matmul); and the draft pack -in /pack (tools/mtp_qwen36_pack.py, no draft vocabulary: the whole 128-token head). Without numpy or gguf-py it -writes /SKIP with the reason and exits 0, and the test exits 77 on seeing it. -""" -from __future__ import annotations - -import argparse -import os -import pathlib -import subprocess -import sys - -HERE = pathlib.Path(__file__).resolve().parent -ROOT = HERE.parent.parent -sys.path.insert(0, str(ROOT / "tools")) -sys.path.insert(0, str(HERE)) - -try: - import numpy as np - import _paths - import qwen36_synth_gguf as qs # adds gguf-py to sys.path on import (tools/_paths.py) - import qwen36_prefill_fixture as pf # the per-layer geometry, the BF16 rounding, the Q8_0 suffix list - from gguf import GGUFWriter, GGMLQuantizationType as Q, quants -except ImportError as e: # a trimmed third_party or no numpy: a skip, not a failure - print(f"qwen36_mtp_fixture: {e}", file=sys.stderr) - out = None - for i, a in enumerate(sys.argv[1:], 1): - if a == "--out" and i < len(sys.argv) - 1: - out = sys.argv[i + 1] - elif a.startswith("--out="): - out = a[len("--out="):] - if out: - pathlib.Path(out).mkdir(parents=True, exist_ok=True) - (pathlib.Path(out) / "SKIP").write_text(f"{e}\n") - sys.exit(0) - -# 76 tokens (the ASCII codes of this text: the fixture's vocabulary is the 128 byte tokens): 75 nextn positions, so the -# prompt-side pass (Prefill::draft_kv, batches of at least 64 rows) is exercised and the positions after it are checked -TEXT = "the quick brown fox jumps over the lazy dog while the cat sleeps on the mat " -TOKENS = [ord(c) for c in TEXT] -assert len(TOKENS) == 76, len(TOKENS) -Q8_SUFFIXES = pf.Q8_SUFFIXES + (".nextn.eh_proj.weight",) - - -def cfg(seed: int) -> qs.Cfg: - c = pf.cfg("full4", seed) - c.nextn = True - return c - - -def write(path: str, c: qs.Cfg) -> tuple[int, int]: - """qwen36_prefill_fixture.write with the nextn block declared and the embedding Q8_0.""" - w = GGUFWriter(path, qs.ARCH) - k = lambda s: f"{qs.ARCH}.{s}" - w.add_name("qwen36-synth drafter-geometry") - w.add_uint32(k("context_length"), c.n_ctx_train) - w.add_uint32(k("embedding_length"), c.n_embd) - w.add_uint32(k("block_count"), c.n_layer + 1) - w.add_uint32(k("nextn_predict_layers"), 1) - w.add_uint32(k("attention.head_count"), c.n_head) - w.add_uint32(k("attention.head_count_kv"), c.n_head_kv) - w.add_uint32(k("attention.key_length"), c.head_dim) - w.add_uint32(k("attention.value_length"), c.head_dim) - w.add_float32(k("attention.layer_norm_rms_epsilon"), c.rms_eps) - w.add_uint32(k("rope.dimension_count"), c.n_rot) - w.add_array(k("rope.dimension_sections"), list(c.rope_sections)) - w.add_float32(k("rope.freq_base"), c.rope_base) - w.add_uint32(k("expert_count"), c.n_expert) - w.add_uint32(k("expert_used_count"), c.n_expert_used) - w.add_uint32(k("expert_feed_forward_length"), c.n_ff_exp) - w.add_uint32(k("expert_shared_feed_forward_length"), c.n_ff_shexp) - w.add_uint32(k("ssm.conv_kernel"), c.ssm_conv) - w.add_uint32(k("ssm.state_size"), c.ssm_state) - w.add_uint32(k("ssm.group_count"), c.ssm_k_heads) - w.add_uint32(k("ssm.time_step_rank"), c.ssm_v_heads) - w.add_uint32(k("ssm.inner_size"), c.value_dim) - w.add_uint32(k("full_attention_interval"), c.interval) - w.add_file_type(7) # LLAMA_FTYPE_MOSTLY_Q8_0 - toks = qs.byte_unicode() - w.add_tokenizer_model("gpt2") - w.add_tokenizer_pre("default") - w.add_token_list(toks) - w.add_token_types([1] * c.n_vocab) - w.add_token_merges(["Ā ā"]) - w.add_bos_token_id(0) - w.add_eos_token_id(3) - w.add_add_bos_token(False) - n, nq = 0, 0 - for name, arr in qs.build_tensors(c): - n += 1 - if name.endswith(Q8_SUFFIXES) or name in ("output.weight", "token_embd.weight"): - w.add_tensor(name, quants.quantize(arr, Q.Q8_0), raw_dtype=Q.Q8_0) - nq += 1 - elif name.endswith(pf.BF16_SUFFIXES): - if name.endswith(".ffn_gate_inp.weight"): # half the toy's router gain, as the prompt-path fixture - arr = (arr * 0.5).astype(np.float32) - w.add_tensor(name, pf.to_bf16_exact(arr)) - else: - w.add_tensor(name, arr) - w.write_header_to_file() - w.write_kv_data_to_file() - w.write_tensors_to_file() - w.close() - return n, nq - - -def run(cmd: list[str]) -> None: - env = dict(os.environ) - env.setdefault("STRATA_GGUF_PY", _paths.gguf_py()) - subprocess.run(cmd, check=True, env=env, stdout=subprocess.DEVNULL) - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - ap.add_argument("--out", required=True) - ap.add_argument("--seed", type=int, default=0) - ap.add_argument("--no-oracle", action="store_true", help="write the GGUF and the pack only") - a = ap.parse_args() - out = pathlib.Path(a.out) - out.mkdir(parents=True, exist_ok=True) - (out / "SKIP").unlink(missing_ok=True) - c = cfg(a.seed) - gguf = str(out / "mtp5.gguf") - n, nq = write(gguf, c) - print(f"wrote {gguf}: {n} tensors ({nq} Q8_0), {c.n_layer} trunk layers + the nextn block, {c.n_expert} experts " - f"top-{c.n_expert_used}") - run([sys.executable, "-I", str(ROOT / "tools" / "mtp_qwen36_pack.py"), "--gguf", gguf, "--out", str(out / "pack"), - "--draft-vocab", "none"]) - print(f" pack in {out / 'pack'}") - if a.no_oracle: - return 0 - toks = ",".join(map(str, TOKENS)) - oracle = [sys.executable, "-I", str(ROOT / "ref" / "qwen36.py"), gguf, "--tokens", toks, "--mtp"] - run(oracle + ["--dump", str(out / "o")]) - run(oracle + ["--dump", str(out / "o_q8"), "--act-quant", "q8"]) - print(f" oracle dumps in {out}: o, o_mtp, o_q8, o_q8_mtp") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tests/python/qwen36_prefill_fixture.py b/tests/python/qwen36_prefill_fixture.py deleted file mode 100644 index 2d1b0ce..0000000 --- a/tests/python/qwen36_prefill_fixture.py +++ /dev/null @@ -1,186 +0,0 @@ -#!/usr/bin/env python3 -"""The Qwen3.6 prompt-path harness's fixtures: synthetic qwen35moe GGUFs at the model's per-layer geometry, and the -oracle's dumps for them (docs/qwen36-port/step3-prefill.md). - -The prompt path's kernels are built for the real widths (n_embd 2048, GDN 16 key heads / 32 value heads of 128 with -8192 conv channels, attention 16 heads / 2 KV heads of 256, experts of 512), so the oracle's own 64-wide toy fixture -cannot run through them. This writes the same synthetic model (tools/qwen36_synth_gguf.py's weights) at those widths -with few layers and few experts: - - gdn3 3 layers, all Gated DeltaNet (interval 4: no layer satisfies (il + 1) % 4 == 0), 16 experts top-8 - full4 4 layers: three DeltaNet, layer 3 full attention (the attention kernels' case) - -The projections and the experts are Q8_0 (what the engine serves natively: Gemm::native dequantizes them to FP16, -the prompt experts take the MMQ or the FP16 path), the router / ssm_alpha / ssm_beta / ffn_gate_inp_shexp are F32 -values rounded to BF16 (the engine's forms, exact), the norms, conv, dt bias and ssm_a F32 as in the real file. The -oracle (ref/qwen36.py) dequantizes with gguf-py, bit-identical to ggml, so every difference the harness sees is the -engine's arithmetic (FP16 activations, int8 MMQ), not the weights. - -For each case: /.gguf, the oracle's dumps for 40 tokens in //o (the faithful reading) and -//o_q8 (--act-quant q8: the activations rounded as ggml does before a quantized matmul), and the negative -controls //neg_: the oracle with one reading flipped to its rival (gdn_gate=sigmoid, -head_pairing=interleaved, router_norm=False; attn_gate=False on full4). Without numpy or gguf-py it writes -/SKIP with the reason and exits 0, and the test exits 77 on seeing it (a skip, not a failure). -""" -from __future__ import annotations - -import argparse -import os -import pathlib -import subprocess -import sys - -HERE = pathlib.Path(__file__).resolve().parent -ROOT = HERE.parent.parent -sys.path.insert(0, str(ROOT / "tools")) - -try: - import numpy as np - import _paths - import qwen36_synth_gguf as qs # adds gguf-py to sys.path on import (tools/_paths.py) - from gguf import GGUFWriter, GGMLQuantizationType as Q, quants -except ImportError as e: # a trimmed third_party or no numpy: a skip, not a failure - print(f"qwen36_prefill_fixture: {e}", file=sys.stderr) - out = None - for i, a in enumerate(sys.argv[1:], 1): - if a == "--out" and i < len(sys.argv) - 1: - out = sys.argv[i + 1] - elif a.startswith("--out="): - out = a[len("--out="):] - if out: - pathlib.Path(out).mkdir(parents=True, exist_ok=True) - (pathlib.Path(out) / "SKIP").write_text(f"{e}\n") - sys.exit(0) - -# 40 tokens: the ASCII codes of this text (the fixture's vocabulary is the 128 byte tokens) -TEXT = "the quick brown fox jumps over the lazy " -TOKENS = [ord(c) for c in TEXT] -assert len(TOKENS) == 40 - -Q8_SUFFIXES = (".attn_qkv.weight", ".attn_gate.weight", ".ssm_out.weight", ".attn_q.weight", ".attn_k.weight", - ".attn_v.weight", ".attn_output.weight", ".ffn_gate_shexp.weight", ".ffn_up_shexp.weight", - ".ffn_down_shexp.weight", ".ffn_gate_exps.weight", ".ffn_up_exps.weight", ".ffn_down_exps.weight") -BF16_SUFFIXES = (".ffn_gate_inp.weight", ".ssm_alpha.weight", ".ssm_beta.weight", ".ffn_gate_inp_shexp.weight") - - -def to_bf16_exact(a: np.ndarray) -> np.ndarray: - """The F32 values rounded to the nearest BF16 (round-to-nearest-even), returned as F32: the engine's BF16 image of - the tensor is then exact, and so is the oracle's F32 read of it.""" - u = a.astype(np.float32).view(np.uint32) - r = ((u + 0x7FFF + ((u >> 16) & 1)) & 0xFFFF0000).astype(np.uint32) - return r.view(np.float32) - - -def cfg(case: str, seed: int) -> qs.Cfg: - c = qs.Cfg(n_embd=2048, n_layer=3 if case == "gdn3" else 4, interval=4, n_vocab=128, n_expert=16, n_expert_used=8, - n_ff_exp=512, n_ff_shexp=512, ssm_k_heads=16, ssm_v_heads=32, ssm_state=128, ssm_conv=4, n_head=16, - n_head_kv=2, head_dim=256, n_rot=64, rope_sections=(11, 11, 10, 0), rope_base=1e7, rms_eps=1e-6, - n_ctx_train=4096, nextn=False, seed=seed) - # Cfg.check() demands a full-attention layer; gdn3 deliberately has none (llama.cpp's rule puts attention at - # (il + 1) % 4 == 0, which no layer of three reaches), so its invariants are checked here instead - assert c.ssm_v_heads % c.ssm_k_heads == 0 and c.n_head % c.n_head_kv == 0 and c.n_expert_used <= c.n_expert - assert sum(c.rope_sections) * 2 == c.n_rot - return c - - -def write(path: str, c: qs.Cfg, q8_embd: bool = False) -> tuple[int, int]: - """qwen36_synth_gguf.write with the per-tensor forms above. Returns (tensors, q8 tensors). `q8_embd` writes - token_embd.weight as Q8_0 too (a native pack's embedding must be a type iq_embed_rows serves: the runner's fixture, - tests/python/qwen36_runner_fixture.py); the prompt-path harness keeps it F32.""" - w = GGUFWriter(path, qs.ARCH) - k = lambda s: f"{qs.ARCH}.{s}" - w.add_name("qwen36-synth prefill-geometry") - w.add_uint32(k("context_length"), c.n_ctx_train) - w.add_uint32(k("embedding_length"), c.n_embd) - w.add_uint32(k("block_count"), c.n_layer) - w.add_uint32(k("attention.head_count"), c.n_head) - w.add_uint32(k("attention.head_count_kv"), c.n_head_kv) - w.add_uint32(k("attention.key_length"), c.head_dim) - w.add_uint32(k("attention.value_length"), c.head_dim) - w.add_float32(k("attention.layer_norm_rms_epsilon"), c.rms_eps) - w.add_uint32(k("rope.dimension_count"), c.n_rot) - w.add_array(k("rope.dimension_sections"), list(c.rope_sections)) - w.add_float32(k("rope.freq_base"), c.rope_base) - w.add_uint32(k("expert_count"), c.n_expert) - w.add_uint32(k("expert_used_count"), c.n_expert_used) - w.add_uint32(k("expert_feed_forward_length"), c.n_ff_exp) - w.add_uint32(k("expert_shared_feed_forward_length"), c.n_ff_shexp) - w.add_uint32(k("ssm.conv_kernel"), c.ssm_conv) - w.add_uint32(k("ssm.state_size"), c.ssm_state) - w.add_uint32(k("ssm.group_count"), c.ssm_k_heads) - w.add_uint32(k("ssm.time_step_rank"), c.ssm_v_heads) - w.add_uint32(k("ssm.inner_size"), c.value_dim) - w.add_uint32(k("full_attention_interval"), c.interval) - w.add_file_type(7) # LLAMA_FTYPE_MOSTLY_Q8_0 - toks = qs.byte_unicode() - w.add_tokenizer_model("gpt2") - w.add_tokenizer_pre("default") - w.add_token_list(toks) - w.add_token_types([1] * c.n_vocab) - w.add_token_merges(["Ā ā"]) - w.add_bos_token_id(0) - w.add_eos_token_id(3) - w.add_add_bos_token(False) - n, nq = 0, 0 - for name, arr in qs.build_tensors(c): - n += 1 - if name.endswith(Q8_SUFFIXES) or name == "output.weight" or (q8_embd and name == "token_embd.weight"): - w.add_tensor(name, quants.quantize(arr, Q.Q8_0), raw_dtype=Q.Q8_0) # the byte shape; gguf-py derives the elements - nq += 1 - elif name.endswith(BF16_SUFFIXES): - # the router's logits at half the toy's gain: with 16 experts at the toy's spread the top-8 carry 99 % of the - # softmax mass and the renormalisation rival (router_norm=False) moves ffn_out by 1 %, invisible to a 5 % - # gate; at this gain the top-8 carry less and the rival is seen (the harness measures both) - if name.endswith(".ffn_gate_inp.weight"): - arr = (arr * 0.5).astype(np.float32) - w.add_tensor(name, to_bf16_exact(arr)) - else: - w.add_tensor(name, arr) - w.write_header_to_file() - w.write_kv_data_to_file() - w.write_tensors_to_file() - w.close() - return n, nq - - -def oracle(gguf: str, dump: str, extra: list[str]) -> None: - cmd = [sys.executable, "-I", str(ROOT / "ref" / "qwen36.py"), gguf, "--tokens", ",".join(map(str, TOKENS)), - "--dump", dump] + extra - env = dict(os.environ) - env.setdefault("STRATA_GGUF_PY", _paths.gguf_py()) - subprocess.run(cmd, check=True, env=env, stdout=subprocess.DEVNULL) - - -NEGATIVES = {"gate": ["--opt", "gdn_gate=sigmoid"], "pair": ["--opt", "head_pairing=interleaved"], - "norm": ["--opt", "router_norm=False"], "attngate": ["--opt", "attn_gate=False"]} - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - ap.add_argument("--out", required=True) - ap.add_argument("--seed", type=int, default=0) - ap.add_argument("--cases", default="gdn3,full4") - ap.add_argument("--no-oracle", action="store_true", help="write the GGUFs only") - a = ap.parse_args() - out = pathlib.Path(a.out) - out.mkdir(parents=True, exist_ok=True) - for case in a.cases.split(","): - c = cfg(case, a.seed) - gguf = str(out / f"{case}.gguf") - n, nq = write(gguf, c) - print(f"wrote {gguf}: {n} tensors ({nq} Q8_0), {c.n_layer} layers, {c.n_expert} experts top-{c.n_expert_used}") - if a.no_oracle: - continue - d = out / case - oracle(gguf, str(d / "o"), []) - oracle(gguf, str(d / "o_q8"), ["--act-quant", "q8"]) - for name, opt in NEGATIVES.items(): - if name == "attngate" and case == "gdn3": - continue - oracle(gguf, str(d / f"neg_{name}"), opt) - print(f" oracle dumps in {d}: o, o_q8, " + ", ".join(f"neg_{k}" for k in NEGATIVES if not (k == "attngate" and case == "gdn3"))) - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tests/python/qwen36_runner_check.py b/tests/python/qwen36_runner_check.py deleted file mode 100644 index b6d4983..0000000 --- a/tests/python/qwen36_runner_check.py +++ /dev/null @@ -1,186 +0,0 @@ -#!/usr/bin/env python3 -"""The streaming runner (the `strata` binary) on the synthetic native pack, held to the oracle at every position -(docs/qwen36-port/step4-runner.md; the fixture is tests/python/qwen36_runner_fixture.py, the window-level test -tests/cuda/qwen36_verify_test.cpp). - - python3 -I tests/python/qwen36_runner_check.py --strata build/strata --fixture DIR [--keep] - -Three runs of the 40-token sequence ("the quick brown fox jumps over the lazy "), each teacher-forced to the oracle's -own tokens (--spec-oracle + --teacher-force: every window row committed, the next window from the sequence's token) -with --dump-logits writing one row of head logits per position: - - c7 the oracle's base_c7 shape: positions 0..34 through the prompt path in chunks of 7, then the decode windows - from position 35 (rows 35..39 compared) - c40 one prompt chunk of 35, then the windows (the same rows; a different prompt chunking must give the same) - ar position 0 through a one-token prompt chunk, then every other position through the decode windows - (the oracle's base_ar shape; rows 1..39 compared) - -Each row is held to the Q8 oracle's `result_output_all` (--act-quant q8: the policy's reference for a path that -rounds activations to Q8, oracle-crosscheck.md "Tolerance policy") at the window test's accumulated class (5e-2 -relative L2), with the argmax required to agree at every compared position; the F32 oracle's numbers are reported. Then the -mutation-sensitivity gate: 4 KB of `blk.1.ffn_gate_inp.weight` in a copy of the pack's dense.bin are flipped and the -c7 run repeated; its logits must move by more than 1e-2 relative L1 from the intact run's (a pack whose bytes do not -reach the logits is not being read). Exit 0 / 1 / 77 (no fixture, no CUDA device: the binary says so). -""" -from __future__ import annotations - -import argparse -import os -import pathlib -import shutil -import subprocess -import sys -import tempfile - -import numpy as np - -TEXT = "the quick brown fox jumps over the lazy " -TOKENS = [ord(c) for c in TEXT] -N_VOCAB = 128 -TOL_LOGITS = 5e-2 # the accumulated class against the Q8 oracle (tests/cuda/qwen36_verify_test.cpp's kAccum) -MUTATION_MIN = 1e-2 - - -def run_engine(strata, fixture, pack, tokens, prefill_chunk, prefill_until, oracle, out_logits, max_new, log): - cmd = [strata, "--native", str(fixture / "full4.gguf"), "--pack", str(pack), "--tokens", ",".join(map(str, tokens)), - "--max-new", str(max_new), "--greedy", "--spec", "4", "--prefill", str(prefill_chunk), - "--prefill-until", str(prefill_until), "--max-context", "128", "--kv", "fp16", - "--expert-profile", str(pack / "expert-profile.bin"), "--expert-cache", "64", - "--spec-oracle", str(oracle), "--teacher-force", "--dump-logits", str(out_logits), "--suffix-draft", "0"] - with open(log, "w") as f: - f.write(" ".join(cmd) + "\n") - r = subprocess.run(cmd, stdout=f, stderr=subprocess.STDOUT) - return r.returncode - - -def load_rows(path): - a = np.fromfile(path, dtype=np.float32) - h = np.frombuffer(a[:2].tobytes(), dtype=np.int32) - if int(h[0]) != N_VOCAB: - raise SystemExit(f"{path}: header n_vocab {int(h[0])}") - rows = a[2:].reshape(-1, N_VOCAB) - if rows.shape[0] != int(h[1]): - raise SystemExit(f"{path}: header promises {int(h[1])} rows, the file holds {rows.shape[0]}") - return rows - - -def rel_l2(a, b): - return float(np.linalg.norm(a - b) / max(np.linalg.norm(b), 1e-30)) - - -def rel_l1(a, b): - return float(np.abs(a - b).sum() / max(np.abs(b).sum(), 1e-30)) - - -def main(): - ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - ap.add_argument("--strata", required=True) - ap.add_argument("--fixture", required=True) - ap.add_argument("--keep", action="store_true", help="keep the work directory") - a = ap.parse_args() - fx = pathlib.Path(a.fixture) - if (fx / "SKIP").exists() or not (fx / "pack" / "index.txt").exists() or not (fx / "o40" / "manifest.txt").exists(): - print(f"qwen36_runner_check: no fixture in {fx}: skipped", file=sys.stderr) - return 77 - work = pathlib.Path(tempfile.mkdtemp(prefix="qwen36-runner-check-")) - ref = np.fromfile(fx / "o40" / "result_output_all.f32", dtype=np.float32).reshape(-1, N_VOCAB) - refq = np.fromfile(fx / "o40_q8" / "result_output_all.f32", dtype=np.float32).reshape(-1, N_VOCAB) - fails = 0 - - def check(ok, what): - nonlocal fails - print(f" {what:<100} {'ok' if ok else 'FAIL'}") - fails += not ok - - # the three chunkings: (name, prompt chunk, prefill-until, the first compared position) - cases = [("c7", 7, 35, 35), ("c40", 40, 35, 35), ("ar", 7, 1, 1)] - logits = {} - for name, chunk, until, first in cases: - # the oracle for the windows: the sequence's tokens after `first`, then one more row's worth (the last row's - # draft is never emitted; any id will do and 0 is a token of this vocabulary) - oracle = TOKENS[first + 1:] + [0] - oracle_file = work / f"oracle-{name}.txt" - oracle_file.write_text(",".join(map(str, oracle)) + "\n") - out = work / f"logits-{name}.f32" - log = work / f"run-{name}.log" - max_new = len(TOKENS) - first # rows for positions first .. 39 - rc = run_engine(a.strata, fx, fx / "pack", TOKENS, chunk, until, oracle_file, out, max_new, log) - if rc == 77 or (rc != 0 and "no CUDA device" in log.read_text()): - print(f"qwen36_runner_check: {log.read_text().strip().splitlines()[-1]}: skipped", file=sys.stderr) - return 77 - if rc != 0: - print(log.read_text()[-3000:]) - check(False, f"{name}: the engine exited {rc} (log {log})") - continue - rows = load_rows(out) - if rows.shape[0] != max_new: - check(False, f"{name}: {rows.shape[0]} rows dumped, expected {max_new}") - continue - logits[name] = rows - worst, worstq, top1, top1q, miss, ambiguous = 0.0, 0.0, 0, 0, [], [] - for i in range(max_new): - p = first + i - worst = max(worst, rel_l2(rows[i], ref[p])) - worstq = max(worstq, rel_l2(rows[i], refq[p])) - # a position where the F32 and Q8 oracles themselves disagree is a near tie: it cannot discriminate the - # engine (which rounds activations as the Q8 oracle does), so it is reported, not gated - if int(ref[p].argmax()) != int(refq[p].argmax()): - ambiguous.append(p) - continue - same = int(rows[i].argmax()) == int(refq[p].argmax()) - top1q += same - top1 += int(rows[i].argmax()) == int(ref[p].argmax()) - if not same: - miss.append(p) - n_gated = max_new - len(ambiguous) - check(worstq <= TOL_LOGITS, f"{name}: logits per position {first}..39: worst rel L2 F32 {worst:.2e} | Q8 {worstq:.2e} (Q8 <= {TOL_LOGITS:.0e})") - check(top1q == n_gated, f"{name}: argmax equals the Q8 oracle's at {top1q} of {n_gated} unambiguous positions" - + (f" (differs at {miss})" if miss else "") - + (f"; {len(ambiguous)} near-tie positions where the oracles disagree were not gated: {ambiguous}" if ambiguous else "")) - if "c7" in logits and "c40" in logits: - d = rel_l2(logits["c7"], logits["c40"]) - check(d <= TOL_LOGITS, f"c7 vs c40: the two prompt chunkings' rows 35..39 agree: rel L2 {d:.2e} (<= {TOL_LOGITS:.0e})") - if "c7" in logits and "ar" in logits: - d = rel_l2(logits["c7"], logits["ar"][34:]) - check(d <= TOL_LOGITS, f"c7 vs ar: the prompt path's rows 35..39 against the decode path's: rel L2 {d:.2e}") - - # the mutation-sensitivity gate: 4 KB of blk.1.ffn_gate_inp.weight (BF16 in dense.bin) flipped in a copy of the pack - if "c7" in logits: - mpack = work / "pack-mutated" - shutil.copytree(fx / "pack", mpack) - src_off = None - for line in (mpack / "index.txt").read_text().splitlines(): - parts = line.split() - if parts and parts[0] == "blk.1.ffn_gate_inp.weight": - src_off, src_bytes = int(parts[3]), int(parts[4]) - break - if src_off is None: - check(False, "mutation: blk.1.ffn_gate_inp.weight is not in index.txt") - else: - with open(mpack / "dense.bin", "r+b") as f: - f.seek(src_off) - blk = bytearray(f.read(4096)) - for i in range(len(blk)): - blk[i] ^= 0x55 # every byte flipped: the row's BF16 values are no longer the router's - f.seek(src_off) - f.write(blk) - oracle_file = work / "oracle-c7.txt" - out = work / "logits-mutated.f32" - log = work / "run-mutated.log" - rc = run_engine(a.strata, fx, mpack, TOKENS, 7, 35, oracle_file, out, 5, log) - if rc != 0: - print(log.read_text()[-2000:]) - check(False, f"mutation: the engine exited {rc} on the mutated pack (log {log})") - else: - moved = rel_l1(load_rows(out), logits["c7"]) - check(moved > MUTATION_MIN, f"mutation: 4 KB of blk.1.ffn_gate_inp.weight flipped moves the logits by rel L1 {moved:.2e} (> {MUTATION_MIN:.0e})") - if not a.keep: - shutil.rmtree(work, ignore_errors=True) - else: - print(f"work directory kept: {work}") - print(f"{'PASS' if fails == 0 else 'FAIL'}: {fails} failure(s)") - return 0 if fails == 0 else 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tests/python/qwen36_runner_fixture.py b/tests/python/qwen36_runner_fixture.py deleted file mode 100644 index 0ef76c2..0000000 --- a/tests/python/qwen36_runner_fixture.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env python3 -"""The Qwen3.6 runner harness's fixture (docs/qwen36-port/step4-runner.md): the synthetic qwen35moe model at the real -per-layer geometry (tests/python/qwen36_prefill_fixture.py's `full4`: 4 layers, three DeltaNet and one full attention, -n_embd 2048, 16 experts top-8 of 512), written as a file a NATIVE PACK can be built from, the pack itself -(tools/iq_pack.py, with a 4 x 16 expert profile ranking every pair), and the oracle's dumps for the three sequences the -verify window and the streaming runner are held to: - - o8 8 tokens "hello wo" the verify window's rows (one window) - o11 11 tokens "hello world" two windows, 8 + 3 (a commit between them) - o40 40 tokens "the quick brown fox jumps ..." every position - -each with --all-logits, as the F32 oracle (oN) and in its Q8 mode (oN_q8, --act-quant q8: the activations rounded to -Q8 before every quantized matmul, as ggml and the engine's int8 paths do - the policy's reference for such a path). - -The file differs from the prompt-path fixture in one tensor: `token_embd.weight` is Q8_0 (a pack's embedding must be -a type `iq_embed_rows` serves; the oracle dequantizes it with gguf-py, bit-identical to ggml). Without numpy or -gguf-py it writes /SKIP with the reason and exits 0; the tests exit 77 on seeing it. - - python3 -I tests/python/qwen36_runner_fixture.py --out DIR [--seed 0] [--no-oracle] -""" -from __future__ import annotations - -import argparse -import json -import os -import pathlib -import subprocess -import sys - -HERE = pathlib.Path(__file__).resolve().parent -ROOT = HERE.parent.parent -sys.path.insert(0, str(ROOT / "tools")) -sys.path.insert(0, str(HERE)) - -try: - import qwen36_prefill_fixture as pf # the writer, the geometry, the 40 tokens; imports numpy and gguf-py - import make_profile -except ImportError as e: - print(f"qwen36_runner_fixture: {e}", file=sys.stderr) - out = None - for i, a in enumerate(sys.argv[1:], 1): - if a == "--out" and i < len(sys.argv) - 1: - out = sys.argv[i + 1] - elif a.startswith("--out="): - out = a[len("--out="):] - if out: - pathlib.Path(out).mkdir(parents=True, exist_ok=True) - (pathlib.Path(out) / "SKIP").write_text(f"{e}\n") - sys.exit(0) - -CASES = { - "o8": [ord(c) for c in "hello wo"], - "o11": [ord(c) for c in "hello world"], - "o40": pf.TOKENS, -} - - -def oracle(gguf: str, dump: str, tokens: list[int], extra: list[str]) -> None: - cmd = [sys.executable, "-I", str(ROOT / "ref" / "qwen36.py"), gguf, "--tokens", ",".join(map(str, tokens)), - "--dump", dump] + extra - env = dict(os.environ) - env.setdefault("STRATA_GGUF_PY", pf._paths.gguf_py()) - subprocess.run(cmd, check=True, env=env, stdout=subprocess.DEVNULL) - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - ap.add_argument("--out", required=True) - ap.add_argument("--seed", type=int, default=0) - ap.add_argument("--no-oracle", action="store_true", help="write the GGUF and the pack only") - a = ap.parse_args() - out = pathlib.Path(a.out) - out.mkdir(parents=True, exist_ok=True) - (out / "SKIP").unlink(missing_ok=True) - c = pf.cfg("full4", a.seed) - gguf = out / "full4.gguf" - n, nq = pf.write(str(gguf), c, q8_embd=True) - print(f"wrote {gguf}: {n} tensors ({nq} Q8_0, token_embd included), {c.n_layer} layers, {c.n_expert} experts " - f"top-{c.n_expert_used}") - # the expert cache's ranking: every (layer, expert) pair, layer-major, so a cache of 64 slots holds the whole model - profile = out / "profile.bin" - ranked = [(l, e) for l in range(c.n_layer) for e in range(c.n_expert)] - make_profile.write_profile(str(profile), ranked, n_expert=c.n_expert, n_layer=c.n_layer) - # the pack: the tokenizer export is for real files (the synthetic vocabulary is the 128 bytes and has no chat - # template), so its two marker files are written here and iq_pack.py skips the export - pack = out / "pack" - (pack / "tokenizer").mkdir(parents=True, exist_ok=True) - (pack / "tokenizer" / "vocab.json").write_text(json.dumps({chr(i): i for i in range(c.n_vocab)})) - (pack / "tokenizer" / "chat_template.jinja").write_text("{{ messages[0].content }}") - env = dict(os.environ) - env.setdefault("STRATA_GGUF_PY", pf._paths.gguf_py()) - subprocess.run([sys.executable, "-I", str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(gguf), "--out", str(pack), - "--expert-profile", str(profile)], check=True, env=env) - for name in ("index.txt", "dense.bin", "native_experts.txt", "expert-profile.bin"): - if not (pack / name).exists(): - raise SystemExit(f"the pack lacks {name}") - print(f"pack in {pack}") - if a.no_oracle: - return 0 - for name, toks in CASES.items(): - oracle(str(gguf), str(out / name), toks, ["--all-logits"]) - oracle(str(gguf), str(out / (name + "_q8")), toks, ["--all-logits", "--act-quant", "q8"]) - print(f" oracle dumps {out / name} and {out / (name + '_q8')} (activations rounded to Q8 as ggml does): " - f"{len(toks)} tokens") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tests/python/serve_max_tokens_check.py b/tests/python/serve_max_tokens_check.py deleted file mode 100644 index b5ce651..0000000 --- a/tests/python/serve_max_tokens_check.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env python3 -"""A running server must accept a request that asks for more tokens than the context has left. - -The engine refuses a request unless prompt + max_new + 8 <= context, so the front end has to keep those 8 slots out -of max_new (REGINA-112). Without that, a request with no max_tokens, or with max_tokens at or above -context - prompt - 7, is answered 500 "prompt (N tokens) + max_new (M) exceeds the context". - -usage: serve_max_tokens_check.py [HOST:]PORT (any supported model; a few tokens are generated per case) -""" -import http.client, json, sys - -target = sys.argv[1] if len(sys.argv) > 1 else "8080" -host, _, port = target.rpartition(":") -host = host or "127.0.0.1" - -def call(method, path, body=None): - c = http.client.HTTPConnection(host, int(port), timeout=600) - c.request(method, path, json.dumps(body) if body is not None else None, {"Content-Type": "application/json"}) - r = c.getresponse(); raw = r.read(); c.close() - return r.status, raw - -status, raw = call("GET", "/v1/models") -assert status == 200, (status, raw) -ctx = json.loads(raw)["data"][0]["context_length"] -base = {"messages": [{"role": "user", "content": "Reply with the single word: ok"}], "temperature": 0, - "reasoning_effort": "none"} -cases = {"no max_tokens": {}, "max_tokens = context": {"max_tokens": ctx}, "max_tokens = context - 20": {"max_tokens": ctx - 20}, - "max_completion_tokens = 2 x context": {"max_completion_tokens": 2 * ctx}} -failed = 0 -for name, extra in cases.items(): - status, raw = call("POST", "/v1/chat/completions", dict(base, **extra)) - d = json.loads(raw) - ok = status == 200 and d["choices"][0]["finish_reason"] == "stop" and d["usage"]["completion_tokens"] >= 1 - failed += not ok - print("PASS" if ok else "FAIL", name, status, d.get("error", {}).get("message", "") if status != 200 else d["usage"]) -# streamed: the refusal arrives as an error event after a 200 -c = http.client.HTTPConnection(host, int(port), timeout=600) -c.request("POST", "/v1/chat/completions", json.dumps(dict(base, stream=True)), {"Content-Type": "application/json"}) -text = c.getresponse().read().decode(errors="replace"); c.close() -ok = '"error"' not in text and '"finish_reason":"stop"' in text.replace(" ", "") and text.rstrip().endswith("[DONE]") -failed += not ok -print("PASS" if ok else "FAIL", "no max_tokens, streamed", "" if ok else text[-300:]) -print(f"context {ctx}: {len(cases) + 1 - failed} of {len(cases) + 1} pass") -sys.exit(1 if failed else 0) diff --git a/third_party/ggml/LICENSE b/third_party/ggml/LICENSE deleted file mode 100644 index e7dca55..0000000 --- a/third_party/ggml/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2023-2026 The ggml authors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/third_party/ggml/VERSION.txt b/third_party/ggml/VERSION.txt deleted file mode 100644 index 2fca135..0000000 --- a/third_party/ggml/VERSION.txt +++ /dev/null @@ -1 +0,0 @@ -3cf03257f219afbe7334045ff7c6a06ac68c627d Sun Sep 20 16:08:11 2026 +0800 diff --git a/third_party/ggml/ggml-common.h b/third_party/ggml/ggml-common.h deleted file mode 100644 index 1dbbe32..0000000 --- a/third_party/ggml/ggml-common.h +++ /dev/null @@ -1,1911 +0,0 @@ -#ifndef GGML_COMMON_DECL - -#if defined(GGML_COMMON_DECL_C) -#include - -typedef uint16_t ggml_half; -typedef uint32_t ggml_half2; - -#define GGML_COMMON_AGGR_U -#define GGML_COMMON_AGGR_S - -#define GGML_COMMON_DECL -#elif defined(GGML_COMMON_DECL_CPP) -#include - -typedef uint16_t ggml_half; -typedef uint32_t ggml_half2; - -// std-c++ allow anonymous unions but some compiler warn on it -#define GGML_COMMON_AGGR_U data -// std-c++ do not allow it. -#define GGML_COMMON_AGGR_S data - -#define GGML_COMMON_DECL -#elif defined(GGML_COMMON_DECL_METAL) -#include - -typedef half ggml_half; -typedef half2 ggml_half2; - -#define GGML_COMMON_AGGR_U -#define GGML_COMMON_AGGR_S - -#define GGML_COMMON_DECL -#elif defined(GGML_COMMON_DECL_CUDA) -#if defined(GGML_COMMON_DECL_MUSA) -#include -#else -#include -#endif -#include - -typedef half ggml_half; -typedef half2 ggml_half2; - -#define GGML_COMMON_AGGR_U -#define GGML_COMMON_AGGR_S data - -#define GGML_COMMON_DECL -#elif defined(GGML_COMMON_DECL_HIP) -#include -#include - -typedef half ggml_half; -typedef half2 ggml_half2; - -#define GGML_COMMON_AGGR_U -#define GGML_COMMON_AGGR_S data - -#define GGML_COMMON_DECL -#elif defined(GGML_COMMON_DECL_SYCL) -#include -#include - -typedef sycl::half ggml_half; -typedef sycl::half2 ggml_half2; - -#define GGML_COMMON_AGGR_U -#define GGML_COMMON_AGGR_S data - -#define GGML_COMMON_DECL -#endif - -#if defined(GGML_COMMON_DECL) - -#ifndef __cplusplus -#ifndef static_assert -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201100L) -#define static_assert(cond, msg) _Static_assert(cond, msg) -#else -#define static_assert(cond, msg) struct global_scope_noop_trick -#endif -#endif -#endif // __cplusplus - -// QK = number of values after dequantization -// QK_K = super-block size - -#define QK_K 256 -#define K_SCALE_SIZE 12 - -#if defined(GGML_COMMON_DECL_CUDA) || defined(GGML_COMMON_DECL_HIP) || defined(GGML_COMMON_DECL_SYCL) -// QR = QK / number of values before dequantization -// QI = number of 32 bit integers before dequantization - -#define QI1_0 (QK1_0 / 32) -#define QR1_0 1 - -#define QI2_0 (QK2_0 / 32) -#define QR2_0 1 - - -#define QI4_0 (QK4_0 / (4 * QR4_0)) -#define QR4_0 2 - -#define QI4_1 (QK4_1 / (4 * QR4_1)) -#define QR4_1 2 - -#define QI_MXFP4 (QK_MXFP4 / (4 * QR_MXFP4)) -#define QR_MXFP4 2 - -#define QI_NVFP4 (QK_NVFP4 / (4 * QR_NVFP4)) -#define QR_NVFP4 2 - -#define QI5_0 (QK5_0 / (4 * QR5_0)) -#define QR5_0 2 - -#define QI5_1 (QK5_1 / (4 * QR5_1)) -#define QR5_1 2 - -#define QI8_0 (QK8_0 / (4 * QR8_0)) -#define QR8_0 1 - -#define QI8_1 (QK8_1 / (4 * QR8_1)) -#define QR8_1 1 - -#define QI2_K (QK_K / (4*QR2_K)) -#define QR2_K 4 - -#define QI3_K (QK_K / (4*QR3_K)) -#define QR3_K 4 - -#define QI4_K (QK_K / (4*QR4_K)) -#define QR4_K 2 - -#define QI5_K (QK_K / (4*QR5_K)) -#define QR5_K 2 - -#define QI6_K (QK_K / (4*QR6_K)) -#define QR6_K 2 - -#define QI2_XXS (QK_K / (4*QR2_XXS)) -#define QR2_XXS 4 - -#define QI2_XS (QK_K / (4*QR2_XS)) -#define QR2_XS 4 - -#define QI2_S (QK_K / (4*QR2_S)) -#define QR2_S 4 - -#define QI3_XXS (QK_K / (4*QR3_XXS)) -#define QR3_XXS 4 - -#define QI3_XS (QK_K / (4*QR3_XS)) -#define QR3_XS 4 - -#define QI1_S (QK_K / (4*QR1_S)) -#define QR1_S 8 - -#define QI1_M (QK_K / (4*QR1_M)) -#define QR1_M 8 - -#define QI4_NL (QK4_NL / (4*QR4_NL)) -#define QR4_NL 2 - -#define QI4_XS (QK_K / (4*QR4_XS)) -#define QR4_XS 2 - -#define QI3_S (QK_K / (4*QR3_S)) -#define QR3_S 4 - -#endif // GGML_COMMON_DECL_CUDA || GGML_COMMON_DECL_HIP - -#ifdef _MSC_VER -#define GGML_EXTENSION -#else // _MSC_VER -#define GGML_EXTENSION __extension__ -#endif // _MSC_VER - -#define QK1_0 128 -typedef struct { - ggml_half d; // delta - uint8_t qs[QK1_0 / 8]; // bits / quants -} block_q1_0; -static_assert(sizeof(block_q1_0) == sizeof(ggml_half) + QK1_0 / 8, "wrong q1_0 block size/padding"); - -#define QK2_0 64 -typedef struct { - ggml_half d; // delta (scale) - uint8_t qs[QK2_0 / 4]; // 2 bits per element -} block_q2_0; -static_assert(sizeof(block_q2_0) == sizeof(ggml_half) + QK2_0 / 4, "wrong q2_0 block size/padding"); - -#define QK4_0 32 -typedef struct { - ggml_half d; // delta - uint8_t qs[QK4_0 / 2]; // nibbles / quants -} block_q4_0; -static_assert(sizeof(block_q4_0) == sizeof(ggml_half) + QK4_0 / 2, "wrong q4_0 block size/padding"); - -#define QK4_1 32 -typedef struct { - GGML_EXTENSION union { - struct { - ggml_half d; // delta - ggml_half m; // min - } GGML_COMMON_AGGR_S; - ggml_half2 dm; - } GGML_COMMON_AGGR_U; - uint8_t qs[QK4_1 / 2]; // nibbles / quants -} block_q4_1; -static_assert(sizeof(block_q4_1) == 2 * sizeof(ggml_half) + QK4_1 / 2, "wrong q4_1 block size/padding"); - -#define QK_MXFP4 32 -typedef struct { - uint8_t e; // E8M0 - uint8_t qs[QK_MXFP4/2]; -} block_mxfp4; -static_assert(sizeof(block_mxfp4) == sizeof(uint8_t) + QK_MXFP4/2, "wrong mxfp4 block size/padding"); - -#define QK_NVFP4 64 -#define QK_NVFP4_SUB 16 // sub-block size for per-group scales -typedef struct { - uint8_t d[QK_NVFP4/QK_NVFP4_SUB]; // UE4M3 scales (4 bytes, one per 16-element sub-block) - uint8_t qs[QK_NVFP4/2]; // packed 4-bit E2M1 values (32 bytes) -} block_nvfp4; -static_assert(sizeof(block_nvfp4) == sizeof(uint8_t)*(QK_NVFP4/QK_NVFP4_SUB) + QK_NVFP4/2, "wrong nvfp4 block size/padding"); - -#define QK5_0 32 -typedef struct { - ggml_half d; // delta - uint8_t qh[4]; // 5-th bit of quants - uint8_t qs[QK5_0 / 2]; // nibbles / quants -} block_q5_0; -static_assert(sizeof(block_q5_0) == sizeof(ggml_half) + sizeof(uint32_t) + QK5_0 / 2, "wrong q5_0 block size/padding"); - -#define QK5_1 32 -typedef struct { - GGML_EXTENSION union { - struct { - ggml_half d; // delta - ggml_half m; // min - } GGML_COMMON_AGGR_S; - ggml_half2 dm; - } GGML_COMMON_AGGR_U; - uint8_t qh[4]; // 5-th bit of quants - uint8_t qs[QK5_1 / 2]; // nibbles / quants -} block_q5_1; -static_assert(sizeof(block_q5_1) == 2 * sizeof(ggml_half) + sizeof(uint32_t) + QK5_1 / 2, "wrong q5_1 block size/padding"); - -#define QK8_0 32 -typedef struct { - ggml_half d; // delta - int8_t qs[QK8_0]; // quants -} block_q8_0; -static_assert(sizeof(block_q8_0) == sizeof(ggml_half) + QK8_0, "wrong q8_0 block size/padding"); - -#define QK8_1 32 -typedef struct { - GGML_EXTENSION union { - struct { - ggml_half d; // delta - ggml_half s; // d * sum(qs[i]) - } GGML_COMMON_AGGR_S; - ggml_half2 ds; - } GGML_COMMON_AGGR_U; - int8_t qs[QK8_1]; // quants -} block_q8_1; -static_assert(sizeof(block_q8_1) == 2*sizeof(ggml_half) + QK8_1, "wrong q8_1 block size/padding"); - -// -// Ternary quantization -// - -// 1.6875 bpw -typedef struct { - uint8_t qs[(QK_K - 4 * QK_K / 64) / 5]; // 5 elements per byte (3^5 = 243 < 256) - uint8_t qh[QK_K/64]; // 4 elements per byte - ggml_half d; -} block_tq1_0; -static_assert(sizeof(block_tq1_0) == sizeof(ggml_half) + QK_K / 64 + (QK_K - 4 * QK_K / 64) / 5, "wrong tq1_0 block size/padding"); - -// 2.0625 bpw -typedef struct { - uint8_t qs[QK_K/4]; // 2 bits per element - ggml_half d; -} block_tq2_0; -static_assert(sizeof(block_tq2_0) == sizeof(ggml_half) + QK_K / 4, "wrong tq2_0 block size/padding"); - -// -// Super-block quantization structures -// - -// 2-bit quantization -// weight is represented as x = a * q + b -// 16 blocks of 16 elements each -// Effectively 2.625 bits per weight -typedef struct { - uint8_t scales[QK_K/16]; // scales and mins, quantized with 4 bits - uint8_t qs[QK_K/4]; // quants - GGML_EXTENSION union { - struct { - ggml_half d; // super-block scale for quantized scales - ggml_half dmin; // super-block scale for quantized mins - } GGML_COMMON_AGGR_S; - ggml_half2 dm; - } GGML_COMMON_AGGR_U; -} block_q2_K; -static_assert(sizeof(block_q2_K) == 2*sizeof(ggml_half) + QK_K/16 + QK_K/4, "wrong q2_K block size/padding"); - -// 3-bit quantization -// weight is represented as x = a * q -// 16 blocks of 16 elements each -// Effectively 3.4375 bits per weight -typedef struct { - uint8_t hmask[QK_K/8]; // quants - high bit - uint8_t qs[QK_K/4]; // quants - low 2 bits - uint8_t scales[12]; // scales, quantized with 6 bits - ggml_half d; // super-block scale -} block_q3_K; -static_assert(sizeof(block_q3_K) == sizeof(ggml_half) + QK_K / 4 + QK_K / 8 + 12, "wrong q3_K block size/padding"); - -// 4-bit quantization -// 8 blocks of 32 elements each -// weight is represented as x = a * q + b -// Effectively 4.5 bits per weight -typedef struct { - GGML_EXTENSION union { - struct { - ggml_half d; // super-block scale for quantized scales - ggml_half dmin; // super-block scale for quantized mins - } GGML_COMMON_AGGR_S; - ggml_half2 dm; - } GGML_COMMON_AGGR_U; - uint8_t scales[K_SCALE_SIZE]; // scales and mins, quantized with 6 bits - uint8_t qs[QK_K/2]; // 4--bit quants -} block_q4_K; -static_assert(sizeof(block_q4_K) == 2*sizeof(ggml_half) + K_SCALE_SIZE + QK_K/2, "wrong q4_K block size/padding"); - -// 5-bit quantization -// 8 blocks of 32 elements each -// weight is represented as x = a * q + b -// Effectively 5.5 bits per weight -typedef struct { - GGML_EXTENSION union { - struct { - ggml_half d; // super-block scale for quantized scales - ggml_half dmin; // super-block scale for quantized mins - } GGML_COMMON_AGGR_S; - ggml_half2 dm; - } GGML_COMMON_AGGR_U; - uint8_t scales[K_SCALE_SIZE]; // scales and mins, quantized with 6 bits - uint8_t qh[QK_K/8]; // quants, high bit - uint8_t qs[QK_K/2]; // quants, low 4 bits -} block_q5_K; -static_assert(sizeof(block_q5_K) == 2*sizeof(ggml_half) + K_SCALE_SIZE + QK_K/2 + QK_K/8, "wrong q5_K block size/padding"); - -// 6-bit quantization -// weight is represented as x = a * q -// 16 blocks of 16 elements each -// Effectively 6.5625 bits per weight -typedef struct { - uint8_t ql[QK_K/2]; // quants, lower 4 bits - uint8_t qh[QK_K/4]; // quants, upper 2 bits - int8_t scales[QK_K/16]; // scales, quantized with 8 bits - ggml_half d; // super-block scale -} block_q6_K; -static_assert(sizeof(block_q6_K) == sizeof(ggml_half) + QK_K / 16 + 3*QK_K/4, "wrong q6_K block size/padding"); - -// This is only used for intermediate quantization and dot products -typedef struct { - float d; // delta - int8_t qs[QK_K]; // quants - int16_t bsums[QK_K/16]; // sum of quants in groups of 16 -} block_q8_K; -static_assert(sizeof(block_q8_K) == sizeof(float) + QK_K + QK_K/16*sizeof(int16_t), "wrong q8_K block size/padding"); - -// (Almost) "true" 2-bit quantization. -// Due to the need to use blocks as per ggml design, it ends up using -// 2.0625 bpw because of the 16-bit scale for each block of 256. -typedef struct { - ggml_half d; - uint16_t qs[QK_K/8]; -} block_iq2_xxs; -static_assert(sizeof(block_iq2_xxs) == sizeof(ggml_half) + QK_K/8*sizeof(uint16_t), "wrong iq2_xxs block size/padding"); - -// 2.3125 bpw quants -typedef struct { - ggml_half d; - uint16_t qs[QK_K/8]; - uint8_t scales[QK_K/32]; -} block_iq2_xs; -static_assert(sizeof(block_iq2_xs) == sizeof(ggml_half) + QK_K/8*sizeof(uint16_t) + QK_K/32, "wrong iq2_xs block size/padding"); - -// 2.5625 bpw quants -typedef struct { - ggml_half d; - uint8_t qs[QK_K/4]; - uint8_t qh[QK_K/32]; - uint8_t scales[QK_K/32]; -} block_iq2_s; -static_assert(sizeof(block_iq2_s) == sizeof(ggml_half) + QK_K/4 + QK_K/16, "wrong iq2_s block size/padding"); - -// (Almost) "true" 3-bit quantization. -// Due to the need to use blocks as per ggml design, it ends up using -// 3.0625 bpw because of the 16-bit scale for each block of 256. -typedef struct { - ggml_half d; - uint8_t qs[3*QK_K/8]; -} block_iq3_xxs; -static_assert(sizeof(block_iq3_xxs) == sizeof(ggml_half) + 3*(QK_K/8), "wrong iq3_xxs block size/padding"); - -// 3.4375 bpw -#define IQ3S_N_SCALE QK_K/64 -typedef struct { - ggml_half d; - uint8_t qs[QK_K/4]; - uint8_t qh[QK_K/32]; - uint8_t signs[QK_K/8]; - uint8_t scales[IQ3S_N_SCALE]; -} block_iq3_s; -static_assert(sizeof(block_iq3_s) == sizeof(ggml_half) + 13*(QK_K/32) + IQ3S_N_SCALE, "wrong iq3_s block size/padding"); - -// 1.5625 bpw -typedef struct { - ggml_half d; - uint8_t qs[QK_K/8]; - uint16_t qh[QK_K/32]; -} block_iq1_s; -static_assert(sizeof(block_iq1_s) == sizeof(ggml_half) + QK_K/8 + QK_K/16, "wrong iq1_s block size/padding"); - -// 1.75 bpw -typedef struct { - uint8_t qs[QK_K/8]; // grid index, low 8 bits - uint8_t qh[QK_K/16]; // grid index, high 3 bits + grid shift bit (for two groups of 8) - uint8_t scales[QK_K/32]; // 3-bit block scales (4-bit if QK_K == 64) -} block_iq1_m; -static_assert(sizeof(block_iq1_m) == QK_K/8 + QK_K/16 + QK_K/32, "wrong iq1_m block size/padding"); - -// Used by IQ1_M quants -typedef union { - ggml_half f16; - uint16_t u16; -} iq1m_scale_t; - -// Non-linear quants -#define QK4_NL 32 -typedef struct { - ggml_half d; - uint8_t qs[QK4_NL/2]; -} block_iq4_nl; -static_assert(sizeof(block_iq4_nl) == sizeof(ggml_half) + QK4_NL/2, "wrong iq4_nl block size/padding"); - -typedef struct { - ggml_half d; - uint16_t scales_h; - uint8_t scales_l[QK_K/64]; - uint8_t qs[QK_K/2]; -} block_iq4_xs; -static_assert(sizeof(block_iq4_xs) == sizeof(ggml_half) + sizeof(uint16_t) + QK_K/64 + QK_K/2, "wrong iq4_xs block size/padding"); - -#endif // GGML_COMMON_DECL -#endif // GGML_COMMON_DECL - -//////////////////////////////////////////////////////////////////////////////// - -#ifndef GGML_COMMON_IMPL - -#if defined(GGML_COMMON_IMPL_C) -#include - -#define GGML_TABLE_BEGIN(type, name, size) static const type name[size] = { -#define GGML_TABLE_END() }; - -#define GGML_COMMON_IMPL -#elif defined(GGML_COMMON_IMPL_CPP) -#include - -#define GGML_TABLE_BEGIN(type, name, size) static const type name[size] = { -#define GGML_TABLE_END() }; - -#define GGML_COMMON_IMPL -#elif defined(GGML_COMMON_IMPL_METAL) -#include - -#define GGML_TABLE_BEGIN(type, name, size) static const constant type name[size] = { -#define GGML_TABLE_END() }; - -#define GGML_COMMON_IMPL -#elif defined(GGML_COMMON_IMPL_CUDA) || defined(GGML_COMMON_IMPL_HIP) || defined(GGML_COMMON_IMPL_MUSA) -#include - -#define GGML_TABLE_BEGIN(type, name, size) static const __device__ type name[size] = { -#define GGML_TABLE_END() }; - -#define GGML_COMMON_IMPL -#elif defined(GGML_COMMON_IMPL_SYCL) - -#include - -#define GGML_TABLE_BEGIN(type, name, size) static const type name[size] = { -#define GGML_TABLE_END() }; - -#define GGML_COMMON_IMPL -#endif - -#if defined(GGML_COMMON_IMPL) - -GGML_TABLE_BEGIN(uint8_t, kmask_iq2xs, 8) - 1, 2, 4, 8, 16, 32, 64, 128 -GGML_TABLE_END() - -GGML_TABLE_BEGIN(uint8_t, ksigns_iq2xs, 128) - 0, 129, 130, 3, 132, 5, 6, 135, 136, 9, 10, 139, 12, 141, 142, 15, - 144, 17, 18, 147, 20, 149, 150, 23, 24, 153, 154, 27, 156, 29, 30, 159, - 160, 33, 34, 163, 36, 165, 166, 39, 40, 169, 170, 43, 172, 45, 46, 175, - 48, 177, 178, 51, 180, 53, 54, 183, 184, 57, 58, 187, 60, 189, 190, 63, - 192, 65, 66, 195, 68, 197, 198, 71, 72, 201, 202, 75, 204, 77, 78, 207, - 80, 209, 210, 83, 212, 85, 86, 215, 216, 89, 90, 219, 92, 221, 222, 95, - 96, 225, 226, 99, 228, 101, 102, 231, 232, 105, 106, 235, 108, 237, 238, 111, - 240, 113, 114, 243, 116, 245, 246, 119, 120, 249, 250, 123, 252, 125, 126, 255, -GGML_TABLE_END() - -GGML_TABLE_BEGIN(uint64_t, ksigns64, 128) - 0x0000000000000000, 0xff000000000000ff, 0xff0000000000ff00, 0x000000000000ffff, - 0xff00000000ff0000, 0x0000000000ff00ff, 0x0000000000ffff00, 0xff00000000ffffff, - 0xff000000ff000000, 0x00000000ff0000ff, 0x00000000ff00ff00, 0xff000000ff00ffff, - 0x00000000ffff0000, 0xff000000ffff00ff, 0xff000000ffffff00, 0x00000000ffffffff, - 0xff0000ff00000000, 0x000000ff000000ff, 0x000000ff0000ff00, 0xff0000ff0000ffff, - 0x000000ff00ff0000, 0xff0000ff00ff00ff, 0xff0000ff00ffff00, 0x000000ff00ffffff, - 0x000000ffff000000, 0xff0000ffff0000ff, 0xff0000ffff00ff00, 0x000000ffff00ffff, - 0xff0000ffffff0000, 0x000000ffffff00ff, 0x000000ffffffff00, 0xff0000ffffffffff, - 0xff00ff0000000000, 0x0000ff00000000ff, 0x0000ff000000ff00, 0xff00ff000000ffff, - 0x0000ff0000ff0000, 0xff00ff0000ff00ff, 0xff00ff0000ffff00, 0x0000ff0000ffffff, - 0x0000ff00ff000000, 0xff00ff00ff0000ff, 0xff00ff00ff00ff00, 0x0000ff00ff00ffff, - 0xff00ff00ffff0000, 0x0000ff00ffff00ff, 0x0000ff00ffffff00, 0xff00ff00ffffffff, - 0x0000ffff00000000, 0xff00ffff000000ff, 0xff00ffff0000ff00, 0x0000ffff0000ffff, - 0xff00ffff00ff0000, 0x0000ffff00ff00ff, 0x0000ffff00ffff00, 0xff00ffff00ffffff, - 0xff00ffffff000000, 0x0000ffffff0000ff, 0x0000ffffff00ff00, 0xff00ffffff00ffff, - 0x0000ffffffff0000, 0xff00ffffffff00ff, 0xff00ffffffffff00, 0x0000ffffffffffff, - 0xffff000000000000, 0x00ff0000000000ff, 0x00ff00000000ff00, 0xffff00000000ffff, - 0x00ff000000ff0000, 0xffff000000ff00ff, 0xffff000000ffff00, 0x00ff000000ffffff, - 0x00ff0000ff000000, 0xffff0000ff0000ff, 0xffff0000ff00ff00, 0x00ff0000ff00ffff, - 0xffff0000ffff0000, 0x00ff0000ffff00ff, 0x00ff0000ffffff00, 0xffff0000ffffffff, - 0x00ff00ff00000000, 0xffff00ff000000ff, 0xffff00ff0000ff00, 0x00ff00ff0000ffff, - 0xffff00ff00ff0000, 0x00ff00ff00ff00ff, 0x00ff00ff00ffff00, 0xffff00ff00ffffff, - 0xffff00ffff000000, 0x00ff00ffff0000ff, 0x00ff00ffff00ff00, 0xffff00ffff00ffff, - 0x00ff00ffffff0000, 0xffff00ffffff00ff, 0xffff00ffffffff00, 0x00ff00ffffffffff, - 0x00ffff0000000000, 0xffffff00000000ff, 0xffffff000000ff00, 0x00ffff000000ffff, - 0xffffff0000ff0000, 0x00ffff0000ff00ff, 0x00ffff0000ffff00, 0xffffff0000ffffff, - 0xffffff00ff000000, 0x00ffff00ff0000ff, 0x00ffff00ff00ff00, 0xffffff00ff00ffff, - 0x00ffff00ffff0000, 0xffffff00ffff00ff, 0xffffff00ffffff00, 0x00ffff00ffffffff, - 0xffffffff00000000, 0x00ffffff000000ff, 0x00ffffff0000ff00, 0xffffffff0000ffff, - 0x00ffffff00ff0000, 0xffffffff00ff00ff, 0xffffffff00ffff00, 0x00ffffff00ffffff, - 0x00ffffffff000000, 0xffffffffff0000ff, 0xffffffffff00ff00, 0x00ffffffff00ffff, - 0xffffffffffff0000, 0x00ffffffffff00ff, 0x00ffffffffffff00, 0xffffffffffffffff, -GGML_TABLE_END() - - -GGML_TABLE_BEGIN(uint64_t, iq2xxs_grid, 256) - 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, - 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x08080808082b0808, - 0x08080808082b082b, 0x08080808082b2b08, 0x08080808082b2b2b, 0x0808080819080819, - 0x0808080819081908, 0x0808080819190808, 0x0808080819192b08, 0x08080808192b0819, - 0x08080808192b1908, 0x080808082b080808, 0x080808082b08082b, 0x080808082b082b2b, - 0x080808082b2b082b, 0x0808081908080819, 0x0808081908081908, 0x0808081908190808, - 0x0808081908191919, 0x0808081919080808, 0x080808192b081908, 0x080808192b192b08, - 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b082b082b, 0x0808082b2b08082b, - 0x0808190808080819, 0x0808190808081908, 0x0808190808190808, 0x08081908082b0819, - 0x08081908082b1908, 0x0808190819080808, 0x080819081908082b, 0x0808190819082b08, - 0x08081908192b0808, 0x080819082b080819, 0x080819082b081908, 0x080819082b190808, - 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b, 0x0808191908082b08, - 0x08081919082b0808, 0x080819191908192b, 0x08081919192b2b19, 0x080819192b080808, - 0x080819192b190819, 0x0808192b08082b19, 0x0808192b08190808, 0x0808192b19080808, - 0x0808192b2b081908, 0x0808192b2b2b1908, 0x08082b0808080808, 0x08082b0808081919, - 0x08082b0808082b08, 0x08082b0808191908, 0x08082b08082b2b08, 0x08082b0819080819, - 0x08082b0819081908, 0x08082b0819190808, 0x08082b081919082b, 0x08082b082b082b08, - 0x08082b1908081908, 0x08082b1919080808, 0x08082b2b0808082b, 0x08082b2b08191908, - 0x0819080808080819, 0x0819080808081908, 0x0819080808190808, 0x08190808082b0819, - 0x0819080819080808, 0x08190808192b0808, 0x081908082b081908, 0x081908082b190808, - 0x081908082b191919, 0x0819081908080808, 0x0819081908082b08, 0x08190819082b0808, - 0x0819081919190808, 0x0819081919192b2b, 0x081908192b080808, 0x0819082b082b1908, - 0x0819082b19081919, 0x0819190808080808, 0x0819190808082b08, 0x08191908082b0808, - 0x08191908082b1919, 0x0819190819082b19, 0x081919082b080808, 0x0819191908192b08, - 0x08191919192b082b, 0x0819192b08080808, 0x0819192b0819192b, 0x08192b0808080819, - 0x08192b0808081908, 0x08192b0808190808, 0x08192b0819080808, 0x08192b082b080819, - 0x08192b1908080808, 0x08192b1908081919, 0x08192b192b2b0808, 0x08192b2b19190819, - 0x082b080808080808, 0x082b08080808082b, 0x082b080808082b2b, 0x082b080819081908, - 0x082b0808192b0819, 0x082b08082b080808, 0x082b08082b08082b, 0x082b0819082b2b19, - 0x082b081919082b08, 0x082b082b08080808, 0x082b082b0808082b, 0x082b190808080819, - 0x082b190808081908, 0x082b190808190808, 0x082b190819080808, 0x082b19081919192b, - 0x082b191908080808, 0x082b191919080819, 0x082b1919192b1908, 0x082b192b2b190808, - 0x082b2b0808082b08, 0x082b2b08082b0808, 0x082b2b082b191908, 0x082b2b2b19081908, - 0x1908080808080819, 0x1908080808081908, 0x1908080808190808, 0x1908080808192b08, - 0x19080808082b0819, 0x19080808082b1908, 0x1908080819080808, 0x1908080819082b08, - 0x190808081919192b, 0x19080808192b0808, 0x190808082b080819, 0x190808082b081908, - 0x190808082b190808, 0x1908081908080808, 0x19080819082b0808, 0x19080819192b0819, - 0x190808192b080808, 0x190808192b081919, 0x1908082b08080819, 0x1908082b08190808, - 0x1908082b19082b08, 0x1908082b1919192b, 0x1908082b192b2b08, 0x1908190808080808, - 0x1908190808082b08, 0x19081908082b0808, 0x190819082b080808, 0x190819082b192b19, - 0x190819190819082b, 0x19081919082b1908, 0x1908192b08080808, 0x19082b0808080819, - 0x19082b0808081908, 0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919, - 0x19082b1908080808, 0x19082b1919192b08, 0x19082b19192b0819, 0x19082b192b08082b, - 0x19082b2b19081919, 0x19082b2b2b190808, 0x1919080808080808, 0x1919080808082b08, - 0x1919080808190819, 0x1919080808192b19, 0x19190808082b0808, 0x191908082b080808, - 0x191908082b082b08, 0x1919081908081908, 0x191908191908082b, 0x191908192b2b1908, - 0x1919082b2b190819, 0x191919082b190808, 0x191919082b19082b, 0x1919191908082b2b, - 0x1919192b08080819, 0x1919192b19191908, 0x19192b0808080808, 0x19192b0808190819, - 0x19192b0808192b19, 0x19192b08192b1908, 0x19192b1919080808, 0x19192b2b08082b08, - 0x192b080808081908, 0x192b080808190808, 0x192b080819080808, 0x192b0808192b2b08, - 0x192b081908080808, 0x192b081919191919, 0x192b082b08192b08, 0x192b082b192b0808, - 0x192b190808080808, 0x192b190808081919, 0x192b191908190808, 0x192b19190819082b, - 0x192b19192b081908, 0x192b2b081908082b, 0x2b08080808080808, 0x2b0808080808082b, - 0x2b08080808082b2b, 0x2b08080819080819, 0x2b0808082b08082b, 0x2b08081908081908, - 0x2b08081908192b08, 0x2b08081919080808, 0x2b08082b08190819, 0x2b08190808080819, - 0x2b08190808081908, 0x2b08190808190808, 0x2b08190808191919, 0x2b08190819080808, - 0x2b081908192b0808, 0x2b08191908080808, 0x2b0819191908192b, 0x2b0819192b191908, - 0x2b08192b08082b19, 0x2b08192b19080808, 0x2b08192b192b0808, 0x2b082b080808082b, - 0x2b082b1908081908, 0x2b082b2b08190819, 0x2b19080808081908, 0x2b19080808190808, - 0x2b190808082b1908, 0x2b19080819080808, 0x2b1908082b2b0819, 0x2b1908190819192b, - 0x2b1908192b080808, 0x2b19082b19081919, 0x2b19190808080808, 0x2b191908082b082b, - 0x2b19190819081908, 0x2b19191919190819, 0x2b192b082b080819, 0x2b192b19082b0808, - 0x2b2b08080808082b, 0x2b2b080819190808, 0x2b2b08082b081919, 0x2b2b081908082b19, - 0x2b2b082b08080808, 0x2b2b190808192b08, 0x2b2b2b0819190808, 0x2b2b2b1908081908, -GGML_TABLE_END() - -GGML_TABLE_BEGIN(uint64_t, iq2xs_grid, 512) - 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, - 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x080808080819192b, - 0x0808080808192b19, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b1919, - 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908, 0x080808081908192b, - 0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919, - 0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x080808082b080808, - 0x080808082b08082b, 0x080808082b081919, 0x080808082b082b08, 0x080808082b190819, - 0x080808082b191908, 0x080808082b192b19, 0x080808082b2b0808, 0x0808081908080819, - 0x0808081908081908, 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808, - 0x080808190819082b, 0x0808081908191919, 0x0808081908192b08, 0x0808081908192b2b, - 0x08080819082b0819, 0x08080819082b1908, 0x0808081919080808, 0x080808191908082b, - 0x0808081919081919, 0x0808081919082b08, 0x0808081919190819, 0x0808081919191908, - 0x08080819192b0808, 0x08080819192b2b08, 0x080808192b080819, 0x080808192b081908, - 0x080808192b190808, 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b08081919, - 0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, 0x0808082b082b0808, - 0x0808082b19080819, 0x0808082b19081908, 0x0808082b19190808, 0x0808082b19191919, - 0x0808082b2b080808, 0x0808082b2b082b2b, 0x0808190808080819, 0x0808190808081908, - 0x080819080808192b, 0x0808190808082b19, 0x0808190808190808, 0x080819080819082b, - 0x0808190808191919, 0x0808190808192b08, 0x08081908082b0819, 0x08081908082b1908, - 0x0808190819080808, 0x080819081908082b, 0x0808190819081919, 0x0808190819082b08, - 0x0808190819190819, 0x0808190819191908, 0x080819081919192b, 0x08081908192b0808, - 0x080819082b080819, 0x080819082b081908, 0x080819082b190808, 0x0808191908080808, - 0x080819190808082b, 0x0808191908081919, 0x0808191908082b08, 0x0808191908190819, - 0x0808191908191908, 0x08081919082b0808, 0x0808191919080819, 0x0808191919081908, - 0x0808191919190808, 0x08081919192b0819, 0x080819192b080808, 0x0808192b08080819, - 0x0808192b08081908, 0x0808192b08190808, 0x0808192b082b192b, 0x0808192b19080808, - 0x0808192b1908082b, 0x0808192b2b081908, 0x08082b0808080808, 0x08082b080808082b, - 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808082b2b, 0x08082b0808190819, - 0x08082b0808191908, 0x08082b08082b0808, 0x08082b08082b1919, 0x08082b0819080819, - 0x08082b0819081908, 0x08082b0819190808, 0x08082b0819192b08, 0x08082b082b080808, - 0x08082b082b2b0808, 0x08082b082b2b2b2b, 0x08082b1908080819, 0x08082b1908081908, - 0x08082b1908190808, 0x08082b1919080808, 0x08082b192b080819, 0x08082b192b082b19, - 0x08082b2b08080808, 0x08082b2b082b0808, 0x08082b2b082b2b08, 0x08082b2b2b19192b, - 0x08082b2b2b2b0808, 0x0819080808080819, 0x0819080808081908, 0x081908080808192b, - 0x0819080808082b19, 0x0819080808190808, 0x081908080819082b, 0x0819080808191919, - 0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908, 0x0819080819080808, - 0x081908081908082b, 0x0819080819081919, 0x0819080819082b08, 0x0819080819190819, - 0x0819080819191908, 0x08190808192b0808, 0x08190808192b2b2b, 0x081908082b080819, - 0x081908082b081908, 0x081908082b190808, 0x0819081908080808, 0x081908190808082b, - 0x0819081908081919, 0x0819081908082b08, 0x0819081908190819, 0x0819081908191908, - 0x08190819082b0808, 0x0819081919080819, 0x0819081919081908, 0x0819081919190808, - 0x081908192b080808, 0x081908192b191908, 0x081908192b19192b, 0x0819082b08080819, - 0x0819082b08081908, 0x0819082b0808192b, 0x0819082b08190808, 0x0819082b19080808, - 0x0819082b192b0808, 0x0819190808080808, 0x081919080808082b, 0x0819190808081919, - 0x0819190808082b08, 0x0819190808190819, 0x0819190808191908, 0x08191908082b0808, - 0x0819190819080819, 0x0819190819081908, 0x0819190819082b19, 0x0819190819190808, - 0x08191908192b1908, 0x081919082b080808, 0x0819191908080819, 0x0819191908081908, - 0x0819191908190808, 0x0819191919080808, 0x0819192b08080808, 0x0819192b08191908, - 0x0819192b19082b19, 0x08192b0808080819, 0x08192b0808081908, 0x08192b0808190808, - 0x08192b080819082b, 0x08192b0819080808, 0x08192b0819191908, 0x08192b082b08192b, - 0x08192b1908080808, 0x08192b1908081919, 0x08192b19192b192b, 0x08192b2b19190819, - 0x08192b2b2b2b2b19, 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919, - 0x082b080808082b08, 0x082b080808082b2b, 0x082b080808190819, 0x082b080808191908, - 0x082b0808082b0808, 0x082b080819080819, 0x082b080819081908, 0x082b080819190808, - 0x082b08082b080808, 0x082b08082b2b0808, 0x082b081908080819, 0x082b081908081908, - 0x082b081908190808, 0x082b081919080808, 0x082b081919082b08, 0x082b0819192b1919, - 0x082b082b08080808, 0x082b082b082b082b, 0x082b082b2b080808, 0x082b082b2b2b2b08, - 0x082b190808080819, 0x082b190808081908, 0x082b190808190808, 0x082b1908082b2b19, - 0x082b190819080808, 0x082b191908080808, 0x082b191919080819, 0x082b19191919082b, - 0x082b19192b192b19, 0x082b192b08080819, 0x082b192b08192b2b, 0x082b192b2b2b192b, - 0x082b2b0808080808, 0x082b2b0808082b08, 0x082b2b0808082b2b, 0x082b2b08082b0808, - 0x082b2b0819191919, 0x082b2b082b082b08, 0x082b2b082b2b082b, 0x082b2b19192b2b08, - 0x082b2b192b190808, 0x082b2b2b08082b08, 0x082b2b2b082b0808, 0x082b2b2b2b08082b, - 0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819, 0x1908080808081908, - 0x190808080808192b, 0x1908080808082b19, 0x1908080808190808, 0x190808080819082b, - 0x1908080808191919, 0x1908080808192b08, 0x19080808082b0819, 0x19080808082b1908, - 0x1908080819080808, 0x190808081908082b, 0x1908080819081919, 0x1908080819082b08, - 0x1908080819082b2b, 0x1908080819190819, 0x1908080819191908, 0x19080808192b0808, - 0x19080808192b1919, 0x190808082b080819, 0x190808082b081908, 0x190808082b190808, - 0x1908081908080808, 0x190808190808082b, 0x1908081908081919, 0x1908081908082b08, - 0x1908081908190819, 0x1908081908191908, 0x19080819082b0808, 0x1908081919080819, - 0x1908081919081908, 0x1908081919190808, 0x190808192b080808, 0x190808192b081919, - 0x190808192b2b082b, 0x1908082b08080819, 0x1908082b08081908, 0x1908082b08190808, - 0x1908082b0819082b, 0x1908082b082b2b19, 0x1908082b19080808, 0x1908190808080808, - 0x190819080808082b, 0x1908190808081919, 0x1908190808082b08, 0x1908190808190819, - 0x1908190808191908, 0x1908190808192b19, 0x19081908082b0808, 0x1908190819080819, - 0x1908190819081908, 0x1908190819190808, 0x190819082b080808, 0x190819082b191908, - 0x1908191908080819, 0x1908191908081908, 0x1908191908190808, 0x19081919082b1908, - 0x1908191919080808, 0x190819192b192b2b, 0x1908192b08080808, 0x1908192b08082b2b, - 0x1908192b19081908, 0x1908192b19190808, 0x19082b0808080819, 0x19082b0808081908, - 0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919, 0x19082b0819191908, - 0x19082b08192b082b, 0x19082b1908080808, 0x19082b1908190819, 0x19082b1919081908, - 0x19082b1919190808, 0x19082b19192b2b19, 0x19082b2b08081908, 0x1919080808080808, - 0x191908080808082b, 0x1919080808081919, 0x1919080808082b08, 0x1919080808190819, - 0x1919080808191908, 0x19190808082b0808, 0x19190808082b2b08, 0x1919080819080819, - 0x1919080819081908, 0x1919080819190808, 0x191908082b080808, 0x1919081908080819, - 0x1919081908081908, 0x1919081908190808, 0x1919081908191919, 0x1919081919080808, - 0x191908191908082b, 0x1919082b08080808, 0x1919082b19081908, 0x1919082b2b2b2b2b, - 0x1919190808080819, 0x1919190808081908, 0x1919190808190808, 0x19191908082b0819, - 0x1919190819080808, 0x19191908192b0808, 0x191919082b080819, 0x191919082b2b0819, - 0x1919191908080808, 0x1919191908082b08, 0x191919192b080808, 0x191919192b082b08, - 0x1919192b082b0819, 0x1919192b192b2b08, 0x1919192b2b2b0819, 0x19192b0808080808, - 0x19192b0808191908, 0x19192b0819080819, 0x19192b0819190808, 0x19192b082b192b19, - 0x19192b1908192b2b, 0x19192b1919080808, 0x19192b191908082b, 0x19192b2b2b081919, - 0x192b080808080819, 0x192b080808081908, 0x192b080808190808, 0x192b080819080808, - 0x192b080819191908, 0x192b0808192b082b, 0x192b08082b08192b, 0x192b08082b2b2b19, - 0x192b081908080808, 0x192b082b082b1908, 0x192b082b19082b2b, 0x192b082b2b19082b, - 0x192b190808080808, 0x192b19080819192b, 0x192b191908190808, 0x192b191919080808, - 0x192b191919081919, 0x192b19192b2b1908, 0x192b2b0808080819, 0x192b2b08192b2b2b, - 0x192b2b19082b1919, 0x192b2b2b0808192b, 0x192b2b2b19191908, 0x192b2b2b192b082b, - 0x2b08080808080808, 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08, - 0x2b08080808190819, 0x2b08080808191908, 0x2b080808082b0808, 0x2b080808082b2b2b, - 0x2b08080819080819, 0x2b08080819081908, 0x2b08080819190808, 0x2b0808082b080808, - 0x2b0808082b08082b, 0x2b0808082b2b2b08, 0x2b0808082b2b2b2b, 0x2b08081908080819, - 0x2b08081908081908, 0x2b0808190808192b, 0x2b08081908190808, 0x2b08081919080808, - 0x2b08081919190819, 0x2b08081919192b19, 0x2b08082b08080808, 0x2b08082b082b0808, - 0x2b08082b2b080808, 0x2b08082b2b08082b, 0x2b08082b2b2b0808, 0x2b08082b2b2b2b08, - 0x2b08190808080819, 0x2b08190808081908, 0x2b08190808190808, 0x2b0819080819082b, - 0x2b08190808191919, 0x2b08190819080808, 0x2b081908192b0808, 0x2b0819082b082b19, - 0x2b08191908080808, 0x2b08191919081908, 0x2b0819192b2b1919, 0x2b08192b08192b08, - 0x2b08192b192b2b2b, 0x2b082b0808080808, 0x2b082b0808082b08, 0x2b082b08082b1919, - 0x2b082b0819192b2b, 0x2b082b082b080808, 0x2b082b082b08082b, 0x2b082b082b2b2b08, - 0x2b082b190808192b, 0x2b082b2b082b082b, 0x2b082b2b2b080808, 0x2b082b2b2b082b08, - 0x2b082b2b2b19192b, 0x2b082b2b2b2b2b08, 0x2b19080808080819, 0x2b19080808081908, - 0x2b19080808190808, 0x2b19080819080808, 0x2b1908081919192b, 0x2b1908082b081908, - 0x2b19081908080808, 0x2b190819082b082b, 0x2b190819192b1908, 0x2b19082b1919192b, - 0x2b19082b2b082b19, 0x2b19190808080808, 0x2b19190808081919, 0x2b19190819081908, - 0x2b19190819190808, 0x2b19190819192b08, 0x2b191919082b2b19, 0x2b1919192b190808, - 0x2b1919192b19082b, 0x2b19192b19080819, 0x2b192b0819190819, 0x2b192b082b2b192b, - 0x2b192b1919082b19, 0x2b192b2b08191919, 0x2b192b2b192b0808, 0x2b2b080808080808, - 0x2b2b08080808082b, 0x2b2b080808082b08, 0x2b2b080808082b2b, 0x2b2b0808082b0808, - 0x2b2b0808082b2b2b, 0x2b2b08082b2b0808, 0x2b2b081919190819, 0x2b2b081919192b19, - 0x2b2b08192b2b192b, 0x2b2b082b08080808, 0x2b2b082b0808082b, 0x2b2b082b08082b08, - 0x2b2b082b082b2b2b, 0x2b2b082b2b080808, 0x2b2b082b2b2b0808, 0x2b2b190819080808, - 0x2b2b19082b191919, 0x2b2b192b192b1919, 0x2b2b192b2b192b08, 0x2b2b2b0808082b2b, - 0x2b2b2b08082b0808, 0x2b2b2b08082b082b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b0808, - 0x2b2b2b082b2b2b08, 0x2b2b2b1908081908, 0x2b2b2b192b081908, 0x2b2b2b192b08192b, - 0x2b2b2b2b082b2b08, 0x2b2b2b2b082b2b2b, 0x2b2b2b2b2b190819, 0x2b2b2b2b2b2b2b2b, -GGML_TABLE_END() - -GGML_TABLE_BEGIN(uint64_t, iq2s_grid, 1024) - 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, - 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x080808080819192b, - 0x0808080808192b19, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b1919, - 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908, 0x080808081908192b, - 0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919, - 0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x08080808192b192b, - 0x08080808192b2b19, 0x080808082b080808, 0x080808082b08082b, 0x080808082b081919, - 0x080808082b082b08, 0x080808082b190819, 0x080808082b191908, 0x080808082b2b0808, - 0x080808082b2b1919, 0x080808082b2b2b2b, 0x0808081908080819, 0x0808081908081908, - 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808, 0x080808190819082b, - 0x0808081908191919, 0x0808081908192b08, 0x08080819082b0819, 0x08080819082b1908, - 0x0808081919080808, 0x080808191908082b, 0x0808081919081919, 0x0808081919082b08, - 0x0808081919190819, 0x0808081919191908, 0x080808191919192b, 0x0808081919192b19, - 0x08080819192b0808, 0x08080819192b1919, 0x08080819192b2b08, 0x080808192b080819, - 0x080808192b081908, 0x080808192b190808, 0x080808192b19082b, 0x080808192b191919, - 0x080808192b2b0819, 0x080808192b2b1908, 0x0808082b08080808, 0x0808082b0808082b, - 0x0808082b08081919, 0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, - 0x0808082b082b0808, 0x0808082b082b2b2b, 0x0808082b19080819, 0x0808082b19081908, - 0x0808082b1908192b, 0x0808082b19082b19, 0x0808082b19190808, 0x0808082b19191919, - 0x0808082b2b080808, 0x0808082b2b081919, 0x0808082b2b082b2b, 0x0808082b2b191908, - 0x0808082b2b2b082b, 0x0808190808080819, 0x0808190808081908, 0x080819080808192b, - 0x0808190808082b19, 0x0808190808190808, 0x080819080819082b, 0x0808190808191919, - 0x0808190808192b08, 0x08081908082b0819, 0x08081908082b1908, 0x08081908082b192b, - 0x08081908082b2b19, 0x0808190819080808, 0x080819081908082b, 0x0808190819081919, - 0x0808190819082b08, 0x0808190819082b2b, 0x0808190819190819, 0x0808190819191908, - 0x080819081919192b, 0x0808190819192b19, 0x08081908192b0808, 0x08081908192b082b, - 0x08081908192b1919, 0x080819082b080819, 0x080819082b081908, 0x080819082b08192b, - 0x080819082b082b19, 0x080819082b190808, 0x080819082b191919, 0x080819082b192b08, - 0x080819082b2b0819, 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b, - 0x0808191908081919, 0x0808191908082b08, 0x0808191908082b2b, 0x0808191908190819, - 0x0808191908191908, 0x080819190819192b, 0x0808191908192b19, 0x08081919082b0808, - 0x08081919082b1919, 0x08081919082b2b08, 0x0808191919080819, 0x0808191919081908, - 0x080819191908192b, 0x0808191919082b19, 0x0808191919190808, 0x080819191919082b, - 0x0808191919191919, 0x0808191919192b08, 0x08081919192b0819, 0x08081919192b1908, - 0x080819192b080808, 0x080819192b08082b, 0x080819192b081919, 0x080819192b082b08, - 0x080819192b190819, 0x080819192b191908, 0x080819192b2b0808, 0x0808192b08080819, - 0x0808192b08081908, 0x0808192b0808192b, 0x0808192b08082b19, 0x0808192b08190808, - 0x0808192b08191919, 0x0808192b19080808, 0x0808192b19081919, 0x0808192b19082b08, - 0x0808192b19190819, 0x0808192b19191908, 0x0808192b192b0808, 0x0808192b2b080819, - 0x0808192b2b081908, 0x0808192b2b190808, 0x08082b0808080808, 0x08082b080808082b, - 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808190819, 0x08082b0808191908, - 0x08082b080819192b, 0x08082b0808192b19, 0x08082b08082b0808, 0x08082b08082b1919, - 0x08082b08082b2b2b, 0x08082b0819080819, 0x08082b0819081908, 0x08082b081908192b, - 0x08082b0819082b19, 0x08082b0819190808, 0x08082b081919082b, 0x08082b0819191919, - 0x08082b0819192b08, 0x08082b08192b0819, 0x08082b08192b1908, 0x08082b082b080808, - 0x08082b082b081919, 0x08082b082b191908, 0x08082b082b2b2b2b, 0x08082b1908080819, - 0x08082b1908081908, 0x08082b1908190808, 0x08082b190819082b, 0x08082b1908191919, - 0x08082b1908192b08, 0x08082b19082b0819, 0x08082b1919080808, 0x08082b1919081919, - 0x08082b1919082b08, 0x08082b1919190819, 0x08082b1919191908, 0x08082b19192b0808, - 0x08082b192b080819, 0x08082b192b190808, 0x08082b2b08080808, 0x08082b2b08190819, - 0x08082b2b08191908, 0x08082b2b082b082b, 0x08082b2b082b2b08, 0x08082b2b082b2b2b, - 0x08082b2b19190808, 0x08082b2b2b192b19, 0x0819080808080819, 0x0819080808081908, - 0x081908080808192b, 0x0819080808082b19, 0x0819080808190808, 0x081908080819082b, - 0x0819080808191919, 0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908, - 0x08190808082b192b, 0x0819080819080808, 0x081908081908082b, 0x0819080819081919, - 0x0819080819082b08, 0x0819080819190819, 0x0819080819191908, 0x081908081919192b, - 0x0819080819192b19, 0x08190808192b0808, 0x08190808192b082b, 0x08190808192b1919, - 0x08190808192b2b08, 0x081908082b080819, 0x081908082b081908, 0x081908082b08192b, - 0x081908082b190808, 0x081908082b191919, 0x081908082b192b08, 0x081908082b2b0819, - 0x081908082b2b1908, 0x0819081908080808, 0x081908190808082b, 0x0819081908081919, - 0x0819081908082b08, 0x0819081908082b2b, 0x0819081908190819, 0x0819081908191908, - 0x081908190819192b, 0x0819081908192b19, 0x08190819082b0808, 0x08190819082b082b, - 0x08190819082b1919, 0x08190819082b2b08, 0x0819081919080819, 0x0819081919081908, - 0x081908191908192b, 0x0819081919082b19, 0x0819081919190808, 0x081908191919082b, - 0x0819081919191919, 0x0819081919192b08, 0x08190819192b0819, 0x08190819192b1908, - 0x081908192b080808, 0x081908192b08082b, 0x081908192b081919, 0x081908192b082b08, - 0x081908192b190819, 0x081908192b191908, 0x0819082b08080819, 0x0819082b08081908, - 0x0819082b08082b19, 0x0819082b08190808, 0x0819082b08191919, 0x0819082b082b0819, - 0x0819082b082b1908, 0x0819082b19080808, 0x0819082b19081919, 0x0819082b19190819, - 0x0819082b19191908, 0x0819082b2b080819, 0x0819082b2b081908, 0x0819082b2b190808, - 0x0819190808080808, 0x081919080808082b, 0x0819190808081919, 0x0819190808082b08, - 0x0819190808190819, 0x0819190808191908, 0x081919080819192b, 0x0819190808192b19, - 0x08191908082b0808, 0x08191908082b1919, 0x08191908082b2b08, 0x0819190819080819, - 0x0819190819081908, 0x081919081908192b, 0x0819190819082b19, 0x0819190819190808, - 0x081919081919082b, 0x0819190819191919, 0x0819190819192b08, 0x08191908192b0819, - 0x08191908192b1908, 0x081919082b080808, 0x081919082b08082b, 0x081919082b081919, - 0x081919082b082b08, 0x081919082b190819, 0x081919082b191908, 0x081919082b2b0808, - 0x0819191908080819, 0x0819191908081908, 0x081919190808192b, 0x0819191908082b19, - 0x0819191908190808, 0x081919190819082b, 0x0819191908191919, 0x0819191908192b08, - 0x08191919082b0819, 0x08191919082b1908, 0x0819191919080808, 0x081919191908082b, - 0x0819191919081919, 0x0819191919082b08, 0x0819191919190819, 0x0819191919191908, - 0x08191919192b0808, 0x081919192b080819, 0x081919192b081908, 0x081919192b190808, - 0x0819192b08080808, 0x0819192b08081919, 0x0819192b08082b08, 0x0819192b08190819, - 0x0819192b08191908, 0x0819192b082b0808, 0x0819192b19080819, 0x0819192b19081908, - 0x0819192b19190808, 0x0819192b2b080808, 0x0819192b2b2b2b2b, 0x08192b0808080819, - 0x08192b0808081908, 0x08192b080808192b, 0x08192b0808082b19, 0x08192b0808190808, - 0x08192b0808191919, 0x08192b0808192b08, 0x08192b08082b0819, 0x08192b0819080808, - 0x08192b081908082b, 0x08192b0819081919, 0x08192b0819082b08, 0x08192b0819190819, - 0x08192b0819191908, 0x08192b08192b0808, 0x08192b082b080819, 0x08192b082b081908, - 0x08192b1908080808, 0x08192b190808082b, 0x08192b1908081919, 0x08192b1908082b08, - 0x08192b1908190819, 0x08192b1908191908, 0x08192b19082b0808, 0x08192b1919080819, - 0x08192b1919081908, 0x08192b1919190808, 0x08192b19192b2b19, 0x08192b192b2b082b, - 0x08192b2b08081908, 0x08192b2b08190808, 0x08192b2b19080808, 0x08192b2b1919192b, - 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919, 0x082b080808082b08, - 0x082b080808190819, 0x082b080808191908, 0x082b08080819192b, 0x082b080808192b19, - 0x082b0808082b0808, 0x082b0808082b1919, 0x082b0808082b2b2b, 0x082b080819080819, - 0x082b080819081908, 0x082b080819190808, 0x082b08081919082b, 0x082b080819191919, - 0x082b0808192b1908, 0x082b08082b080808, 0x082b08082b082b2b, 0x082b08082b191908, - 0x082b08082b2b2b2b, 0x082b081908080819, 0x082b081908081908, 0x082b081908190808, - 0x082b08190819082b, 0x082b081908191919, 0x082b0819082b0819, 0x082b081919080808, - 0x082b08191908082b, 0x082b081919081919, 0x082b081919190819, 0x082b081919191908, - 0x082b0819192b0808, 0x082b08192b080819, 0x082b08192b081908, 0x082b08192b190808, - 0x082b082b08080808, 0x082b082b08082b2b, 0x082b082b082b082b, 0x082b082b082b2b08, - 0x082b082b082b2b2b, 0x082b082b19081908, 0x082b082b19190808, 0x082b082b2b082b08, - 0x082b082b2b082b2b, 0x082b082b2b2b2b08, 0x082b190808080819, 0x082b190808081908, - 0x082b19080808192b, 0x082b190808082b19, 0x082b190808190808, 0x082b190808191919, - 0x082b190808192b08, 0x082b1908082b0819, 0x082b1908082b1908, 0x082b190819080808, - 0x082b19081908082b, 0x082b190819081919, 0x082b190819082b08, 0x082b190819190819, - 0x082b190819191908, 0x082b1908192b0808, 0x082b19082b080819, 0x082b19082b081908, - 0x082b19082b190808, 0x082b191908080808, 0x082b191908081919, 0x082b191908082b08, - 0x082b191908190819, 0x082b191908191908, 0x082b1919082b0808, 0x082b191919080819, - 0x082b191919081908, 0x082b191919190808, 0x082b1919192b192b, 0x082b19192b080808, - 0x082b192b08080819, 0x082b192b08081908, 0x082b192b08190808, 0x082b192b19080808, - 0x082b192b19192b19, 0x082b2b0808080808, 0x082b2b0808081919, 0x082b2b0808190819, - 0x082b2b0808191908, 0x082b2b0819080819, 0x082b2b0819081908, 0x082b2b0819190808, - 0x082b2b082b082b2b, 0x082b2b082b2b2b2b, 0x082b2b1908080819, 0x082b2b1908081908, - 0x082b2b1908190808, 0x082b2b192b191919, 0x082b2b2b08082b2b, 0x082b2b2b082b082b, - 0x082b2b2b192b1908, 0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819, - 0x1908080808081908, 0x190808080808192b, 0x1908080808082b19, 0x1908080808190808, - 0x190808080819082b, 0x1908080808191919, 0x1908080808192b08, 0x1908080808192b2b, - 0x19080808082b0819, 0x19080808082b1908, 0x19080808082b192b, 0x1908080819080808, - 0x190808081908082b, 0x1908080819081919, 0x1908080819082b08, 0x1908080819082b2b, - 0x1908080819190819, 0x1908080819191908, 0x190808081919192b, 0x1908080819192b19, - 0x19080808192b0808, 0x19080808192b082b, 0x19080808192b1919, 0x190808082b080819, - 0x190808082b081908, 0x190808082b190808, 0x190808082b191919, 0x190808082b192b08, - 0x190808082b2b0819, 0x190808082b2b1908, 0x1908081908080808, 0x190808190808082b, - 0x1908081908081919, 0x1908081908082b08, 0x1908081908190819, 0x1908081908191908, - 0x190808190819192b, 0x1908081908192b19, 0x19080819082b0808, 0x19080819082b082b, - 0x19080819082b1919, 0x1908081919080819, 0x1908081919081908, 0x190808191908192b, - 0x1908081919082b19, 0x1908081919190808, 0x190808191919082b, 0x1908081919191919, - 0x1908081919192b08, 0x19080819192b0819, 0x19080819192b1908, 0x190808192b080808, - 0x190808192b08082b, 0x190808192b081919, 0x190808192b082b08, 0x190808192b190819, - 0x190808192b191908, 0x190808192b2b0808, 0x1908082b08080819, 0x1908082b08081908, - 0x1908082b08190808, 0x1908082b0819082b, 0x1908082b08191919, 0x1908082b08192b08, - 0x1908082b082b1908, 0x1908082b19080808, 0x1908082b19081919, 0x1908082b19082b08, - 0x1908082b19190819, 0x1908082b19191908, 0x1908082b192b0808, 0x1908082b2b080819, - 0x1908082b2b081908, 0x1908190808080808, 0x190819080808082b, 0x1908190808081919, - 0x1908190808082b08, 0x1908190808082b2b, 0x1908190808190819, 0x1908190808191908, - 0x190819080819192b, 0x1908190808192b19, 0x19081908082b0808, 0x19081908082b082b, - 0x19081908082b1919, 0x19081908082b2b08, 0x1908190819080819, 0x1908190819081908, - 0x190819081908192b, 0x1908190819082b19, 0x1908190819190808, 0x190819081919082b, - 0x1908190819191919, 0x1908190819192b08, 0x19081908192b0819, 0x19081908192b1908, - 0x190819082b080808, 0x190819082b08082b, 0x190819082b081919, 0x190819082b082b08, - 0x190819082b190819, 0x190819082b191908, 0x190819082b2b0808, 0x1908191908080819, - 0x1908191908081908, 0x190819190808192b, 0x1908191908082b19, 0x1908191908190808, - 0x190819190819082b, 0x1908191908191919, 0x1908191908192b08, 0x19081919082b0819, - 0x19081919082b1908, 0x1908191919080808, 0x190819191908082b, 0x1908191919081919, - 0x1908191919082b08, 0x1908191919190819, 0x1908191919191908, 0x19081919192b0808, - 0x19081919192b2b2b, 0x190819192b080819, 0x190819192b081908, 0x190819192b190808, - 0x1908192b08080808, 0x1908192b0808082b, 0x1908192b08081919, 0x1908192b08082b08, - 0x1908192b08190819, 0x1908192b08191908, 0x1908192b082b0808, 0x1908192b19080819, - 0x1908192b19081908, 0x1908192b19190808, 0x1908192b2b080808, 0x1908192b2b2b1919, - 0x19082b0808080819, 0x19082b0808081908, 0x19082b0808082b19, 0x19082b0808190808, - 0x19082b080819082b, 0x19082b0808191919, 0x19082b0808192b08, 0x19082b08082b0819, - 0x19082b08082b1908, 0x19082b0819080808, 0x19082b081908082b, 0x19082b0819081919, - 0x19082b0819082b08, 0x19082b0819190819, 0x19082b0819191908, 0x19082b08192b0808, - 0x19082b082b081908, 0x19082b082b190808, 0x19082b1908080808, 0x19082b190808082b, - 0x19082b1908081919, 0x19082b1908082b08, 0x19082b1908190819, 0x19082b1908191908, - 0x19082b19082b0808, 0x19082b1919080819, 0x19082b1919081908, 0x19082b1919190808, - 0x19082b192b080808, 0x19082b192b19192b, 0x19082b2b08080819, 0x19082b2b08081908, - 0x19082b2b08190808, 0x19082b2b19080808, 0x1919080808080808, 0x191908080808082b, - 0x1919080808081919, 0x1919080808082b08, 0x1919080808190819, 0x1919080808191908, - 0x191908080819192b, 0x1919080808192b19, 0x19190808082b0808, 0x19190808082b082b, - 0x19190808082b1919, 0x19190808082b2b08, 0x1919080819080819, 0x1919080819081908, - 0x191908081908192b, 0x1919080819082b19, 0x1919080819190808, 0x191908081919082b, - 0x1919080819191919, 0x1919080819192b08, 0x19190808192b0819, 0x19190808192b1908, - 0x191908082b080808, 0x191908082b08082b, 0x191908082b081919, 0x191908082b082b08, - 0x191908082b190819, 0x191908082b191908, 0x1919081908080819, 0x1919081908081908, - 0x191908190808192b, 0x1919081908082b19, 0x1919081908190808, 0x191908190819082b, - 0x1919081908191919, 0x1919081908192b08, 0x19190819082b0819, 0x19190819082b1908, - 0x1919081919080808, 0x191908191908082b, 0x1919081919081919, 0x1919081919082b08, - 0x1919081919190819, 0x1919081919191908, 0x19190819192b0808, 0x191908192b080819, - 0x191908192b081908, 0x191908192b190808, 0x1919082b08080808, 0x1919082b08081919, - 0x1919082b08082b08, 0x1919082b08190819, 0x1919082b08191908, 0x1919082b082b0808, - 0x1919082b19080819, 0x1919082b19081908, 0x1919082b19190808, 0x1919082b192b2b19, - 0x1919082b2b080808, 0x1919190808080819, 0x1919190808081908, 0x191919080808192b, - 0x1919190808082b19, 0x1919190808190808, 0x191919080819082b, 0x1919190808191919, - 0x1919190808192b08, 0x19191908082b0819, 0x19191908082b1908, 0x1919190819080808, - 0x191919081908082b, 0x1919190819081919, 0x1919190819082b08, 0x1919190819190819, - 0x1919190819191908, 0x19191908192b0808, 0x191919082b080819, 0x191919082b081908, - 0x191919082b190808, 0x1919191908080808, 0x191919190808082b, 0x1919191908081919, - 0x1919191908082b08, 0x1919191908190819, 0x1919191908191908, 0x19191919082b0808, - 0x1919191919080819, 0x1919191919081908, 0x1919191919190808, 0x191919192b080808, - 0x1919192b08080819, 0x1919192b08081908, 0x1919192b08190808, 0x1919192b082b192b, - 0x1919192b19080808, 0x19192b0808080808, 0x19192b080808082b, 0x19192b0808081919, - 0x19192b0808082b08, 0x19192b0808190819, 0x19192b0808191908, 0x19192b08082b0808, - 0x19192b0819080819, 0x19192b0819081908, 0x19192b0819190808, 0x19192b0819192b2b, - 0x19192b082b080808, 0x19192b1908080819, 0x19192b1908081908, 0x19192b1908190808, - 0x19192b1919080808, 0x19192b2b08080808, 0x19192b2b08192b19, 0x19192b2b2b081919, - 0x19192b2b2b2b2b08, 0x192b080808080819, 0x192b080808081908, 0x192b08080808192b, - 0x192b080808190808, 0x192b08080819082b, 0x192b080808191919, 0x192b080808192b08, - 0x192b0808082b0819, 0x192b0808082b1908, 0x192b080819080808, 0x192b080819081919, - 0x192b080819082b08, 0x192b080819190819, 0x192b080819191908, 0x192b0808192b0808, - 0x192b08082b081908, 0x192b08082b190808, 0x192b081908080808, 0x192b08190808082b, - 0x192b081908081919, 0x192b081908082b08, 0x192b081908190819, 0x192b081908191908, - 0x192b0819082b0808, 0x192b081919080819, 0x192b081919081908, 0x192b081919190808, - 0x192b08192b080808, 0x192b08192b192b19, 0x192b082b08081908, 0x192b082b08190808, - 0x192b082b19080808, 0x192b082b1919192b, 0x192b082b2b2b0819, 0x192b190808080808, - 0x192b190808081919, 0x192b190808082b08, 0x192b190808190819, 0x192b190808191908, - 0x192b1908082b0808, 0x192b190819080819, 0x192b190819081908, 0x192b190819190808, - 0x192b19082b080808, 0x192b191908080819, 0x192b191908081908, 0x192b191908190808, - 0x192b191919080808, 0x192b191919082b2b, 0x192b1919192b2b08, 0x192b19192b19082b, - 0x192b192b08080808, 0x192b192b2b191908, 0x192b2b0808080819, 0x192b2b0808081908, - 0x192b2b0808190808, 0x192b2b08192b1919, 0x192b2b082b192b08, 0x192b2b1908080808, - 0x192b2b19082b2b2b, 0x192b2b2b1908082b, 0x192b2b2b2b2b0819, 0x2b08080808080808, - 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08, 0x2b08080808190819, - 0x2b08080808191908, 0x2b08080808192b19, 0x2b080808082b0808, 0x2b080808082b1919, - 0x2b08080819080819, 0x2b08080819081908, 0x2b08080819190808, 0x2b0808081919082b, - 0x2b08080819191919, 0x2b08080819192b08, 0x2b080808192b0819, 0x2b0808082b080808, - 0x2b0808082b081919, 0x2b0808082b190819, 0x2b0808082b191908, 0x2b08081908080819, - 0x2b08081908081908, 0x2b08081908082b19, 0x2b08081908190808, 0x2b0808190819082b, - 0x2b08081908191919, 0x2b08081908192b08, 0x2b080819082b0819, 0x2b080819082b1908, - 0x2b08081919080808, 0x2b0808191908082b, 0x2b08081919081919, 0x2b08081919082b08, - 0x2b08081919190819, 0x2b08081919191908, 0x2b0808192b080819, 0x2b0808192b081908, - 0x2b0808192b190808, 0x2b0808192b2b2b19, 0x2b08082b08080808, 0x2b08082b08081919, - 0x2b08082b08082b2b, 0x2b08082b08190819, 0x2b08082b08191908, 0x2b08082b19080819, - 0x2b08082b19081908, 0x2b08082b19190808, 0x2b08190808080819, 0x2b08190808081908, - 0x2b0819080808192b, 0x2b08190808082b19, 0x2b08190808190808, 0x2b0819080819082b, - 0x2b08190808191919, 0x2b08190808192b08, 0x2b081908082b0819, 0x2b08190819080808, - 0x2b0819081908082b, 0x2b08190819081919, 0x2b08190819082b08, 0x2b08190819190819, - 0x2b08190819191908, 0x2b081908192b0808, 0x2b0819082b080819, 0x2b0819082b081908, - 0x2b0819082b190808, 0x2b08191908080808, 0x2b0819190808082b, 0x2b08191908081919, - 0x2b08191908082b08, 0x2b08191908190819, 0x2b08191908191908, 0x2b081919082b0808, - 0x2b08191919080819, 0x2b08191919081908, 0x2b08191919190808, 0x2b0819192b080808, - 0x2b0819192b082b2b, 0x2b08192b08080819, 0x2b08192b08081908, 0x2b08192b08190808, - 0x2b08192b082b2b19, 0x2b08192b19080808, 0x2b082b0808080808, 0x2b082b0808081919, - 0x2b082b0808190819, 0x2b082b0808191908, 0x2b082b0819080819, 0x2b082b0819081908, - 0x2b082b0819190808, 0x2b082b082b2b082b, 0x2b082b1908080819, 0x2b082b1908081908, - 0x2b082b1919080808, 0x2b082b19192b1919, 0x2b082b2b082b082b, 0x2b082b2b19192b08, - 0x2b082b2b19192b2b, 0x2b082b2b2b08082b, 0x2b082b2b2b2b082b, 0x2b19080808080819, - 0x2b19080808081908, 0x2b19080808082b19, 0x2b19080808190808, 0x2b1908080819082b, - 0x2b19080808191919, 0x2b19080808192b08, 0x2b190808082b1908, 0x2b19080819080808, - 0x2b1908081908082b, 0x2b19080819081919, 0x2b19080819082b08, 0x2b19080819190819, - 0x2b19080819191908, 0x2b190808192b0808, 0x2b1908082b080819, 0x2b1908082b081908, - 0x2b1908082b190808, 0x2b19081908080808, 0x2b19081908081919, 0x2b19081908190819, - 0x2b19081908191908, 0x2b19081919080819, 0x2b19081919081908, 0x2b19081919190808, - 0x2b19081919192b2b, 0x2b19082b08080819, 0x2b19082b08081908, 0x2b19082b08190808, - 0x2b19082b19080808, 0x2b19082b2b2b192b, 0x2b19190808080808, 0x2b1919080808082b, - 0x2b19190808081919, 0x2b19190808082b08, 0x2b19190808190819, 0x2b19190808191908, - 0x2b191908082b0808, 0x2b19190819080819, 0x2b19190819081908, 0x2b19190819190808, - 0x2b1919082b080808, 0x2b1919082b19192b, 0x2b19191908080819, 0x2b19191908081908, - 0x2b19191908190808, 0x2b19191919080808, 0x2b1919192b192b08, 0x2b1919192b2b0819, - 0x2b19192b08080808, 0x2b19192b1908192b, 0x2b19192b192b1908, 0x2b192b0808080819, - 0x2b192b0808081908, 0x2b192b0808190808, 0x2b192b08082b192b, 0x2b192b0819080808, - 0x2b192b082b2b2b19, 0x2b192b1908080808, 0x2b192b1919082b19, 0x2b192b191919082b, - 0x2b192b2b2b190808, 0x2b2b080808080808, 0x2b2b080808081919, 0x2b2b080808082b2b, - 0x2b2b080808191908, 0x2b2b0808082b082b, 0x2b2b0808082b2b2b, 0x2b2b080819080819, - 0x2b2b080819081908, 0x2b2b080819190808, 0x2b2b08082b2b082b, 0x2b2b08082b2b2b2b, - 0x2b2b081919080808, 0x2b2b0819192b1919, 0x2b2b082b0808082b, 0x2b2b082b08082b2b, - 0x2b2b082b082b082b, 0x2b2b082b082b2b08, 0x2b2b082b082b2b2b, 0x2b2b082b2b08082b, - 0x2b2b082b2b082b08, 0x2b2b082b2b082b2b, 0x2b2b082b2b2b2b08, 0x2b2b190808080819, - 0x2b2b190808081908, 0x2b2b190808190808, 0x2b2b190819080808, 0x2b2b19082b082b19, - 0x2b2b19082b2b1908, 0x2b2b191908080808, 0x2b2b191908192b19, 0x2b2b192b19190819, - 0x2b2b2b0808082b2b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b082b, 0x2b2b2b1919191908, - 0x2b2b2b192b08192b, 0x2b2b2b2b08082b08, 0x2b2b2b2b08082b2b, 0x2b2b2b2b082b0808, - 0x2b2b2b2b082b082b, 0x2b2b2b2b082b2b08, 0x2b2b2b2b2b082b08, 0x2b2b2b2b2b2b2b2b, -GGML_TABLE_END() - -GGML_TABLE_BEGIN(uint32_t, iq3xxs_grid, 256) - 0x04040404, 0x04040414, 0x04040424, 0x04040c0c, 0x04040c1c, 0x04040c3e, 0x04041404, 0x04041414, - 0x04041c0c, 0x04042414, 0x04043e1c, 0x04043e2c, 0x040c040c, 0x040c041c, 0x040c0c04, 0x040c0c14, - 0x040c140c, 0x040c142c, 0x040c1c04, 0x040c1c14, 0x040c240c, 0x040c2c24, 0x040c3e04, 0x04140404, - 0x04140414, 0x04140424, 0x04140c0c, 0x04141404, 0x04141414, 0x04141c0c, 0x04141c1c, 0x04141c3e, - 0x04142c0c, 0x04142c3e, 0x04143e2c, 0x041c040c, 0x041c043e, 0x041c0c04, 0x041c0c14, 0x041c142c, - 0x041c3e04, 0x04240c1c, 0x04241c3e, 0x04242424, 0x04242c3e, 0x04243e1c, 0x04243e2c, 0x042c040c, - 0x042c043e, 0x042c1c14, 0x042c2c14, 0x04341c2c, 0x04343424, 0x043e0c04, 0x043e0c24, 0x043e0c34, - 0x043e241c, 0x043e340c, 0x0c04040c, 0x0c04041c, 0x0c040c04, 0x0c040c14, 0x0c04140c, 0x0c04141c, - 0x0c041c04, 0x0c041c14, 0x0c041c24, 0x0c04243e, 0x0c042c04, 0x0c0c0404, 0x0c0c0414, 0x0c0c0c0c, - 0x0c0c1404, 0x0c0c1414, 0x0c14040c, 0x0c14041c, 0x0c140c04, 0x0c140c14, 0x0c14140c, 0x0c141c04, - 0x0c143e14, 0x0c1c0404, 0x0c1c0414, 0x0c1c1404, 0x0c1c1c0c, 0x0c1c2434, 0x0c1c3434, 0x0c24040c, - 0x0c24042c, 0x0c242c04, 0x0c2c1404, 0x0c2c1424, 0x0c2c2434, 0x0c2c3e0c, 0x0c34042c, 0x0c3e1414, - 0x0c3e2404, 0x14040404, 0x14040414, 0x14040c0c, 0x14040c1c, 0x14041404, 0x14041414, 0x14041434, - 0x14041c0c, 0x14042414, 0x140c040c, 0x140c041c, 0x140c042c, 0x140c0c04, 0x140c0c14, 0x140c140c, - 0x140c1c04, 0x140c341c, 0x140c343e, 0x140c3e04, 0x14140404, 0x14140414, 0x14140c0c, 0x14140c3e, - 0x14141404, 0x14141414, 0x14141c3e, 0x14142404, 0x14142c2c, 0x141c040c, 0x141c0c04, 0x141c0c24, - 0x141c3e04, 0x141c3e24, 0x14241c2c, 0x14242c1c, 0x142c041c, 0x142c143e, 0x142c240c, 0x142c3e24, - 0x143e040c, 0x143e041c, 0x143e0c34, 0x143e242c, 0x1c04040c, 0x1c040c04, 0x1c040c14, 0x1c04140c, - 0x1c04141c, 0x1c042c04, 0x1c04342c, 0x1c043e14, 0x1c0c0404, 0x1c0c0414, 0x1c0c1404, 0x1c0c1c0c, - 0x1c0c2424, 0x1c0c2434, 0x1c14040c, 0x1c14041c, 0x1c140c04, 0x1c14142c, 0x1c142c14, 0x1c143e14, - 0x1c1c0c0c, 0x1c1c1c1c, 0x1c241c04, 0x1c24243e, 0x1c243e14, 0x1c2c0404, 0x1c2c0434, 0x1c2c1414, - 0x1c2c2c2c, 0x1c340c24, 0x1c341c34, 0x1c34341c, 0x1c3e1c1c, 0x1c3e3404, 0x24040424, 0x24040c3e, - 0x24041c2c, 0x24041c3e, 0x24042c1c, 0x24042c3e, 0x240c3e24, 0x24141404, 0x24141c3e, 0x24142404, - 0x24143404, 0x24143434, 0x241c043e, 0x241c242c, 0x24240424, 0x24242c0c, 0x24243424, 0x242c142c, - 0x242c241c, 0x242c3e04, 0x243e042c, 0x243e0c04, 0x243e0c14, 0x243e1c04, 0x2c040c14, 0x2c04240c, - 0x2c043e04, 0x2c0c0404, 0x2c0c0434, 0x2c0c1434, 0x2c0c2c2c, 0x2c140c24, 0x2c141c14, 0x2c143e14, - 0x2c1c0414, 0x2c1c2c1c, 0x2c240c04, 0x2c24141c, 0x2c24143e, 0x2c243e14, 0x2c2c0414, 0x2c2c1c0c, - 0x2c342c04, 0x2c3e1424, 0x2c3e2414, 0x34041424, 0x34042424, 0x34042434, 0x34043424, 0x340c140c, - 0x340c340c, 0x34140c3e, 0x34143424, 0x341c1c04, 0x341c1c34, 0x34242424, 0x342c042c, 0x342c2c14, - 0x34341c1c, 0x343e041c, 0x343e140c, 0x3e04041c, 0x3e04042c, 0x3e04043e, 0x3e040c04, 0x3e041c14, - 0x3e042c14, 0x3e0c1434, 0x3e0c2404, 0x3e140c14, 0x3e14242c, 0x3e142c14, 0x3e1c0404, 0x3e1c0c2c, - 0x3e1c1c1c, 0x3e1c3404, 0x3e24140c, 0x3e24240c, 0x3e2c0404, 0x3e2c0414, 0x3e2c1424, 0x3e341c04, -GGML_TABLE_END() - -GGML_TABLE_BEGIN(uint32_t, iq3s_grid, 512) - 0x01010101, 0x01010103, 0x01010105, 0x0101010b, 0x0101010f, 0x01010301, 0x01010303, 0x01010305, - 0x01010309, 0x0101030d, 0x01010501, 0x01010503, 0x0101050b, 0x01010707, 0x01010901, 0x01010905, - 0x0101090b, 0x0101090f, 0x01010b03, 0x01010b07, 0x01010d01, 0x01010d05, 0x01010f03, 0x01010f09, - 0x01010f0f, 0x01030101, 0x01030103, 0x01030105, 0x01030109, 0x01030301, 0x01030303, 0x0103030b, - 0x01030501, 0x01030507, 0x0103050f, 0x01030703, 0x0103070b, 0x01030909, 0x01030d03, 0x01030d0b, - 0x01030f05, 0x01050101, 0x01050103, 0x0105010b, 0x0105010f, 0x01050301, 0x01050307, 0x0105030d, - 0x01050503, 0x0105050b, 0x01050701, 0x01050709, 0x01050905, 0x0105090b, 0x0105090f, 0x01050b03, - 0x01050b07, 0x01050f01, 0x01050f07, 0x01070107, 0x01070303, 0x0107030b, 0x01070501, 0x01070505, - 0x01070703, 0x01070707, 0x0107070d, 0x01070909, 0x01070b01, 0x01070b05, 0x01070d0f, 0x01070f03, - 0x01070f0b, 0x01090101, 0x01090307, 0x0109030f, 0x01090503, 0x01090509, 0x01090705, 0x01090901, - 0x01090907, 0x01090b03, 0x01090f01, 0x010b0105, 0x010b0109, 0x010b0501, 0x010b0505, 0x010b050d, - 0x010b0707, 0x010b0903, 0x010b090b, 0x010b090f, 0x010b0d0d, 0x010b0f07, 0x010d010d, 0x010d0303, - 0x010d0307, 0x010d0703, 0x010d0b05, 0x010d0f03, 0x010f0101, 0x010f0105, 0x010f0109, 0x010f0501, - 0x010f0505, 0x010f050d, 0x010f0707, 0x010f0b01, 0x010f0b09, 0x03010101, 0x03010103, 0x03010105, - 0x03010109, 0x03010301, 0x03010303, 0x03010307, 0x0301030b, 0x0301030f, 0x03010501, 0x03010505, - 0x03010703, 0x03010709, 0x0301070d, 0x03010b09, 0x03010b0d, 0x03010d03, 0x03010f05, 0x03030101, - 0x03030103, 0x03030107, 0x0303010d, 0x03030301, 0x03030309, 0x03030503, 0x03030701, 0x03030707, - 0x03030903, 0x03030b01, 0x03030b05, 0x03030f01, 0x03030f0d, 0x03050101, 0x03050305, 0x0305030b, - 0x0305030f, 0x03050501, 0x03050509, 0x03050705, 0x03050901, 0x03050907, 0x03050b0b, 0x03050d01, - 0x03050f05, 0x03070103, 0x03070109, 0x0307010f, 0x03070301, 0x03070307, 0x03070503, 0x0307050f, - 0x03070701, 0x03070709, 0x03070903, 0x03070d05, 0x03070f01, 0x03090107, 0x0309010b, 0x03090305, - 0x03090309, 0x03090703, 0x03090707, 0x03090905, 0x0309090d, 0x03090b01, 0x03090b09, 0x030b0103, - 0x030b0301, 0x030b0307, 0x030b0503, 0x030b0701, 0x030b0705, 0x030b0b03, 0x030d0501, 0x030d0509, - 0x030d050f, 0x030d0909, 0x030d090d, 0x030f0103, 0x030f0107, 0x030f0301, 0x030f0305, 0x030f0503, - 0x030f070b, 0x030f0903, 0x030f0d05, 0x030f0f01, 0x05010101, 0x05010103, 0x05010107, 0x0501010b, - 0x0501010f, 0x05010301, 0x05010305, 0x05010309, 0x0501030d, 0x05010503, 0x05010507, 0x0501050f, - 0x05010701, 0x05010705, 0x05010903, 0x05010907, 0x0501090b, 0x05010b01, 0x05010b05, 0x05010d0f, - 0x05010f01, 0x05010f07, 0x05010f0b, 0x05030101, 0x05030105, 0x05030301, 0x05030307, 0x0503030f, - 0x05030505, 0x0503050b, 0x05030703, 0x05030709, 0x05030905, 0x05030b03, 0x05050103, 0x05050109, - 0x0505010f, 0x05050503, 0x05050507, 0x05050701, 0x0505070f, 0x05050903, 0x05050b07, 0x05050b0f, - 0x05050f03, 0x05050f09, 0x05070101, 0x05070105, 0x0507010b, 0x05070303, 0x05070505, 0x05070509, - 0x05070703, 0x05070707, 0x05070905, 0x05070b01, 0x05070d0d, 0x05090103, 0x0509010f, 0x05090501, - 0x05090507, 0x05090705, 0x0509070b, 0x05090903, 0x05090f05, 0x05090f0b, 0x050b0109, 0x050b0303, - 0x050b0505, 0x050b070f, 0x050b0901, 0x050b0b07, 0x050b0f01, 0x050d0101, 0x050d0105, 0x050d010f, - 0x050d0503, 0x050d0b0b, 0x050d0d03, 0x050f010b, 0x050f0303, 0x050f050d, 0x050f0701, 0x050f0907, - 0x050f0b01, 0x07010105, 0x07010303, 0x07010307, 0x0701030b, 0x0701030f, 0x07010505, 0x07010703, - 0x07010707, 0x0701070b, 0x07010905, 0x07010909, 0x0701090f, 0x07010b03, 0x07010d07, 0x07010f03, - 0x07030103, 0x07030107, 0x0703010b, 0x07030309, 0x07030503, 0x07030507, 0x07030901, 0x07030d01, - 0x07030f05, 0x07030f0d, 0x07050101, 0x07050305, 0x07050501, 0x07050705, 0x07050709, 0x07050b01, - 0x07070103, 0x07070301, 0x07070309, 0x07070503, 0x07070507, 0x0707050f, 0x07070701, 0x07070903, - 0x07070907, 0x0707090f, 0x07070b0b, 0x07070f07, 0x07090107, 0x07090303, 0x0709030d, 0x07090505, - 0x07090703, 0x07090b05, 0x07090d01, 0x07090d09, 0x070b0103, 0x070b0301, 0x070b0305, 0x070b050b, - 0x070b0705, 0x070b0909, 0x070b0b0d, 0x070b0f07, 0x070d030d, 0x070d0903, 0x070f0103, 0x070f0107, - 0x070f0501, 0x070f0505, 0x070f070b, 0x09010101, 0x09010109, 0x09010305, 0x09010501, 0x09010509, - 0x0901050f, 0x09010705, 0x09010903, 0x09010b01, 0x09010f01, 0x09030105, 0x0903010f, 0x09030303, - 0x09030307, 0x09030505, 0x09030701, 0x0903070b, 0x09030907, 0x09030b03, 0x09030b0b, 0x09050103, - 0x09050107, 0x09050301, 0x0905030b, 0x09050503, 0x09050707, 0x09050901, 0x09050b0f, 0x09050d05, - 0x09050f01, 0x09070109, 0x09070303, 0x09070307, 0x09070501, 0x09070505, 0x09070703, 0x0907070b, - 0x09090101, 0x09090105, 0x09090509, 0x0909070f, 0x09090901, 0x09090f03, 0x090b010b, 0x090b010f, - 0x090b0503, 0x090b0d05, 0x090d0307, 0x090d0709, 0x090d0d01, 0x090f0301, 0x090f030b, 0x090f0701, - 0x090f0907, 0x090f0b03, 0x0b010105, 0x0b010301, 0x0b010309, 0x0b010505, 0x0b010901, 0x0b010909, - 0x0b01090f, 0x0b010b05, 0x0b010d0d, 0x0b010f09, 0x0b030103, 0x0b030107, 0x0b03010b, 0x0b030305, - 0x0b030503, 0x0b030705, 0x0b030f05, 0x0b050101, 0x0b050303, 0x0b050507, 0x0b050701, 0x0b05070d, - 0x0b050b07, 0x0b070105, 0x0b07010f, 0x0b070301, 0x0b07050f, 0x0b070909, 0x0b070b03, 0x0b070d0b, - 0x0b070f07, 0x0b090103, 0x0b090109, 0x0b090501, 0x0b090705, 0x0b09090d, 0x0b0b0305, 0x0b0b050d, - 0x0b0b0b03, 0x0b0b0b07, 0x0b0d0905, 0x0b0f0105, 0x0b0f0109, 0x0b0f0505, 0x0d010303, 0x0d010307, - 0x0d01030b, 0x0d010703, 0x0d010707, 0x0d010d01, 0x0d030101, 0x0d030501, 0x0d03050f, 0x0d030d09, - 0x0d050305, 0x0d050709, 0x0d050905, 0x0d050b0b, 0x0d050d05, 0x0d050f01, 0x0d070101, 0x0d070309, - 0x0d070503, 0x0d070901, 0x0d09050b, 0x0d090907, 0x0d090d05, 0x0d0b0101, 0x0d0b0107, 0x0d0b0709, - 0x0d0b0d01, 0x0d0d010b, 0x0d0d0901, 0x0d0f0303, 0x0d0f0307, 0x0f010101, 0x0f010109, 0x0f01010f, - 0x0f010501, 0x0f010505, 0x0f01070d, 0x0f010901, 0x0f010b09, 0x0f010d05, 0x0f030105, 0x0f030303, - 0x0f030509, 0x0f030907, 0x0f03090b, 0x0f050103, 0x0f050109, 0x0f050301, 0x0f05030d, 0x0f050503, - 0x0f050701, 0x0f050b03, 0x0f070105, 0x0f070705, 0x0f07070b, 0x0f070b07, 0x0f090103, 0x0f09010b, - 0x0f090307, 0x0f090501, 0x0f090b01, 0x0f0b0505, 0x0f0b0905, 0x0f0d0105, 0x0f0d0703, 0x0f0f0101, -GGML_TABLE_END() - -// TODO: fix name to kvalues_iq4_nl -GGML_TABLE_BEGIN(int8_t, kvalues_iq4nl, 16) - -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113, -GGML_TABLE_END() - -// e2m1 values (doubled), shared by MXFP4 and NVFP4 -// ref: https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf -GGML_TABLE_BEGIN(int8_t, kvalues_fp4, 16) - 0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12, -GGML_TABLE_END() -#define kvalues_mxfp4 kvalues_fp4 - -#define NGRID_IQ1S 2048 -#define IQ1S_DELTA 0.125f -#define IQ1M_DELTA 0.125f -#if defined(GGML_COMMON_IMPL_C) || defined(GGML_COMMON_IMPL_CPP) -GGML_TABLE_BEGIN(uint64_t, iq1s_grid, NGRID_IQ1S) - 0xffffffffffffffff, 0xffffffffffffff01, 0xffffffffffff0000, 0xffffffffffff01ff, - 0xffffffffffff0101, 0xffffffffff00ff00, 0xffffffffff000000, 0xffffffffff01ffff, - 0xffffffffff01ff01, 0xffffffffff0101ff, 0xffffffffff010101, 0xffffffff00ff0000, - 0xffffffff0000ff00, 0xffffffff000000ff, 0xffffffff00000001, 0xffffffff00010000, - 0xffffffff01ffffff, 0xffffffff01ffff01, 0xffffffff01ff01ff, 0xffffffff01ff0101, - 0xffffffff01000000, 0xffffffff0101ffff, 0xffffffff0101ff01, 0xffffffff010101ff, - 0xffffffff01010101, 0xffffff00ffff00ff, 0xffffff00ffff0000, 0xffffff00ff00ff00, - 0xffffff00ff0000ff, 0xffffff00ff000001, 0xffffff00ff000100, 0xffffff00ff000101, - 0xffffff00ff010000, 0xffffff0000ffff00, 0xffffff0000ff0001, 0xffffff0000ff0100, - 0xffffff000000ff01, 0xffffff0000000000, 0xffffff0000000101, 0xffffff000001ff00, - 0xffffff00000100ff, 0xffffff0000010001, 0xffffff00000101ff, 0xffffff0001ff0000, - 0xffffff000100ff00, 0xffffff00010000ff, 0xffffff0001000001, 0xffffff0001010000, - 0xffffff01ffffffff, 0xffffff01ffffff01, 0xffffff01ffff01ff, 0xffffff01ffff0101, - 0xffffff01ff000000, 0xffffff01ff01ffff, 0xffffff01ff01ff01, 0xffffff01ff0101ff, - 0xffffff01ff010101, 0xffffff0100ff0000, 0xffffff010000ff00, 0xffffff0100000100, - 0xffffff01000100ff, 0xffffff0100010100, 0xffffff0101ffffff, 0xffffff0101ffff01, - 0xffffff0101ff01ff, 0xffffff0101ff0101, 0xffffff010100ff00, 0xffffff0101000000, - 0xffffff0101000100, 0xffffff010101ffff, 0xffffff010101ff01, 0xffffff01010101ff, - 0xffffff0101010101, 0xffff00ffff00ff00, 0xffff00ffff0000ff, 0xffff00ffff000001, - 0xffff00ffff010000, 0xffff00ff00ffff00, 0xffff00ff00ff0100, 0xffff00ff00000000, - 0xffff00ff00000101, 0xffff00ff000100ff, 0xffff00ff00010000, 0xffff00ff0100ff00, - 0xffff00ff01000100, 0xffff00ff01010000, 0xffff0000ffffff00, 0xffff0000ffff00ff, - 0xffff0000ffff0000, 0xffff0000ffff0001, 0xffff0000ff000000, 0xffff0000ff0001ff, - 0xffff0000ff000101, 0xffff0000ff010100, 0xffff000000ffffff, 0xffff000000ff0000, - 0xffff000000ff0101, 0xffff00000000ffff, 0xffff00000000ff00, 0xffff0000000000ff, - 0xffff000000000000, 0xffff000000000001, 0xffff000000000100, 0xffff00000001ffff, - 0xffff00000001ff01, 0xffff000000010000, 0xffff0000000101ff, 0xffff000000010101, - 0xffff000001ffff00, 0xffff00000100ff00, 0xffff000001000000, 0xffff0000010001ff, - 0xffff000001000101, 0xffff00000101ff00, 0xffff0000010100ff, 0xffff000001010000, - 0xffff000001010001, 0xffff000001010100, 0xffff0001ff0000ff, 0xffff0001ff000100, - 0xffff000100ffff00, 0xffff000100ff00ff, 0xffff00010000ffff, 0xffff00010000ff01, - 0xffff000100000000, 0xffff0001000001ff, 0xffff00010001ffff, 0xffff00010001ff00, - 0xffff000100010001, 0xffff000100010100, 0xffff000101ff0000, 0xffff00010100ff00, - 0xffff0001010000ff, 0xffff000101000100, 0xffff01ffffffffff, 0xffff01ffffffff01, - 0xffff01ffffff01ff, 0xffff01ffffff0101, 0xffff01ffff000000, 0xffff01ffff01ffff, - 0xffff01ffff01ff01, 0xffff01ffff0101ff, 0xffff01ffff010101, 0xffff01ff00ff0000, - 0xffff01ff0000ff00, 0xffff01ff00000001, 0xffff01ff00010000, 0xffff01ff01ffffff, - 0xffff01ff01ffff01, 0xffff01ff01ff01ff, 0xffff01ff01ff0101, 0xffff01ff01000000, - 0xffff01ff0101ffff, 0xffff01ff0101ff01, 0xffff01ff010101ff, 0xffff01ff01010101, - 0xffff0100ffff0000, 0xffff0100ff00ff00, 0xffff0100ff0000ff, 0xffff0100ff000100, - 0xffff0100ff0100ff, 0xffff0100ff010000, 0xffff010000ffff00, 0xffff01000000ffff, - 0xffff01000000ff00, 0xffff010000000000, 0xffff01000001ff00, 0xffff0100000100ff, - 0xffff010000010100, 0xffff01000100ff00, 0xffff0100010000ff, 0xffff010001000001, - 0xffff010001000100, 0xffff010001010000, 0xffff0101ffffffff, 0xffff0101ffffff01, - 0xffff0101ffff01ff, 0xffff0101ffff0101, 0xffff0101ff000000, 0xffff0101ff01ffff, - 0xffff0101ff01ff01, 0xffff0101ff0101ff, 0xffff0101ff010101, 0xffff010100ff0000, - 0xffff01010000ff00, 0xffff010100000100, 0xffff01010001ff00, 0xffff010100010000, - 0xffff010101ffffff, 0xffff010101ffff01, 0xffff010101ff0000, 0xffff010101ff01ff, - 0xffff010101ff0101, 0xffff010101000000, 0xffff01010101ffff, 0xffff01010101ff01, - 0xffff0101010101ff, 0xffff010101010101, 0xff00ffffff00ffff, 0xff00ffffff00ff00, - 0xff00ffffff0000ff, 0xff00ffffff000100, 0xff00ffffff0100ff, 0xff00ffffff010000, - 0xff00ffff00ffff00, 0xff00ffff00ff00ff, 0xff00ffff0000ffff, 0xff00ffff00000000, - 0xff00ffff000001ff, 0xff00ffff0001ff00, 0xff00ffff000100ff, 0xff00ffff00010000, - 0xff00ffff00010100, 0xff00ffff0100ff00, 0xff00ffff010000ff, 0xff00ffff01000001, - 0xff00ffff0101ff00, 0xff00ffff01010000, 0xff00ff00ffffff00, 0xff00ff00ffff00ff, - 0xff00ff00ffff0001, 0xff00ff00ffff0100, 0xff00ff00ff00ffff, 0xff00ff00ff00ff01, - 0xff00ff00ff000000, 0xff00ff00ff0001ff, 0xff00ff00ff01ff00, 0xff00ff00ff0100ff, - 0xff00ff00ff010100, 0xff00ff0000ff0000, 0xff00ff0000ff0101, 0xff00ff000000ffff, - 0xff00ff000000ff00, 0xff00ff000000ff01, 0xff00ff00000000ff, 0xff00ff0000000000, - 0xff00ff0000000001, 0xff00ff0000000100, 0xff00ff000001ffff, 0xff00ff0000010000, - 0xff00ff0001ff00ff, 0xff00ff000100ff01, 0xff00ff0001000000, 0xff00ff000101ff00, - 0xff00ff00010100ff, 0xff00ff01ff00ff00, 0xff00ff01ff0000ff, 0xff00ff01ff000001, - 0xff00ff01ff010000, 0xff00ff0100ffffff, 0xff00ff0100ff0001, 0xff00ff0100ff0100, - 0xff00ff010000ff01, 0xff00ff0100000000, 0xff00ff01000001ff, 0xff00ff0100000101, - 0xff00ff01000100ff, 0xff00ff0100010001, 0xff00ff0101ff0000, 0xff00ff010100ff00, - 0xff00ff01010000ff, 0xff00ff0101000001, 0xff00ff0101010000, 0xff0000ffffffff00, - 0xff0000ffffff0001, 0xff0000ffffff0100, 0xff0000ffff0000ff, 0xff0000ffff000000, - 0xff0000ffff0001ff, 0xff0000ffff000100, 0xff0000ffff01ff00, 0xff0000ffff010001, - 0xff0000ff00ffff00, 0xff0000ff00ff0000, 0xff0000ff00ff0001, 0xff0000ff00ff01ff, - 0xff0000ff00ff0101, 0xff0000ff0000ff00, 0xff0000ff000000ff, 0xff0000ff00000000, - 0xff0000ff00000001, 0xff0000ff00000100, 0xff0000ff0001ff01, 0xff0000ff00010000, - 0xff0000ff000101ff, 0xff0000ff01ff00ff, 0xff0000ff01ff0100, 0xff0000ff0100ffff, - 0xff0000ff010000ff, 0xff0000ff01000000, 0xff0000ff010001ff, 0xff0000ff01000100, - 0xff0000ff01000101, 0xff0000ff0101ff00, 0xff0000ff010100ff, 0xff0000ff01010000, - 0xff0000ff01010100, 0xff000000ffffff01, 0xff000000ffff0000, 0xff000000ffff0101, - 0xff000000ff00ff00, 0xff000000ff0000ff, 0xff000000ff000000, 0xff000000ff000001, - 0xff000000ff000100, 0xff000000ff01ffff, 0xff000000ff01ff01, 0xff000000ff010000, - 0xff000000ff0101ff, 0xff000000ff010101, 0xff00000000ffff00, 0xff00000000ff00ff, - 0xff00000000ff0000, 0xff00000000ff0001, 0xff0000000000ff00, 0xff0000000000ff01, - 0xff000000000000ff, 0xff00000000000000, 0xff00000000000001, 0xff00000000000100, - 0xff00000000000101, 0xff0000000001ff00, 0xff000000000100ff, 0xff00000000010000, - 0xff00000000010001, 0xff00000000010100, 0xff00000001ffffff, 0xff00000001ffff01, - 0xff00000001ff00ff, 0xff00000001ff0000, 0xff00000001ff01ff, 0xff00000001ff0101, - 0xff0000000100ffff, 0xff0000000100ff00, 0xff000000010000ff, 0xff00000001000000, - 0xff00000001000001, 0xff00000001000100, 0xff00000001000101, 0xff0000000101ffff, - 0xff0000000101ff01, 0xff00000001010000, 0xff000001ffffff00, 0xff000001ffff00ff, - 0xff000001ffff0000, 0xff000001ffff0001, 0xff000001ff000000, 0xff000001ff000001, - 0xff000001ff0001ff, 0xff000001ff000101, 0xff000001ff01ff00, 0xff000001ff010001, - 0xff00000100ffffff, 0xff00000100ffff01, 0xff00000100ff00ff, 0xff00000100ff0000, - 0xff00000100ff01ff, 0xff00000100ff0101, 0xff0000010000ff00, 0xff00000100000000, - 0xff00000100000001, 0xff000001000001ff, 0xff00000100000100, 0xff0000010001ff00, - 0xff000001000100ff, 0xff00000100010000, 0xff000001000101ff, 0xff00000100010100, - 0xff00000100010101, 0xff00000101ff0001, 0xff00000101ff0101, 0xff0000010100ff01, - 0xff00000101000000, 0xff000001010100ff, 0xff00000101010100, 0xff0001ffff00ff00, - 0xff0001ffff000001, 0xff0001ffff010000, 0xff0001ff00ffff00, 0xff0001ff00ff00ff, - 0xff0001ff00ff0001, 0xff0001ff00ff0100, 0xff0001ff0000ffff, 0xff0001ff00000000, - 0xff0001ff000001ff, 0xff0001ff00000101, 0xff0001ff0001ffff, 0xff0001ff0001ff00, - 0xff0001ff000100ff, 0xff0001ff00010001, 0xff0001ff00010100, 0xff0001ff01ff0000, - 0xff0001ff0100ff00, 0xff0001ff010000ff, 0xff0001ff01010000, 0xff000100ff00ffff, - 0xff000100ff00ff01, 0xff000100ff000000, 0xff000100ff000101, 0xff000100ff01ff00, - 0xff000100ff010000, 0xff00010000ffff01, 0xff00010000ff00ff, 0xff00010000ff0000, - 0xff00010000ff01ff, 0xff0001000000ff00, 0xff000100000000ff, 0xff00010000000000, - 0xff00010000000001, 0xff00010000000100, 0xff00010000000101, 0xff0001000001ffff, - 0xff00010000010000, 0xff00010000010101, 0xff00010001ff0100, 0xff0001000100ff00, - 0xff0001000100ff01, 0xff00010001000000, 0xff000100010001ff, 0xff0001000101ff00, - 0xff00010001010001, 0xff00010001010100, 0xff000101ffff0100, 0xff000101ff000001, - 0xff000101ff0100ff, 0xff000101ff010001, 0xff00010100ff00ff, 0xff00010100ff0001, - 0xff00010100ff0100, 0xff0001010000ffff, 0xff0001010000ff01, 0xff00010100000000, - 0xff000101000001ff, 0xff0001010001ff00, 0xff00010100010001, 0xff00010100010100, - 0xff00010101ff0000, 0xff0001010100ff00, 0xff00010101000001, 0xff00010101000101, - 0xff01ffffffffffff, 0xff01ffffffffff01, 0xff01ffffffff01ff, 0xff01ffffffff0101, - 0xff01ffffff000000, 0xff01ffffff01ffff, 0xff01ffffff01ff01, 0xff01ffffff010000, - 0xff01ffffff0101ff, 0xff01ffffff010101, 0xff01ffff00ff0000, 0xff01ffff0000ff00, - 0xff01ffff00000100, 0xff01ffff0001ff00, 0xff01ffff00010000, 0xff01ffff01ffffff, - 0xff01ffff01ffff01, 0xff01ffff01ff01ff, 0xff01ffff01ff0101, 0xff01ffff01000000, - 0xff01ffff0101ffff, 0xff01ffff0101ff01, 0xff01ffff01010000, 0xff01ffff010101ff, - 0xff01ffff01010101, 0xff01ff00ffff0000, 0xff01ff00ff00ff00, 0xff01ff00ff0000ff, - 0xff01ff00ff000100, 0xff01ff00ff010000, 0xff01ff0000ffff01, 0xff01ff0000ff00ff, - 0xff01ff0000ff0100, 0xff01ff0000000000, 0xff01ff00000001ff, 0xff01ff0000000101, - 0xff01ff000001ff00, 0xff01ff00000100ff, 0xff01ff0000010000, 0xff01ff0000010001, - 0xff01ff0001ff0000, 0xff01ff000100ffff, 0xff01ff0001000001, 0xff01ff0001000100, - 0xff01ff0001010000, 0xff01ff01ffffff00, 0xff01ff01ffff01ff, 0xff01ff01ffff0101, - 0xff01ff01ff00ff00, 0xff01ff01ff000000, 0xff01ff01ff01ffff, 0xff01ff01ff01ff01, - 0xff01ff01ff0101ff, 0xff01ff01ff010101, 0xff01ff0100ff0000, 0xff01ff010000ff00, - 0xff01ff0100000001, 0xff01ff0100000100, 0xff01ff0100010000, 0xff01ff0101ffff00, - 0xff01ff0101ff01ff, 0xff01ff0101ff0101, 0xff01ff010100ff00, 0xff01ff0101000000, - 0xff01ff010101ffff, 0xff01ff010101ff01, 0xff01ff01010101ff, 0xff01ff0101010101, - 0xff0100ffffff0000, 0xff0100ffff0000ff, 0xff0100ffff000001, 0xff0100ffff000100, - 0xff0100ffff010000, 0xff0100ff00ff00ff, 0xff0100ff00ff0000, 0xff0100ff00ff0001, - 0xff0100ff00ff0100, 0xff0100ff0000ff01, 0xff0100ff00000000, 0xff0100ff000001ff, - 0xff0100ff00000101, 0xff0100ff00010001, 0xff0100ff01ff0000, 0xff0100ff0100ff00, - 0xff0100ff010000ff, 0xff0100ff01000100, 0xff0100ff0101ff00, 0xff0100ff01010000, - 0xff010000ffff0100, 0xff010000ff000000, 0xff010000ff01ff00, 0xff010000ff010100, - 0xff01000000ffffff, 0xff01000000ff0000, 0xff01000000ff01ff, 0xff0100000000ff00, - 0xff010000000000ff, 0xff01000000000000, 0xff01000000000100, 0xff0100000001ff01, - 0xff01000000010000, 0xff010000000101ff, 0xff01000001ff0100, 0xff0100000100ffff, - 0xff010000010000ff, 0xff01000001000000, 0xff010000010001ff, 0xff01000001000101, - 0xff0100000101ff00, 0xff010000010100ff, 0xff01000001010001, 0xff01000001010100, - 0xff010001ffff0000, 0xff010001ff00ffff, 0xff010001ff00ff01, 0xff010001ff000100, - 0xff010001ff010000, 0xff01000100ffff00, 0xff01000100ff0100, 0xff01000100000000, - 0xff0100010001ffff, 0xff0100010001ff00, 0xff01000100010100, 0xff01000101ff00ff, - 0xff01000101ff0001, 0xff0100010100ffff, 0xff01000101000101, 0xff0101ffffffffff, - 0xff0101ffffffff01, 0xff0101ffffff01ff, 0xff0101ffffff0101, 0xff0101ffff000000, - 0xff0101ffff01ffff, 0xff0101ffff01ff01, 0xff0101ffff0101ff, 0xff0101ffff010101, - 0xff0101ff00ff0000, 0xff0101ff0000ff00, 0xff0101ff000000ff, 0xff0101ff00010000, - 0xff0101ff01ffffff, 0xff0101ff01ffff01, 0xff0101ff01ff01ff, 0xff0101ff01ff0101, - 0xff0101ff0101ffff, 0xff0101ff0101ff01, 0xff0101ff010101ff, 0xff0101ff01010101, - 0xff010100ffff0100, 0xff010100ff00ff00, 0xff010100ff0000ff, 0xff010100ff000100, - 0xff010100ff010000, 0xff01010000ff0001, 0xff01010000ff0100, 0xff0101000000ff01, - 0xff01010000000000, 0xff0101000001ff00, 0xff010100000100ff, 0xff01010000010001, - 0xff01010000010100, 0xff01010001ff0000, 0xff0101000100ffff, 0xff01010001000001, - 0xff01010001000100, 0xff010100010100ff, 0xff01010001010000, 0xff010101ffffffff, - 0xff010101ffffff01, 0xff010101ffff01ff, 0xff010101ffff0101, 0xff010101ff01ffff, - 0xff010101ff01ff01, 0xff010101ff0101ff, 0xff010101ff010101, 0xff01010100ff0000, - 0xff0101010000ff00, 0xff01010100000001, 0xff01010100000100, 0xff01010100010000, - 0xff01010101ffffff, 0xff01010101ffff01, 0xff01010101ff01ff, 0xff01010101ff0101, - 0xff01010101000000, 0xff0101010101ffff, 0xff0101010101ff01, 0xff010101010101ff, - 0xff01010101010101, 0x00ffffffffff0000, 0x00ffffffff00ff00, 0x00ffffffff000001, - 0x00ffffffff010000, 0x00ffffff00ff0100, 0x00ffffff0000ff01, 0x00ffffff00000000, - 0x00ffffff000001ff, 0x00ffffff00000101, 0x00ffffff0001ff00, 0x00ffffff000100ff, - 0x00ffffff00010001, 0x00ffffff010000ff, 0x00ffffff01000100, 0x00ffffff0101ff00, - 0x00ffffff01010001, 0x00ffff00ffffffff, 0x00ffff00ffffff00, 0x00ffff00ffff00ff, - 0x00ffff00ffff0001, 0x00ffff00ffff0100, 0x00ffff00ff00ff01, 0x00ffff00ff000000, - 0x00ffff00ff000001, 0x00ffff00ff0001ff, 0x00ffff00ff000101, 0x00ffff00ff01ff00, - 0x00ffff00ff010001, 0x00ffff00ff010100, 0x00ffff0000ff0000, 0x00ffff0000ff01ff, - 0x00ffff0000ff0101, 0x00ffff000000ff00, 0x00ffff00000000ff, 0x00ffff0000000000, - 0x00ffff0000000001, 0x00ffff0000000100, 0x00ffff0000000101, 0x00ffff0000010000, - 0x00ffff00000101ff, 0x00ffff0000010101, 0x00ffff0001ffff00, 0x00ffff0001ff00ff, - 0x00ffff0001ff0001, 0x00ffff000100ffff, 0x00ffff000100ff01, 0x00ffff0001000000, - 0x00ffff000101ffff, 0x00ffff000101ff00, 0x00ffff000101ff01, 0x00ffff01ffff0000, - 0x00ffff01ff00ff00, 0x00ffff01ff0000ff, 0x00ffff01ff000001, 0x00ffff01ff010000, - 0x00ffff0100ffff00, 0x00ffff010000ff01, 0x00ffff0100000000, 0x00ffff0100000101, - 0x00ffff01000100ff, 0x00ffff0100010100, 0x00ffff0101ff0100, 0x00ffff01010000ff, - 0x00ffff0101010000, 0x00ff00ffffffff00, 0x00ff00ffff000000, 0x00ff00ffff000100, - 0x00ff00ffff010100, 0x00ff00ff00ff0000, 0x00ff00ff00ff01ff, 0x00ff00ff00ff0101, - 0x00ff00ff0000ff00, 0x00ff00ff000000ff, 0x00ff00ff00000000, 0x00ff00ff00000001, - 0x00ff00ff0001ff00, 0x00ff00ff0001ff01, 0x00ff00ff00010000, 0x00ff00ff000101ff, - 0x00ff00ff00010101, 0x00ff00ff01ffff00, 0x00ff00ff01ff0001, 0x00ff00ff01ff0100, - 0x00ff00ff0100ffff, 0x00ff00ff0100ff01, 0x00ff00ff01000000, 0x00ff00ff0101ffff, - 0x00ff00ff0101ff00, 0x00ff00ff01010100, 0x00ff0000ffffff00, 0x00ff0000ffffff01, - 0x00ff0000ffff0000, 0x00ff0000ffff0101, 0x00ff0000ff00ff00, 0x00ff0000ff0000ff, - 0x00ff0000ff000000, 0x00ff0000ff000001, 0x00ff0000ff000100, 0x00ff0000ff01ffff, - 0x00ff0000ff010000, 0x00ff0000ff010101, 0x00ff000000ffff00, 0x00ff000000ff00ff, - 0x00ff000000ff0000, 0x00ff000000ff0001, 0x00ff000000ff0100, 0x00ff00000000ffff, - 0x00ff00000000ff00, 0x00ff0000000000ff, 0x00ff000000000000, 0x00ff000000000001, - 0x00ff0000000001ff, 0x00ff000000000100, 0x00ff00000001ff00, 0x00ff0000000100ff, - 0x00ff000000010000, 0x00ff000000010001, 0x00ff000000010100, 0x00ff000001ffff01, - 0x00ff000001ff00ff, 0x00ff000001ff0000, 0x00ff000001ff01ff, 0x00ff00000100ff00, - 0x00ff0000010000ff, 0x00ff000001000000, 0x00ff000001000001, 0x00ff000001000100, - 0x00ff000001000101, 0x00ff000001010000, 0x00ff0000010101ff, 0x00ff000001010101, - 0x00ff0001ffffff00, 0x00ff0001ffff0000, 0x00ff0001ffff0100, 0x00ff0001ff0000ff, - 0x00ff0001ff000000, 0x00ff0001ff0001ff, 0x00ff0001ff000101, 0x00ff0001ff01ff00, - 0x00ff0001ff0100ff, 0x00ff0001ff010100, 0x00ff000100ffffff, 0x00ff000100ffff01, - 0x00ff000100ff0000, 0x00ff000100ff01ff, 0x00ff00010000ffff, 0x00ff00010000ff00, - 0x00ff00010000ff01, 0x00ff000100000000, 0x00ff000100000001, 0x00ff000100000100, - 0x00ff00010001ff01, 0x00ff000100010000, 0x00ff0001000101ff, 0x00ff000101ffff00, - 0x00ff000101ff0000, 0x00ff000101ff0101, 0x00ff0001010000ff, 0x00ff000101000000, - 0x00ff00010101ff00, 0x00ff0001010100ff, 0x00ff000101010001, 0x00ff01ffffff0000, - 0x00ff01ffff00ff00, 0x00ff01ffff000000, 0x00ff01ffff000101, 0x00ff01ffff010000, - 0x00ff01ff00ffff01, 0x00ff01ff00ff0100, 0x00ff01ff0000ffff, 0x00ff01ff00000000, - 0x00ff01ff000001ff, 0x00ff01ff0001ff00, 0x00ff01ff000100ff, 0x00ff01ff00010001, - 0x00ff01ff00010100, 0x00ff01ff01ff0000, 0x00ff01ff0100ff00, 0x00ff01ff010000ff, - 0x00ff01ff01000001, 0x00ff01ff01000100, 0x00ff01ff01010000, 0x00ff0100ffffff00, - 0x00ff0100ffff0000, 0x00ff0100ffff0001, 0x00ff0100ffff0101, 0x00ff0100ff00ffff, - 0x00ff0100ff0000ff, 0x00ff0100ff000000, 0x00ff0100ff0001ff, 0x00ff0100ff01ff00, - 0x00ff0100ff0100ff, 0x00ff0100ff010001, 0x00ff010000ffffff, 0x00ff010000ff0000, - 0x00ff010000ff0101, 0x00ff01000000ff00, 0x00ff01000000ff01, 0x00ff0100000000ff, - 0x00ff010000000000, 0x00ff010000000001, 0x00ff010000000100, 0x00ff01000001ffff, - 0x00ff01000001ff01, 0x00ff010000010000, 0x00ff010000010001, 0x00ff010000010101, - 0x00ff010001ff0001, 0x00ff010001ff0100, 0x00ff01000100ff01, 0x00ff010001000000, - 0x00ff010001000001, 0x00ff0100010001ff, 0x00ff01000101ff00, 0x00ff0100010100ff, - 0x00ff010001010001, 0x00ff010001010100, 0x00ff0101ff000001, 0x00ff010100ff00ff, - 0x00ff010100ff0001, 0x00ff010100ff0100, 0x00ff010100000000, 0x00ff0101000001ff, - 0x00ff010100000101, 0x00ff0101000100ff, 0x00ff010100010100, 0x00ff0101010000ff, - 0x00ff010101010000, 0x0000ffffffffff00, 0x0000ffffffff00ff, 0x0000ffffffff0000, - 0x0000ffffffff0001, 0x0000ffffffff0100, 0x0000ffffff00ff01, 0x0000ffffff000000, - 0x0000ffffff000101, 0x0000ffffff01ff00, 0x0000ffffff0100ff, 0x0000ffffff010100, - 0x0000ffff00ffffff, 0x0000ffff00ff0000, 0x0000ffff00ff01ff, 0x0000ffff0000ff00, - 0x0000ffff000000ff, 0x0000ffff00000000, 0x0000ffff00000001, 0x0000ffff00000100, - 0x0000ffff00010000, 0x0000ffff000101ff, 0x0000ffff01ff0001, 0x0000ffff01ff0100, - 0x0000ffff01000000, 0x0000ffff010001ff, 0x0000ffff0101ffff, 0x0000ffff0101ff00, - 0x0000ffff01010001, 0x0000ffff01010100, 0x0000ff00ffff0000, 0x0000ff00ffff01ff, - 0x0000ff00ffff0100, 0x0000ff00ffff0101, 0x0000ff00ff00ff00, 0x0000ff00ff0000ff, - 0x0000ff00ff000000, 0x0000ff00ff000001, 0x0000ff00ff0001ff, 0x0000ff00ff000100, - 0x0000ff00ff01ffff, 0x0000ff00ff010000, 0x0000ff00ff010001, 0x0000ff00ff0101ff, - 0x0000ff00ff010101, 0x0000ff0000ffff00, 0x0000ff0000ff00ff, 0x0000ff0000ff0000, - 0x0000ff0000ff0001, 0x0000ff0000ff0100, 0x0000ff000000ffff, 0x0000ff000000ff00, - 0x0000ff000000ff01, 0x0000ff00000000ff, 0x0000ff0000000000, 0x0000ff0000000001, - 0x0000ff00000001ff, 0x0000ff0000000100, 0x0000ff0000000101, 0x0000ff000001ff00, - 0x0000ff00000100ff, 0x0000ff0000010000, 0x0000ff0000010001, 0x0000ff0000010100, - 0x0000ff0001ffff01, 0x0000ff0001ff0000, 0x0000ff000100ff00, 0x0000ff00010000ff, - 0x0000ff0001000000, 0x0000ff0001000001, 0x0000ff0001000100, 0x0000ff000101ffff, - 0x0000ff0001010000, 0x0000ff0001010101, 0x0000ff01ffffff00, 0x0000ff01ffff0001, - 0x0000ff01ff00ff01, 0x0000ff01ff000000, 0x0000ff01ff000101, 0x0000ff01ff01ff00, - 0x0000ff01ff0100ff, 0x0000ff0100ffff01, 0x0000ff0100ff0000, 0x0000ff0100ff0101, - 0x0000ff010000ff00, 0x0000ff01000000ff, 0x0000ff0100000000, 0x0000ff0100000001, - 0x0000ff0100000100, 0x0000ff010001ff01, 0x0000ff0100010000, 0x0000ff0101ff0000, - 0x0000ff010100ffff, 0x0000ff010100ff01, 0x0000ff0101000000, 0x0000ff0101000100, - 0x0000ff0101000101, 0x0000ff01010100ff, 0x000000ffffff00ff, 0x000000ffffff0000, - 0x000000ffff00ff00, 0x000000ffff0000ff, 0x000000ffff000000, 0x000000ffff000001, - 0x000000ffff0001ff, 0x000000ffff000100, 0x000000ffff01ff00, 0x000000ffff010000, - 0x000000ffff0101ff, 0x000000ffff010101, 0x000000ff00ffff00, 0x000000ff00ff00ff, - 0x000000ff00ff0000, 0x000000ff00ff0001, 0x000000ff00ff0100, 0x000000ff00ff0101, - 0x000000ff0000ffff, 0x000000ff0000ff00, 0x000000ff000000ff, 0x000000ff00000000, - 0x000000ff00000001, 0x000000ff000001ff, 0x000000ff00000100, 0x000000ff00000101, - 0x000000ff0001ff00, 0x000000ff0001ff01, 0x000000ff000100ff, 0x000000ff00010000, - 0x000000ff00010001, 0x000000ff00010100, 0x000000ff01ffffff, 0x000000ff01ff01ff, - 0x000000ff01ff0101, 0x000000ff0100ff00, 0x000000ff010000ff, 0x000000ff01000000, - 0x000000ff01000001, 0x000000ff01000100, 0x000000ff0101ff00, 0x000000ff010100ff, - 0x000000ff01010000, 0x000000ff01010101, 0x00000000ffffff00, 0x00000000ffffff01, - 0x00000000ffff00ff, 0x00000000ffff0000, 0x00000000ffff0001, 0x00000000ffff0100, - 0x00000000ff00ffff, 0x00000000ff00ff00, 0x00000000ff00ff01, 0x00000000ff0000ff, - 0x00000000ff000000, 0x00000000ff000001, 0x00000000ff000100, 0x00000000ff000101, - 0x00000000ff01ff00, 0x00000000ff0100ff, 0x00000000ff010000, 0x00000000ff010001, - 0x00000000ff010100, 0x0000000000ffffff, 0x0000000000ffff00, 0x0000000000ffff01, - 0x0000000000ff00ff, 0x0000000000ff0000, 0x0000000000ff0001, 0x0000000000ff01ff, - 0x0000000000ff0100, 0x000000000000ffff, 0x000000000000ff00, 0x000000000000ff01, - 0x00000000000000ff, 0x0000000000000000, 0x0000000000000001, 0x00000000000001ff, - 0x0000000000000100, 0x0000000000000101, 0x000000000001ffff, 0x000000000001ff00, - 0x00000000000100ff, 0x0000000000010000, 0x0000000000010001, 0x00000000000101ff, - 0x0000000000010100, 0x0000000000010101, 0x0000000001ffff00, 0x0000000001ff00ff, - 0x0000000001ff0000, 0x0000000001ff0100, 0x0000000001ff0101, 0x000000000100ffff, - 0x000000000100ff00, 0x00000000010000ff, 0x0000000001000000, 0x0000000001000001, - 0x00000000010001ff, 0x0000000001000100, 0x000000000101ff00, 0x00000000010100ff, - 0x0000000001010000, 0x0000000001010001, 0x0000000001010100, 0x00000001ffffffff, - 0x00000001ffffff00, 0x00000001ffffff01, 0x00000001ffff00ff, 0x00000001ffff0001, - 0x00000001ffff01ff, 0x00000001ffff0100, 0x00000001ff00ff00, 0x00000001ff0000ff, - 0x00000001ff000000, 0x00000001ff0001ff, 0x00000001ff000100, 0x00000001ff01ffff, - 0x00000001ff01ff00, 0x00000001ff01ff01, 0x00000001ff0100ff, 0x00000001ff010000, - 0x00000001ff010001, 0x00000001ff0101ff, 0x00000001ff010100, 0x0000000100ffff00, - 0x0000000100ff0000, 0x0000000100ff0001, 0x0000000100ff01ff, 0x0000000100ff0100, - 0x0000000100ff0101, 0x000000010000ffff, 0x000000010000ff00, 0x000000010000ff01, - 0x00000001000000ff, 0x0000000100000000, 0x0000000100000001, 0x00000001000001ff, - 0x0000000100000100, 0x0000000100000101, 0x000000010001ff00, 0x00000001000100ff, - 0x0000000100010000, 0x0000000100010100, 0x0000000101ffff01, 0x0000000101ff0000, - 0x0000000101ff0001, 0x0000000101ff01ff, 0x0000000101ff0100, 0x0000000101ff0101, - 0x000000010100ff00, 0x0000000101000000, 0x0000000101000101, 0x000000010101ff01, - 0x0000000101010000, 0x0000000101010001, 0x00000001010101ff, 0x0000000101010100, - 0x000001ffffff00ff, 0x000001ffffff0000, 0x000001ffffff0001, 0x000001ffffff0100, - 0x000001ffff00ffff, 0x000001ffff000000, 0x000001ffff0001ff, 0x000001ffff01ff00, - 0x000001ffff010101, 0x000001ff00ff0000, 0x000001ff00ff01ff, 0x000001ff00ff0101, - 0x000001ff0000ff00, 0x000001ff000000ff, 0x000001ff00000000, 0x000001ff00000001, - 0x000001ff000001ff, 0x000001ff00000100, 0x000001ff0001ffff, 0x000001ff0001ff01, - 0x000001ff000100ff, 0x000001ff00010000, 0x000001ff01ffff01, 0x000001ff01ff0100, - 0x000001ff0100ffff, 0x000001ff0100ff01, 0x000001ff01000000, 0x000001ff010001ff, - 0x000001ff0101ff00, 0x000001ff01010100, 0x00000100ffffff00, 0x00000100ffffff01, - 0x00000100ffff0000, 0x00000100ffff0101, 0x00000100ff00ff00, 0x00000100ff0000ff, - 0x00000100ff000000, 0x00000100ff000001, 0x00000100ff000100, 0x00000100ff010000, - 0x0000010000ffff00, 0x0000010000ff00ff, 0x0000010000ff0000, 0x0000010000ff0001, - 0x0000010000ff0100, 0x000001000000ffff, 0x000001000000ff00, 0x000001000000ff01, - 0x00000100000000ff, 0x0000010000000000, 0x0000010000000001, 0x00000100000001ff, - 0x0000010000000100, 0x0000010000000101, 0x000001000001ff00, 0x00000100000100ff, - 0x0000010000010000, 0x0000010000010001, 0x0000010000010100, 0x0000010001ffff00, - 0x0000010001ff0000, 0x0000010001ff0100, 0x000001000100ff00, 0x00000100010000ff, - 0x0000010001000000, 0x0000010001000001, 0x00000100010001ff, 0x0000010001000100, - 0x0000010001010000, 0x00000101ffff00ff, 0x00000101ffff01ff, 0x00000101ff000000, - 0x00000101ff000101, 0x00000101ff01ffff, 0x00000101ff010000, 0x00000101ff010001, - 0x00000101ff010100, 0x0000010100ff0000, 0x0000010100ff01ff, 0x0000010100ff0100, - 0x000001010000ff00, 0x0000010100000000, 0x0000010100000001, 0x00000101000001ff, - 0x0000010100000100, 0x000001010001ff01, 0x0000010100010000, 0x00000101000101ff, - 0x0000010100010101, 0x0000010101ffff00, 0x0000010101ff0101, 0x000001010100ff01, - 0x0000010101000000, 0x0000010101000001, 0x00000101010001ff, 0x0000010101000101, - 0x000001010101ff00, 0x0001ffffffff0000, 0x0001ffffff0000ff, 0x0001ffffff000001, - 0x0001ffffff000100, 0x0001ffffff010000, 0x0001ffff00ff00ff, 0x0001ffff0000ffff, - 0x0001ffff00000000, 0x0001ffff00000001, 0x0001ffff000001ff, 0x0001ffff00000101, - 0x0001ffff0001ff00, 0x0001ffff000100ff, 0x0001ffff00010001, 0x0001ffff00010100, - 0x0001ffff01ffff00, 0x0001ffff01000001, 0x0001ffff01010000, 0x0001ff00ffffff00, - 0x0001ff00ffff00ff, 0x0001ff00ffff0001, 0x0001ff00ffff0100, 0x0001ff00ff00ff01, - 0x0001ff00ff000000, 0x0001ff00ff01ff00, 0x0001ff00ff01ff01, 0x0001ff00ff010001, - 0x0001ff00ff010100, 0x0001ff0000ff0000, 0x0001ff0000ff0100, 0x0001ff000000ff00, - 0x0001ff0000000000, 0x0001ff0000000001, 0x0001ff0000000100, 0x0001ff0000010000, - 0x0001ff0000010001, 0x0001ff0000010101, 0x0001ff0001ff00ff, 0x0001ff0001ff0101, - 0x0001ff000100ff01, 0x0001ff0001000000, 0x0001ff000101ff00, 0x0001ff0001010001, - 0x0001ff0001010100, 0x0001ff01ff00ff00, 0x0001ff01ff000001, 0x0001ff01ff000100, - 0x0001ff0100ffffff, 0x0001ff0100ffff00, 0x0001ff0100ff0001, 0x0001ff0100000000, - 0x0001ff0100000001, 0x0001ff01000001ff, 0x0001ff010001ffff, 0x0001ff0101ff0000, - 0x0001ff010100ff00, 0x0001ff0101000001, 0x0001ff0101010000, 0x000100ffff00ff00, - 0x000100ffff00ff01, 0x000100ffff000000, 0x000100ffff000001, 0x000100ffff000101, - 0x000100ffff01ff00, 0x000100ffff010001, 0x000100ffff010100, 0x000100ff00ffffff, - 0x000100ff00ffff01, 0x000100ff00ff0000, 0x000100ff00ff01ff, 0x000100ff00ff0101, - 0x000100ff0000ff00, 0x000100ff000000ff, 0x000100ff00000000, 0x000100ff00000001, - 0x000100ff00000100, 0x000100ff00000101, 0x000100ff0001ffff, 0x000100ff0001ff01, - 0x000100ff00010000, 0x000100ff01ff00ff, 0x000100ff01ff0000, 0x000100ff01ff0100, - 0x000100ff0100ffff, 0x000100ff0100ff01, 0x000100ff010000ff, 0x000100ff01000000, - 0x000100ff01000001, 0x000100ff010001ff, 0x000100ff01000101, 0x000100ff0101ff00, - 0x000100ff010100ff, 0x000100ff01010100, 0x00010000ffff0000, 0x00010000ffff01ff, - 0x00010000ffff0101, 0x00010000ff00ff00, 0x00010000ff000000, 0x00010000ff000001, - 0x00010000ff000100, 0x0001000000ff00ff, 0x0001000000ff0000, 0x0001000000ff0001, - 0x0001000000ff0100, 0x000100000000ffff, 0x000100000000ff00, 0x00010000000000ff, - 0x0001000000000000, 0x0001000000000001, 0x0001000000000100, 0x000100000001ff00, - 0x00010000000100ff, 0x0001000000010000, 0x0001000000010001, 0x0001000000010100, - 0x0001000001ff0001, 0x0001000001ff0100, 0x0001000001ff0101, 0x000100000100ff00, - 0x0001000001000000, 0x0001000001000001, 0x0001000001000100, 0x0001000001000101, - 0x000100000101ff01, 0x0001000001010000, 0x0001000001010001, 0x00010000010101ff, - 0x00010001ffffff01, 0x00010001ffff0100, 0x00010001ff000000, 0x00010001ff01ffff, - 0x00010001ff010001, 0x00010001ff0101ff, 0x00010001ff010100, 0x0001000100ffffff, - 0x0001000100ff0000, 0x0001000100ff01ff, 0x0001000100ff0101, 0x000100010000ff00, - 0x00010001000000ff, 0x0001000100000000, 0x0001000100000001, 0x00010001000001ff, - 0x0001000100000101, 0x000100010001ffff, 0x0001000100010000, 0x00010001000101ff, - 0x0001000101ffffff, 0x0001000101ffff01, 0x0001000101ff0000, 0x0001000101ff0101, - 0x00010001010000ff, 0x0001000101000001, 0x00010001010001ff, 0x0001000101000100, - 0x000100010101ffff, 0x00010001010100ff, 0x0001000101010001, 0x0001000101010101, - 0x000101ffff000001, 0x000101ffff000100, 0x000101ffff010000, 0x000101ff00ffff00, - 0x000101ff0000ff01, 0x000101ff00000000, 0x000101ff00000101, 0x000101ff0001ff00, - 0x000101ff00010100, 0x000101ff01ff0000, 0x000101ff0100ff00, 0x000101ff010001ff, - 0x000101ff01010001, 0x00010100ffffff00, 0x00010100ffff00ff, 0x00010100ff00ffff, - 0x00010100ff000000, 0x00010100ff01ff00, 0x00010100ff0100ff, 0x00010100ff010001, - 0x00010100ff010100, 0x0001010000ffffff, 0x0001010000ffff00, 0x0001010000ff0000, - 0x0001010000ff0001, 0x0001010000ff01ff, 0x000101000000ff00, 0x00010100000000ff, - 0x0001010000000000, 0x0001010000000001, 0x0001010000000100, 0x000101000001ffff, - 0x0001010000010000, 0x0001010000010101, 0x0001010001ffff01, 0x0001010001ff00ff, - 0x0001010001ff0101, 0x0001010001000000, 0x000101000101ff00, 0x00010100010100ff, - 0x0001010001010000, 0x0001010001010100, 0x00010101ff00ff00, 0x00010101ff000001, - 0x00010101ff0001ff, 0x0001010100ffff00, 0x0001010100ff00ff, 0x0001010100ff0100, - 0x000101010000ffff, 0x0001010100000000, 0x00010101000001ff, 0x0001010100000101, - 0x00010101000100ff, 0x0001010100010000, 0x0001010100010100, 0x0001010101ff0001, - 0x00010101010000ff, 0x00010101010001ff, 0x0001010101000101, 0x0001010101010001, - 0x01ffffffffffffff, 0x01ffffffffffff01, 0x01ffffffffff01ff, 0x01ffffffffff0101, - 0x01ffffffff01ffff, 0x01ffffffff01ff01, 0x01ffffffff0101ff, 0x01ffffffff010101, - 0x01ffffff00ff0000, 0x01ffffff0000ffff, 0x01ffffff0000ff00, 0x01ffffff000000ff, - 0x01ffffff00000001, 0x01ffffff00000100, 0x01ffffff00010000, 0x01ffffff01ffffff, - 0x01ffffff01ffff01, 0x01ffffff01ff01ff, 0x01ffffff01ff0101, 0x01ffffff01000000, - 0x01ffffff0101ffff, 0x01ffffff0101ff01, 0x01ffffff010101ff, 0x01ffffff01010101, - 0x01ffff00ffff0000, 0x01ffff00ff00ff00, 0x01ffff00ff0000ff, 0x01ffff00ff000001, - 0x01ffff00ff000100, 0x01ffff00ff010000, 0x01ffff0000ffff00, 0x01ffff0000ff00ff, - 0x01ffff0000ff0100, 0x01ffff000000ffff, 0x01ffff000000ff01, 0x01ffff0000000000, - 0x01ffff0000000001, 0x01ffff00000001ff, 0x01ffff0000000100, 0x01ffff00000100ff, - 0x01ffff0000010001, 0x01ffff0000010100, 0x01ffff0001ff0000, 0x01ffff0001ff0100, - 0x01ffff00010000ff, 0x01ffff0001000001, 0x01ffff0001000100, 0x01ffff0001010000, - 0x01ffff01ffffffff, 0x01ffff01ffffff01, 0x01ffff01ffff01ff, 0x01ffff01ffff0101, - 0x01ffff01ff000000, 0x01ffff01ff01ffff, 0x01ffff01ff01ff01, 0x01ffff01ff0101ff, - 0x01ffff01ff010101, 0x01ffff010000ff00, 0x01ffff01000000ff, 0x01ffff0100000100, - 0x01ffff0100010000, 0x01ffff0101ffffff, 0x01ffff0101ffff01, 0x01ffff0101ff01ff, - 0x01ffff0101ff0101, 0x01ffff0101000000, 0x01ffff010101ffff, 0x01ffff010101ff01, - 0x01ffff01010101ff, 0x01ffff0101010101, 0x01ff00ffff0000ff, 0x01ff00ffff000100, - 0x01ff00ff00ffff00, 0x01ff00ff00ff00ff, 0x01ff00ff0000ff00, 0x01ff00ff00000000, - 0x01ff00ff00000101, 0x01ff00ff0001ff00, 0x01ff00ff000100ff, 0x01ff00ff00010100, - 0x01ff00ff010000ff, 0x01ff00ff01000100, 0x01ff0000ffffff00, 0x01ff0000ffff0100, - 0x01ff0000ff00ff01, 0x01ff0000ff000000, 0x01ff0000ff000101, 0x01ff0000ff010001, - 0x01ff0000ff010100, 0x01ff000000ffffff, 0x01ff000000ffff00, 0x01ff000000ff0000, - 0x01ff000000ff01ff, 0x01ff00000000ff00, 0x01ff0000000000ff, 0x01ff000000000000, - 0x01ff000000000001, 0x01ff000000000100, 0x01ff000000000101, 0x01ff000000010000, - 0x01ff000000010001, 0x01ff0000000101ff, 0x01ff000000010101, 0x01ff000001ffff00, - 0x01ff000001ff00ff, 0x01ff000001ff0001, 0x01ff000001ff0100, 0x01ff00000100ffff, - 0x01ff00000100ff01, 0x01ff000001000000, 0x01ff0000010001ff, 0x01ff000001010001, - 0x01ff0001ff00ff00, 0x01ff0001ff000001, 0x01ff0001ff000100, 0x01ff0001ff010000, - 0x01ff000100ffff00, 0x01ff000100ff00ff, 0x01ff000100ff0100, 0x01ff000100ff0101, - 0x01ff00010000ffff, 0x01ff000100000000, 0x01ff000100000100, 0x01ff000100000101, - 0x01ff00010001ff00, 0x01ff000100010001, 0x01ff000100010101, 0x01ff000101ff0000, - 0x01ff00010100ff00, 0x01ff000101000101, 0x01ff0001010100ff, 0x01ff01ffffffffff, - 0x01ff01ffffffff01, 0x01ff01ffffff01ff, 0x01ff01ffffff0101, 0x01ff01ffff000000, - 0x01ff01ffff01ffff, 0x01ff01ffff01ff01, 0x01ff01ffff0101ff, 0x01ff01ffff010101, - 0x01ff01ff00ffff00, 0x01ff01ff00ff0000, 0x01ff01ff0000ff00, 0x01ff01ff000000ff, - 0x01ff01ff00000100, 0x01ff01ff00010000, 0x01ff01ff00010100, 0x01ff01ff01ffffff, - 0x01ff01ff01ffff01, 0x01ff01ff01ff01ff, 0x01ff01ff01ff0101, 0x01ff01ff01000000, - 0x01ff01ff0101ffff, 0x01ff01ff0101ff01, 0x01ff01ff010101ff, 0x01ff01ff01010101, - 0x01ff0100ffff0000, 0x01ff0100ffff0001, 0x01ff0100ff00ff00, 0x01ff0100ff0000ff, - 0x01ff0100ff000001, 0x01ff0100ff010000, 0x01ff010000ffff00, 0x01ff010000ff00ff, - 0x01ff010000ff0001, 0x01ff010000ff0100, 0x01ff01000000ffff, 0x01ff01000000ff01, - 0x01ff010000000000, 0x01ff010000000101, 0x01ff01000001ff00, 0x01ff0100000100ff, - 0x01ff010001ff0000, 0x01ff010001000001, 0x01ff010001000100, 0x01ff010001010000, - 0x01ff0101ffffffff, 0x01ff0101ffffff01, 0x01ff0101ffff01ff, 0x01ff0101ffff0101, - 0x01ff0101ff000000, 0x01ff0101ff01ffff, 0x01ff0101ff01ff01, 0x01ff0101ff0101ff, - 0x01ff0101ff010101, 0x01ff010100ff0000, 0x01ff01010000ff00, 0x01ff0101000000ff, - 0x01ff010100000001, 0x01ff010101ffffff, 0x01ff010101ffff01, 0x01ff010101ff01ff, - 0x01ff010101ff0101, 0x01ff010101000000, 0x01ff01010101ffff, 0x01ff01010101ff01, - 0x01ff0101010101ff, 0x01ff010101010101, 0x0100ffffffff0000, 0x0100ffffff00ff00, - 0x0100ffffff000001, 0x0100ffffff0001ff, 0x0100ffffff000100, 0x0100ffffff010000, - 0x0100ffff00ffff00, 0x0100ffff00ff0001, 0x0100ffff00ff0100, 0x0100ffff00000000, - 0x0100ffff000001ff, 0x0100ffff00000101, 0x0100ffff00010100, 0x0100ffff00010101, - 0x0100ffff01ff0000, 0x0100ffff0100ff00, 0x0100ffff010000ff, 0x0100ffff01000001, - 0x0100ffff01000100, 0x0100ffff01010000, 0x0100ff00ffffff00, 0x0100ff00ffff00ff, - 0x0100ff00ffff0001, 0x0100ff00ffff0100, 0x0100ff00ff00ffff, 0x0100ff00ff000000, - 0x0100ff00ff0001ff, 0x0100ff00ff000101, 0x0100ff00ff01ff00, 0x0100ff00ff0100ff, - 0x0100ff00ff010001, 0x0100ff00ff010100, 0x0100ff0000ffffff, 0x0100ff0000ff0000, - 0x0100ff000000ffff, 0x0100ff000000ff00, 0x0100ff00000000ff, 0x0100ff0000000000, - 0x0100ff0000000001, 0x0100ff0000000100, 0x0100ff000001ff01, 0x0100ff0000010000, - 0x0100ff0001ff00ff, 0x0100ff0001ff0001, 0x0100ff000100ff01, 0x0100ff0001000000, - 0x0100ff00010001ff, 0x0100ff000101ff00, 0x0100ff00010100ff, 0x0100ff0001010001, - 0x0100ff0001010100, 0x0100ff01ffff0000, 0x0100ff01ff00ff00, 0x0100ff01ff0000ff, - 0x0100ff01ff000100, 0x0100ff01ff010000, 0x0100ff0100ff00ff, 0x0100ff0100ff0001, - 0x0100ff0100ff0100, 0x0100ff010000ffff, 0x0100ff010000ff01, 0x0100ff0100000000, - 0x0100ff01000001ff, 0x0100ff0100010001, 0x0100ff0100010100, 0x0100ff0101ff0000, - 0x0100ff01010000ff, 0x0100ff0101000001, 0x0100ff0101010100, 0x010000ffffffff00, - 0x010000ffffff00ff, 0x010000ffffff0001, 0x010000ffff00ffff, 0x010000ffff000000, - 0x010000ffff0001ff, 0x010000ffff010001, 0x010000ff00ffffff, 0x010000ff00ff0101, - 0x010000ff0000ff00, 0x010000ff000000ff, 0x010000ff00000000, 0x010000ff00000001, - 0x010000ff000001ff, 0x010000ff00000100, 0x010000ff0001ffff, 0x010000ff0001ff00, - 0x010000ff0001ff01, 0x010000ff00010000, 0x010000ff01ff00ff, 0x010000ff01ff0001, - 0x010000ff0100ff01, 0x010000ff010000ff, 0x010000ff01000000, 0x010000ff010001ff, - 0x010000ff0101ff00, 0x010000ff01010100, 0x01000000ffffffff, 0x01000000ffff0000, - 0x01000000ffff01ff, 0x01000000ffff0101, 0x01000000ff00ffff, 0x01000000ff00ff00, - 0x01000000ff0000ff, 0x01000000ff000000, 0x01000000ff000001, 0x01000000ff000100, - 0x01000000ff01ff00, 0x01000000ff010000, 0x01000000ff010100, 0x01000000ff010101, - 0x0100000000ffff00, 0x0100000000ff00ff, 0x0100000000ff0000, 0x0100000000ff0001, - 0x0100000000ff0100, 0x010000000000ffff, 0x010000000000ff00, 0x010000000000ff01, - 0x01000000000000ff, 0x0100000000000000, 0x0100000000000001, 0x01000000000001ff, - 0x0100000000000100, 0x0100000000000101, 0x010000000001ff00, 0x01000000000100ff, - 0x0100000000010000, 0x0100000000010001, 0x0100000000010100, 0x0100000001ffff00, - 0x0100000001ff0000, 0x0100000001ff01ff, 0x010000000100ff00, 0x010000000100ff01, - 0x01000000010000ff, 0x0100000001000000, 0x0100000001000001, 0x0100000001000100, - 0x0100000001000101, 0x010000000101ffff, 0x010000000101ff01, 0x0100000001010000, - 0x01000000010101ff, 0x0100000001010101, 0x01000001ffffff00, 0x01000001ffff00ff, - 0x01000001ff00ffff, 0x01000001ff000000, 0x01000001ff000100, 0x01000001ff01ffff, - 0x01000001ff010001, 0x01000001ff010100, 0x0100000100ff0000, 0x0100000100ff01ff, - 0x0100000100ff0100, 0x010000010000ff00, 0x010000010000ff01, 0x0100000100000000, - 0x0100000100000001, 0x0100000100000100, 0x0100000100010000, 0x01000001000101ff, - 0x0100000101ffff01, 0x0100000101ff00ff, 0x0100000101ff0100, 0x0100000101ff0101, - 0x010000010100ff01, 0x01000001010000ff, 0x0100000101000000, 0x01000001010100ff, - 0x0100000101010001, 0x0100000101010100, 0x010001ffffff0000, 0x010001ffff000001, - 0x010001ffff000100, 0x010001ffff010000, 0x010001ff00ffff00, 0x010001ff00ff0001, - 0x010001ff0000ffff, 0x010001ff0000ff01, 0x010001ff00000000, 0x010001ff00000001, - 0x010001ff00000101, 0x010001ff000100ff, 0x010001ff00010000, 0x010001ff01ff0000, - 0x010001ff0100ff00, 0x010001ff01000001, 0x010001ff01000100, 0x010001ff01010000, - 0x01000100ffff00ff, 0x01000100ffff0001, 0x01000100ffff0100, 0x01000100ff00ffff, - 0x01000100ff00ff01, 0x01000100ff000000, 0x01000100ff0001ff, 0x01000100ff000101, - 0x01000100ff01ffff, 0x01000100ff01ff00, 0x01000100ff0100ff, 0x01000100ff010001, - 0x0100010000ffffff, 0x0100010000ffff01, 0x0100010000ff0000, 0x0100010000ff01ff, - 0x0100010000ff0101, 0x010001000000ff00, 0x01000100000000ff, 0x0100010000000000, - 0x0100010000000001, 0x0100010000000100, 0x010001000001ff01, 0x0100010000010000, - 0x0100010000010001, 0x0100010000010101, 0x0100010001ffff00, 0x0100010001ff00ff, - 0x010001000100ffff, 0x010001000100ff01, 0x0100010001000000, 0x0100010001000101, - 0x010001000101ff00, 0x0100010001010001, 0x01000101ffff0000, 0x01000101ff000000, - 0x01000101ff010000, 0x0100010100ff00ff, 0x0100010100ff0001, 0x0100010100ff0100, - 0x010001010000ffff, 0x0100010100000000, 0x01000101000001ff, 0x010001010001ff00, - 0x0100010101ff0000, 0x010001010100ff00, 0x01000101010000ff, 0x0100010101000000, - 0x0100010101000001, 0x0101ffffffffffff, 0x0101ffffffffff01, 0x0101ffffffff01ff, - 0x0101ffffffff0101, 0x0101ffffff000000, 0x0101ffffff01ffff, 0x0101ffffff01ff01, - 0x0101ffffff0101ff, 0x0101ffffff010101, 0x0101ffff00ff0000, 0x0101ffff0000ff00, - 0x0101ffff000000ff, 0x0101ffff00000001, 0x0101ffff00000100, 0x0101ffff01ffffff, - 0x0101ffff01ffff01, 0x0101ffff01ff01ff, 0x0101ffff01ff0101, 0x0101ffff01000000, - 0x0101ffff0101ffff, 0x0101ffff0101ff01, 0x0101ffff010101ff, 0x0101ffff01010101, - 0x0101ff00ffff0000, 0x0101ff00ffff0100, 0x0101ff00ff00ff00, 0x0101ff00ff0000ff, - 0x0101ff00ff000001, 0x0101ff00ff000100, 0x0101ff00ff000101, 0x0101ff0000ff0001, - 0x0101ff0000ff0100, 0x0101ff000000ff00, 0x0101ff0000000000, 0x0101ff00000001ff, - 0x0101ff0000000101, 0x0101ff000001ff00, 0x0101ff00000100ff, 0x0101ff0001ff0000, - 0x0101ff000100ffff, 0x0101ff000100ff01, 0x0101ff0001000001, 0x0101ff0001000100, - 0x0101ff01ffffff01, 0x0101ff01ffff01ff, 0x0101ff01ffff0101, 0x0101ff01ff00ffff, - 0x0101ff01ff000100, 0x0101ff01ff01ff01, 0x0101ff01ff0101ff, 0x0101ff01ff010101, - 0x0101ff0100ff0000, 0x0101ff010000ff00, 0x0101ff0100000001, 0x0101ff0100000100, - 0x0101ff0100010000, 0x0101ff0101ffffff, 0x0101ff0101ffff01, 0x0101ff0101ff01ff, - 0x0101ff0101ff0101, 0x0101ff0101000000, 0x0101ff010101ffff, 0x0101ff010101ff01, - 0x0101ff01010101ff, 0x0101ff0101010101, 0x010100ffff000100, 0x010100ffff010000, - 0x010100ff00ffff00, 0x010100ff00ff00ff, 0x010100ff0000ffff, 0x010100ff000000ff, - 0x010100ff00000000, 0x010100ff000001ff, 0x010100ff00000101, 0x010100ff0001ff00, - 0x010100ff00010000, 0x010100ff00010001, 0x010100ff000101ff, 0x010100ff00010100, - 0x010100ff01ff0000, 0x01010000ffff0001, 0x01010000ffff0100, 0x01010000ff00ffff, - 0x01010000ff00ff01, 0x01010000ff000000, 0x01010000ff0001ff, 0x01010000ff010001, - 0x01010000ff010100, 0x0101000000ffff01, 0x0101000000ff0000, 0x010100000000ff00, - 0x01010000000000ff, 0x0101000000000000, 0x0101000000000001, 0x0101000000000100, - 0x0101000000010000, 0x0101000000010101, 0x0101000001ffff00, 0x0101000001ff00ff, - 0x0101000001ff0000, 0x0101000001ff0001, 0x0101000001ff0100, 0x010100000100ff01, - 0x0101000001000000, 0x01010000010001ff, 0x01010001ffff0000, 0x01010001ff00ff00, - 0x01010001ff000001, 0x01010001ff000101, 0x01010001ff01ff00, 0x01010001ff010000, - 0x0101000100ff00ff, 0x0101000100ff0001, 0x0101000100ff0101, 0x010100010000ff01, - 0x0101000100000000, 0x0101000100000001, 0x01010001000001ff, 0x010100010001ffff, - 0x010100010001ff01, 0x0101000101ff0001, 0x010100010100ffff, 0x0101000101000000, - 0x0101000101000001, 0x0101000101000100, 0x010100010101ff00, 0x01010001010100ff, - 0x0101000101010001, 0x010101ffffffffff, 0x010101ffffffff01, 0x010101ffffff01ff, - 0x010101ffffff0101, 0x010101ffff01ffff, 0x010101ffff01ff01, 0x010101ffff0101ff, - 0x010101ffff010101, 0x010101ff0000ff00, 0x010101ff000000ff, 0x010101ff00000001, - 0x010101ff00000100, 0x010101ff01ffffff, 0x010101ff01ffff01, 0x010101ff01ff01ff, - 0x010101ff01ff0101, 0x010101ff01000000, 0x010101ff0101ffff, 0x010101ff0101ff01, - 0x010101ff010101ff, 0x010101ff01010101, 0x01010100ffff0000, 0x01010100ff0000ff, - 0x01010100ff000100, 0x01010100ff01ff00, 0x01010100ff010000, 0x0101010000ffff00, - 0x010101000000ffff, 0x0101010000000000, 0x0101010000000101, 0x010101000001ff00, - 0x0101010000010001, 0x0101010000010100, 0x010101000100ffff, 0x0101010001000001, - 0x01010101ffffffff, 0x01010101ffffff01, 0x01010101ffff01ff, 0x01010101ffff0101, - 0x01010101ff01ffff, 0x01010101ff01ff01, 0x01010101ff0101ff, 0x01010101ff010101, - 0x010101010000ff00, 0x01010101000000ff, 0x0101010100000001, 0x0101010101ffffff, - 0x0101010101ffff01, 0x0101010101ff01ff, 0x0101010101ff0101, 0x0101010101000000, - 0x010101010101ffff, 0x010101010101ff01, 0x01010101010101ff, 0x0101010101010101, -GGML_TABLE_END() -#else -GGML_TABLE_BEGIN(uint32_t, iq1s_grid_gpu, NGRID_IQ1S) - 0x00000000, 0x00000002, 0x00000101, 0x00000200, 0x00000202, 0x00010001, 0x00010101, 0x00020000, - 0x00020002, 0x00020200, 0x00020202, 0x01000101, 0x01010001, 0x01010100, 0x01010102, 0x01020101, - 0x02000000, 0x02000002, 0x02000200, 0x02000202, 0x02010101, 0x02020000, 0x02020002, 0x02020200, - 0x02020202, 0x00000110, 0x00000111, 0x00010011, 0x00010110, 0x00010112, 0x00010211, 0x00010212, - 0x00020111, 0x01000011, 0x01000112, 0x01000211, 0x01010012, 0x01010111, 0x01010212, 0x01020011, - 0x01020110, 0x01020112, 0x01020210, 0x02000111, 0x02010011, 0x02010110, 0x02010112, 0x02020111, - 0x00000020, 0x00000022, 0x00000220, 0x00000222, 0x00010121, 0x00020020, 0x00020022, 0x00020220, - 0x00020222, 0x01000121, 0x01010021, 0x01010221, 0x01020120, 0x01020221, 0x02000020, 0x02000022, - 0x02000220, 0x02000222, 0x02010021, 0x02010121, 0x02010221, 0x02020020, 0x02020022, 0x02020220, - 0x02020222, 0x00011001, 0x00011100, 0x00011102, 0x00021101, 0x01001001, 0x01001201, 0x01011101, - 0x01011202, 0x01021100, 0x01021101, 0x02011001, 0x02011201, 0x02021101, 0x00001011, 0x00001110, - 0x00001111, 0x00001112, 0x00011111, 0x00011210, 0x00011212, 0x00021211, 0x01001010, 0x01001111, - 0x01001212, 0x01011010, 0x01011011, 0x01011110, 0x01011111, 0x01011112, 0x01011211, 0x01021010, - 0x01021012, 0x01021111, 0x01021210, 0x01021212, 0x02001011, 0x02011011, 0x02011111, 0x02011210, - 0x02011212, 0x02021011, 0x02021110, 0x02021111, 0x02021112, 0x02021211, 0x00011120, 0x00011221, - 0x01001021, 0x01001120, 0x01011020, 0x01011022, 0x01011121, 0x01011220, 0x01021020, 0x01021021, - 0x01021122, 0x01021221, 0x02001121, 0x02011021, 0x02011120, 0x02011221, 0x00002000, 0x00002002, - 0x00002200, 0x00002202, 0x00012101, 0x00022000, 0x00022002, 0x00022200, 0x00022202, 0x01002101, - 0x01012001, 0x01012102, 0x01022101, 0x02002000, 0x02002002, 0x02002200, 0x02002202, 0x02012101, - 0x02022000, 0x02022002, 0x02022200, 0x02022202, 0x00002111, 0x00012011, 0x00012110, 0x00012211, - 0x00022110, 0x00022111, 0x01002011, 0x01012010, 0x01012011, 0x01012111, 0x01022011, 0x01022110, - 0x01022211, 0x02012011, 0x02012110, 0x02012112, 0x02012211, 0x02022111, 0x00002020, 0x00002022, - 0x00002220, 0x00002222, 0x00012121, 0x00022020, 0x00022022, 0x00022220, 0x00022222, 0x01002121, - 0x01012021, 0x01012221, 0x01022021, 0x01022121, 0x02002020, 0x02002022, 0x02002121, 0x02002220, - 0x02002222, 0x02012121, 0x02022020, 0x02022022, 0x02022220, 0x02022222, 0x00110000, 0x00110001, - 0x00110100, 0x00110201, 0x00120100, 0x00120101, 0x01100001, 0x01100100, 0x01110000, 0x01110101, - 0x01110200, 0x01120001, 0x01120100, 0x01120101, 0x01120201, 0x02110001, 0x02110100, 0x02110102, - 0x02120001, 0x02120101, 0x00100011, 0x00100110, 0x00100112, 0x00100211, 0x00110010, 0x00110012, - 0x00110111, 0x00110210, 0x00120011, 0x00120110, 0x00120211, 0x01100111, 0x01100212, 0x01110010, - 0x01110011, 0x01110012, 0x01110110, 0x01110111, 0x01110112, 0x01110211, 0x01120010, 0x01120111, - 0x02100110, 0x02110012, 0x02110111, 0x02120011, 0x02120110, 0x00110021, 0x00110120, 0x00110122, - 0x00120121, 0x01100020, 0x01100122, 0x01100221, 0x01110022, 0x01110121, 0x01110220, 0x01110222, - 0x01120120, 0x01120122, 0x02100121, 0x02110021, 0x02110120, 0x02110122, 0x02120121, 0x00101001, - 0x00101102, 0x00101201, 0x00111100, 0x00111101, 0x00111200, 0x00111201, 0x00121001, 0x00121102, - 0x01101001, 0x01101101, 0x01101102, 0x01101200, 0x01101202, 0x01111001, 0x01111100, 0x01111101, - 0x01111102, 0x01111201, 0x01121002, 0x01121101, 0x01121200, 0x02101100, 0x02101201, 0x02111000, - 0x02111100, 0x02111101, 0x02111200, 0x02111201, 0x02111202, 0x02121001, 0x02121100, 0x02121101, - 0x02121201, 0x00101012, 0x00101111, 0x00101212, 0x00111011, 0x00111110, 0x00111111, 0x00111112, - 0x00111211, 0x00121010, 0x00121012, 0x00121111, 0x00121210, 0x00121212, 0x01101011, 0x01101110, - 0x01101111, 0x01101112, 0x01111011, 0x01111012, 0x01111110, 0x01111111, 0x01111112, 0x01111211, - 0x01111212, 0x01121011, 0x01121110, 0x01121111, 0x01121112, 0x01121211, 0x02101010, 0x02101012, - 0x02101110, 0x02101111, 0x02101210, 0x02101212, 0x02111010, 0x02111011, 0x02111110, 0x02111111, - 0x02111112, 0x02111211, 0x02111212, 0x02121010, 0x02121012, 0x02121111, 0x00101021, 0x00101120, - 0x00101121, 0x00101122, 0x00111121, 0x00111122, 0x00111220, 0x00111222, 0x00121021, 0x00121122, - 0x01101020, 0x01101022, 0x01101120, 0x01101121, 0x01101220, 0x01101222, 0x01111021, 0x01111121, - 0x01111122, 0x01111220, 0x01111221, 0x01121021, 0x01121120, 0x01121121, 0x01121220, 0x01121221, - 0x01121222, 0x02101122, 0x02101222, 0x02111022, 0x02111121, 0x02121120, 0x02121221, 0x00112001, - 0x00112102, 0x00122101, 0x01102001, 0x01102100, 0x01102102, 0x01102201, 0x01112000, 0x01112101, - 0x01112200, 0x01112202, 0x01122000, 0x01122001, 0x01122100, 0x01122102, 0x01122201, 0x02102101, - 0x02112001, 0x02112100, 0x02122101, 0x00112010, 0x00112012, 0x00112111, 0x00112212, 0x00122011, - 0x00122111, 0x01102012, 0x01102110, 0x01102111, 0x01102210, 0x01112011, 0x01112110, 0x01112111, - 0x01112112, 0x01112211, 0x01112212, 0x01122010, 0x01122111, 0x01122212, 0x02102211, 0x02112011, - 0x02112012, 0x02112111, 0x02112210, 0x02122011, 0x02122112, 0x02122211, 0x00102221, 0x00112122, - 0x00122120, 0x00122122, 0x01102120, 0x01102122, 0x01102221, 0x01112020, 0x01112022, 0x01112121, - 0x01112220, 0x01122021, 0x01122122, 0x01122221, 0x02102121, 0x02112021, 0x02112122, 0x02112222, - 0x00200000, 0x00200002, 0x00200200, 0x00200202, 0x00210101, 0x00220000, 0x00220002, 0x00220101, - 0x00220200, 0x00220202, 0x01200101, 0x01210001, 0x01210201, 0x01220001, 0x01220101, 0x02200000, - 0x02200002, 0x02200200, 0x02200202, 0x02210101, 0x02220000, 0x02220002, 0x02220101, 0x02220200, - 0x02220202, 0x00200111, 0x00210011, 0x00210110, 0x00210211, 0x00220111, 0x01200012, 0x01200110, - 0x01200211, 0x01210111, 0x01210210, 0x01210212, 0x01220011, 0x01220110, 0x01220111, 0x01220112, - 0x02200111, 0x02210010, 0x02210112, 0x02210211, 0x02220111, 0x00200021, 0x00200220, 0x00200222, - 0x00210021, 0x00210121, 0x00220020, 0x00220022, 0x00220220, 0x00220222, 0x01200121, 0x01210021, - 0x01210122, 0x01210221, 0x01220121, 0x02200021, 0x02200220, 0x02200222, 0x02210021, 0x02210121, - 0x02220020, 0x02220022, 0x02220220, 0x02220222, 0x00201101, 0x00211100, 0x00211102, 0x00211201, - 0x00221101, 0x01201100, 0x01201101, 0x01201102, 0x01201201, 0x01211002, 0x01211101, 0x01211200, - 0x01211202, 0x01221102, 0x02201101, 0x02211001, 0x02211100, 0x02211201, 0x02221001, 0x02221101, - 0x00201211, 0x00211111, 0x00221011, 0x00221211, 0x01201010, 0x01201111, 0x01201210, 0x01211011, - 0x01211110, 0x01211111, 0x01211211, 0x01221012, 0x01221111, 0x01221210, 0x02201211, 0x02211010, - 0x02211110, 0x02211111, 0x02211210, 0x02211212, 0x02221011, 0x02221110, 0x02221112, 0x02221211, - 0x00201121, 0x00211020, 0x00211022, 0x00211221, 0x00221121, 0x01201021, 0x01201221, 0x01211121, - 0x01221020, 0x01221021, 0x01221221, 0x02201120, 0x02201122, 0x02211020, 0x02211222, 0x00202000, - 0x00202002, 0x00202200, 0x00202202, 0x00212101, 0x00222000, 0x00222002, 0x00222200, 0x00222202, - 0x01202101, 0x01212001, 0x01212100, 0x01222101, 0x02202000, 0x02202002, 0x02202200, 0x02202202, - 0x02222000, 0x02222002, 0x02222200, 0x02222202, 0x00202211, 0x00212011, 0x00212110, 0x00212211, - 0x00222111, 0x01202112, 0x01202211, 0x01212012, 0x01212111, 0x01222011, 0x01222110, 0x01222112, - 0x01222211, 0x02202111, 0x02212010, 0x02212112, 0x02212211, 0x02222110, 0x02222111, 0x00202020, - 0x00202022, 0x00202220, 0x00202222, 0x00222020, 0x00222022, 0x00222220, 0x00222222, 0x01202121, - 0x01212021, 0x01212122, 0x01212221, 0x01222121, 0x02202020, 0x02202022, 0x02202220, 0x02202222, - 0x02212121, 0x02222020, 0x02222022, 0x02222220, 0x02222222, 0x10000101, 0x10010001, 0x10010102, - 0x10020101, 0x11000201, 0x11010002, 0x11010101, 0x11010200, 0x11010202, 0x11020001, 0x11020100, - 0x11020102, 0x12010100, 0x12010201, 0x12020001, 0x12020102, 0x10000010, 0x10000011, 0x10000110, - 0x10000112, 0x10000211, 0x10010012, 0x10010111, 0x10010112, 0x10010210, 0x10010212, 0x10020011, - 0x10020112, 0x10020211, 0x11000111, 0x11000210, 0x11000212, 0x11010011, 0x11010110, 0x11010111, - 0x11010112, 0x11010211, 0x11010212, 0x11020111, 0x11020210, 0x11020212, 0x12000011, 0x12000110, - 0x12000112, 0x12010010, 0x12010012, 0x12010111, 0x12020010, 0x12020011, 0x12020012, 0x10000121, - 0x10010021, 0x10010120, 0x10010122, 0x10020121, 0x11000021, 0x11010022, 0x11010121, 0x11010222, - 0x11020120, 0x11020221, 0x12000221, 0x12010120, 0x12020121, 0x10001001, 0x10011101, 0x10011201, - 0x10021201, 0x11001101, 0x11001200, 0x11001202, 0x11011001, 0x11011100, 0x11011101, 0x11011102, - 0x11021001, 0x11021002, 0x11021101, 0x11021200, 0x11021202, 0x12001001, 0x12001102, 0x12001201, - 0x12011000, 0x12011002, 0x12011101, 0x12021000, 0x12021001, 0x12021201, 0x10001011, 0x10001012, - 0x10001111, 0x10001212, 0x10011011, 0x10011110, 0x10011111, 0x10011112, 0x10011211, 0x10021010, - 0x10021111, 0x10021212, 0x11001011, 0x11001110, 0x11001111, 0x11001112, 0x11001211, 0x11011010, - 0x11011011, 0x11011110, 0x11011111, 0x11011112, 0x11011210, 0x11011211, 0x11021011, 0x11021110, - 0x11021111, 0x11021112, 0x11021211, 0x12001012, 0x12001110, 0x12001111, 0x12001210, 0x12011011, - 0x12011110, 0x12011111, 0x12011112, 0x12011211, 0x12011212, 0x12021111, 0x12021210, 0x12021212, - 0x10001021, 0x10001121, 0x10001221, 0x10011120, 0x10011121, 0x10011220, 0x10011222, 0x10021021, - 0x10021120, 0x10021221, 0x11001020, 0x11001022, 0x11001121, 0x11001220, 0x11011020, 0x11011021, - 0x11011022, 0x11011121, 0x11011122, 0x11011221, 0x11021022, 0x11021121, 0x11021220, 0x12001021, - 0x12001121, 0x12001222, 0x12011120, 0x12011121, 0x12021021, 0x12021120, 0x12021122, 0x10002101, - 0x10012001, 0x10012101, 0x10012202, 0x10022101, 0x11002002, 0x11002201, 0x11012000, 0x11012101, - 0x11012200, 0x11022001, 0x11022100, 0x11022102, 0x11022201, 0x12002101, 0x12012001, 0x12012100, - 0x12012102, 0x12012201, 0x12022101, 0x10002011, 0x10002111, 0x10002112, 0x10002212, 0x10012010, - 0x10012110, 0x10012111, 0x10012210, 0x10022011, 0x10022110, 0x10022112, 0x11002010, 0x11002111, - 0x11002212, 0x11012011, 0x11012012, 0x11012110, 0x11012111, 0x11012112, 0x11012211, 0x11022010, - 0x11022012, 0x11022111, 0x11022112, 0x11022212, 0x12002112, 0x12002211, 0x12012012, 0x12012111, - 0x12012112, 0x12012210, 0x12022011, 0x12022110, 0x12022112, 0x12022211, 0x10012122, 0x11002120, - 0x11002122, 0x11002221, 0x11012121, 0x11012220, 0x11012222, 0x11022120, 0x11022221, 0x12012120, - 0x12022121, 0x10100001, 0x10100100, 0x10100101, 0x10100102, 0x10100201, 0x10110002, 0x10110101, - 0x10110202, 0x10120001, 0x10120100, 0x10120201, 0x11100000, 0x11100101, 0x11100200, 0x11110001, - 0x11110100, 0x11110101, 0x11110102, 0x11110201, 0x11120101, 0x11120200, 0x12100102, 0x12100201, - 0x12110101, 0x12110200, 0x12120000, 0x12120001, 0x12120102, 0x12120201, 0x10100111, 0x10100210, - 0x10100211, 0x10100212, 0x10110011, 0x10110110, 0x10110111, 0x10110112, 0x10110210, 0x10110211, - 0x10120010, 0x10120111, 0x10120112, 0x10120210, 0x10120212, 0x11100011, 0x11100110, 0x11100111, - 0x11100112, 0x11100211, 0x11110010, 0x11110011, 0x11110012, 0x11110110, 0x11110111, 0x11110112, - 0x11110210, 0x11110211, 0x11110212, 0x11120011, 0x11120110, 0x11120111, 0x11120112, 0x11120211, - 0x12100012, 0x12100111, 0x12110011, 0x12110110, 0x12110111, 0x12110112, 0x12110211, 0x12120010, - 0x12120111, 0x12120212, 0x10100021, 0x10100122, 0x10110022, 0x10110121, 0x10110222, 0x10120021, - 0x10120120, 0x11100022, 0x11100121, 0x11100222, 0x11110021, 0x11110120, 0x11110121, 0x11110122, - 0x11110221, 0x11120022, 0x11120121, 0x12100121, 0x12110020, 0x12110022, 0x12110121, 0x12110221, - 0x12110222, 0x12120120, 0x10101100, 0x10101101, 0x10111001, 0x10111100, 0x10111101, 0x10111102, - 0x10111200, 0x10111201, 0x10121001, 0x10121101, 0x10121200, 0x10121202, 0x11101001, 0x11101100, - 0x11101101, 0x11101102, 0x11101201, 0x11101202, 0x11111000, 0x11111001, 0x11111100, 0x11111101, - 0x11111102, 0x11111200, 0x11111201, 0x11111202, 0x11121001, 0x11121002, 0x11121100, 0x11121101, - 0x11121102, 0x11121201, 0x12101000, 0x12101200, 0x12101202, 0x12111001, 0x12111100, 0x12111101, - 0x12111102, 0x12111201, 0x12121001, 0x12121100, 0x12121101, 0x12121202, 0x10101011, 0x10101012, - 0x10101110, 0x10101111, 0x10101112, 0x10101211, 0x10111010, 0x10111011, 0x10111012, 0x10111110, - 0x10111111, 0x10111112, 0x10111211, 0x10111212, 0x10121011, 0x10121110, 0x10121111, 0x10121112, - 0x10121211, 0x11101010, 0x11101011, 0x11101012, 0x11101110, 0x11101111, 0x11101112, 0x11101210, - 0x11101211, 0x11111010, 0x11111011, 0x11111012, 0x11111110, 0x11111111, 0x11111112, 0x11111210, - 0x11111211, 0x11111212, 0x11121010, 0x11121011, 0x11121110, 0x11121111, 0x11121112, 0x11121210, - 0x11121211, 0x11121212, 0x12101011, 0x12101110, 0x12101111, 0x12101211, 0x12101212, 0x12111010, - 0x12111011, 0x12111110, 0x12111111, 0x12111112, 0x12111210, 0x12111211, 0x12121011, 0x12121110, - 0x12121111, 0x12121112, 0x12121211, 0x10101020, 0x10101021, 0x10101022, 0x10101120, 0x10101122, - 0x10101220, 0x10101221, 0x10111021, 0x10111120, 0x10111121, 0x10111220, 0x10111221, 0x10121020, - 0x10121021, 0x10121022, 0x10121120, 0x10121121, 0x10121122, 0x10121220, 0x10121221, 0x11101021, - 0x11101121, 0x11101122, 0x11101220, 0x11101221, 0x11101222, 0x11111020, 0x11111021, 0x11111022, - 0x11111120, 0x11111121, 0x11111122, 0x11111220, 0x11111221, 0x11111222, 0x11121021, 0x11121120, - 0x11121121, 0x11121221, 0x12101022, 0x12101121, 0x12101122, 0x12101220, 0x12101221, 0x12101222, - 0x12111021, 0x12111121, 0x12111222, 0x12121022, 0x12121121, 0x12121122, 0x12121220, 0x12121221, - 0x10102100, 0x10102101, 0x10102102, 0x10102201, 0x10112000, 0x10112101, 0x10112200, 0x10122001, - 0x10122202, 0x11102101, 0x11102200, 0x11102202, 0x11112001, 0x11112100, 0x11112101, 0x11112102, - 0x11112200, 0x11112201, 0x11122000, 0x11122002, 0x11122100, 0x11122101, 0x12102002, 0x12102201, - 0x12112000, 0x12112002, 0x12112101, 0x12112200, 0x12122001, 0x12122201, 0x10102011, 0x10102012, - 0x10102111, 0x10102212, 0x10112011, 0x10112110, 0x10112111, 0x10112112, 0x10112211, 0x10122111, - 0x11102011, 0x11102110, 0x11102111, 0x11102112, 0x11102211, 0x11112010, 0x11112011, 0x11112012, - 0x11112110, 0x11112111, 0x11112112, 0x11112210, 0x11112211, 0x11112212, 0x11122011, 0x11122110, - 0x11122111, 0x11122112, 0x11122211, 0x12102011, 0x12102111, 0x12102211, 0x12112011, 0x12112110, - 0x12112111, 0x12112112, 0x12112210, 0x12112211, 0x12122111, 0x10102120, 0x10102220, 0x10112121, - 0x10112222, 0x10122020, 0x10122121, 0x10122122, 0x10122221, 0x11102121, 0x11102220, 0x11102221, - 0x11112021, 0x11112121, 0x11112122, 0x11112220, 0x11112221, 0x11122022, 0x11122121, 0x11122220, - 0x11122222, 0x12102021, 0x12102222, 0x12112022, 0x12112121, 0x12112122, 0x12112220, 0x12112222, - 0x12122021, 0x10200101, 0x10210100, 0x10210102, 0x10210201, 0x10220101, 0x11200100, 0x11210000, - 0x11210101, 0x11210102, 0x11210200, 0x11210202, 0x11220001, 0x11220100, 0x11220102, 0x11220201, - 0x12200001, 0x12210102, 0x12220101, 0x10200011, 0x10200110, 0x10200112, 0x10200211, 0x10210012, - 0x10210111, 0x10220011, 0x10220012, 0x10220112, 0x10220211, 0x11200111, 0x11200211, 0x11210011, - 0x11210111, 0x11210112, 0x11210211, 0x11220111, 0x11220112, 0x11220212, 0x12200110, 0x12200212, - 0x12210012, 0x12210111, 0x12220011, 0x12220112, 0x12220211, 0x10210021, 0x10210122, 0x10210221, - 0x11200020, 0x11200021, 0x11200122, 0x11210121, 0x11210122, 0x11210220, 0x11220020, 0x12200121, - 0x12210021, 0x12210122, 0x12220121, 0x10211001, 0x10211002, 0x10211101, 0x10211102, 0x10211202, - 0x10221001, 0x10221102, 0x10221201, 0x11201000, 0x11201002, 0x11201101, 0x11201200, 0x11201202, - 0x11211001, 0x11211100, 0x11211101, 0x11211102, 0x11211201, 0x11211202, 0x11221000, 0x11221002, - 0x11221101, 0x12201100, 0x12201101, 0x12201201, 0x12211000, 0x12211002, 0x12211100, 0x12211101, - 0x12211102, 0x12211200, 0x12211202, 0x12221001, 0x12221100, 0x12221201, 0x10201111, 0x10201210, - 0x10201212, 0x10211011, 0x10211111, 0x10211112, 0x10211211, 0x11201110, 0x11201111, 0x11201112, - 0x11201211, 0x11211010, 0x11211011, 0x11211110, 0x11211111, 0x11211112, 0x11211211, 0x11221011, - 0x11221110, 0x11221111, 0x11221112, 0x11221211, 0x12201112, 0x12201211, 0x12201212, 0x12211011, - 0x12211111, 0x12211112, 0x12211211, 0x12211212, 0x12221012, 0x12221111, 0x12221112, 0x12221210, - 0x10201022, 0x10201221, 0x10211121, 0x10221020, 0x10221122, 0x10221220, 0x10221221, 0x11201020, - 0x11201121, 0x11201220, 0x11201222, 0x11211021, 0x11211120, 0x11211121, 0x11211122, 0x11211220, - 0x11211222, 0x11221020, 0x11221121, 0x11221220, 0x12201020, 0x12201022, 0x12201121, 0x12201222, - 0x12211120, 0x12211122, 0x12211220, 0x12211221, 0x12221020, 0x12221120, 0x12221122, 0x12221222, - 0x10212102, 0x10212201, 0x10222101, 0x11202001, 0x11212002, 0x11212101, 0x11212202, 0x11222001, - 0x11222201, 0x12202101, 0x12212001, 0x12212200, 0x12222102, 0x10202011, 0x10202110, 0x10212010, - 0x10212111, 0x10222011, 0x10222110, 0x10222112, 0x10222211, 0x11202010, 0x11202011, 0x11202111, - 0x11202112, 0x11202210, 0x11212011, 0x11212110, 0x11212111, 0x11212112, 0x11212211, 0x11222010, - 0x11222111, 0x11222212, 0x12202012, 0x12202110, 0x12202212, 0x12212111, 0x12222011, 0x12222110, - 0x12222111, 0x12222211, 0x10212021, 0x10212122, 0x10212220, 0x11202021, 0x11202120, 0x11202221, - 0x11212020, 0x11212121, 0x11212220, 0x11212222, 0x11222120, 0x11222121, 0x11222221, 0x12202122, - 0x12212120, 0x12212220, 0x12212222, 0x12222122, 0x20000000, 0x20000002, 0x20000200, 0x20000202, - 0x20020000, 0x20020002, 0x20020200, 0x20020202, 0x21000101, 0x21010000, 0x21010001, 0x21010100, - 0x21010102, 0x21010201, 0x21020101, 0x22000000, 0x22000002, 0x22000200, 0x22000202, 0x22010101, - 0x22020000, 0x22020002, 0x22020200, 0x22020202, 0x20000111, 0x20010011, 0x20010110, 0x20010112, - 0x20010211, 0x20020111, 0x21000011, 0x21000110, 0x21000211, 0x21010010, 0x21010012, 0x21010111, - 0x21010112, 0x21010210, 0x21010211, 0x21020110, 0x21020112, 0x21020211, 0x22000111, 0x22000211, - 0x22010110, 0x22010112, 0x22010211, 0x22020111, 0x20000020, 0x20000022, 0x20000220, 0x20000222, - 0x20010121, 0x20020020, 0x20020022, 0x20020220, 0x20020222, 0x21010021, 0x21010120, 0x21010221, - 0x21020121, 0x22000020, 0x22000022, 0x22000220, 0x22000222, 0x22010121, 0x22020020, 0x22020022, - 0x22020220, 0x22020222, 0x20011100, 0x20011201, 0x21001001, 0x21001100, 0x21011001, 0x21011101, - 0x21011202, 0x21021001, 0x21021100, 0x21021201, 0x22011100, 0x22011201, 0x20001011, 0x20001211, - 0x20011012, 0x20011111, 0x20011212, 0x20021112, 0x20021211, 0x21001010, 0x21001011, 0x21001111, - 0x21001210, 0x21011011, 0x21011110, 0x21011111, 0x21011112, 0x21011211, 0x21011212, 0x21021111, - 0x21021112, 0x21021210, 0x21021212, 0x22001011, 0x22001110, 0x22001112, 0x22001211, 0x22011010, - 0x22011012, 0x22011111, 0x22011210, 0x22021112, 0x20011021, 0x20011122, 0x20011221, 0x20021121, - 0x21001021, 0x21001120, 0x21001221, 0x21001222, 0x21011020, 0x21011121, 0x21011221, 0x21011222, - 0x21021021, 0x21021122, 0x21021222, 0x22001121, 0x22011021, 0x22011222, 0x22021120, 0x20002000, - 0x20002002, 0x20002200, 0x20002202, 0x20012101, 0x20022000, 0x20022002, 0x20022200, 0x20022202, - 0x21002001, 0x21002101, 0x21012001, 0x21012100, 0x21012201, 0x21022101, 0x21022201, 0x22002000, - 0x22002002, 0x22002200, 0x22002202, 0x22012101, 0x22022000, 0x22022002, 0x22022200, 0x22022202, - 0x20002111, 0x20002112, 0x20012011, 0x20012110, 0x20012112, 0x20022111, 0x21002011, 0x21002110, - 0x21002112, 0x21002211, 0x21012010, 0x21012012, 0x21012111, 0x21012212, 0x21022011, 0x21022110, - 0x22002111, 0x22012112, 0x22012211, 0x22022111, 0x20002020, 0x20002022, 0x20002220, 0x20002222, - 0x20012121, 0x20022020, 0x20022022, 0x20022220, 0x20022222, 0x21002121, 0x21012021, 0x21012120, - 0x21012122, 0x22002020, 0x22002022, 0x22002220, 0x22002222, 0x22012121, 0x22022020, 0x22022022, - 0x22022220, 0x22022222, 0x20100101, 0x20110001, 0x20110102, 0x20110200, 0x20110201, 0x20120101, - 0x21100001, 0x21100102, 0x21100201, 0x21110101, 0x21110200, 0x21110202, 0x21120201, 0x21120202, - 0x22100101, 0x22110001, 0x22110100, 0x22110102, 0x22110201, 0x22120101, 0x20100011, 0x20100110, - 0x20100112, 0x20100211, 0x20110010, 0x20110111, 0x20110210, 0x20110212, 0x20120011, 0x20120110, - 0x20120112, 0x20120211, 0x21100010, 0x21100111, 0x21110010, 0x21110011, 0x21110110, 0x21110111, - 0x21110112, 0x21110211, 0x21120012, 0x21120111, 0x22100110, 0x22100112, 0x22110012, 0x22110111, - 0x22110210, 0x22120011, 0x22120110, 0x22120112, 0x22120211, 0x20100121, 0x20110021, 0x20110120, - 0x20110221, 0x20120121, 0x21100120, 0x21100122, 0x21100221, 0x21110020, 0x21110022, 0x21110121, - 0x21110220, 0x21120122, 0x21120221, 0x22100121, 0x22110120, 0x22110122, 0x22120221, 0x20101001, - 0x20101100, 0x20101102, 0x20111000, 0x20111101, 0x20111200, 0x20121102, 0x21101000, 0x21101202, - 0x21111001, 0x21111100, 0x21111101, 0x21111102, 0x21111200, 0x21111201, 0x21121000, 0x21121001, - 0x21121002, 0x21121101, 0x22101100, 0x22101102, 0x22111002, 0x22111100, 0x22111101, 0x22111200, - 0x22121001, 0x22121201, 0x20101010, 0x20101111, 0x20101210, 0x20101212, 0x20111010, 0x20111011, - 0x20111110, 0x20111111, 0x20111112, 0x20111211, 0x20121011, 0x20121111, 0x20121211, 0x20121212, - 0x21101011, 0x21101110, 0x21101111, 0x21101112, 0x21101211, 0x21111010, 0x21111011, 0x21111012, - 0x21111110, 0x21111111, 0x21111112, 0x21111210, 0x21111211, 0x21111212, 0x21121011, 0x21121110, - 0x21121111, 0x21121112, 0x21121211, 0x22101011, 0x22101111, 0x22101210, 0x22111011, 0x22111012, - 0x22111110, 0x22111111, 0x22111112, 0x22111211, 0x22111212, 0x22121010, 0x22121012, 0x22121111, - 0x22121210, 0x22121212, 0x20101021, 0x20101120, 0x20111020, 0x20111121, 0x20111221, 0x20121020, - 0x20121122, 0x20121221, 0x21101121, 0x21101220, 0x21101221, 0x21111021, 0x21111022, 0x21111121, - 0x21111122, 0x21111221, 0x21121121, 0x21121220, 0x22101022, 0x22101120, 0x22101221, 0x22101222, - 0x22111022, 0x22111120, 0x22111121, 0x22121120, 0x22121122, 0x22121221, 0x20102101, 0x20112102, - 0x20112201, 0x20122101, 0x21102001, 0x21102102, 0x21112000, 0x21112002, 0x21112101, 0x21112102, - 0x21112202, 0x21122100, 0x21122101, 0x22102101, 0x22112001, 0x22112102, 0x22112201, 0x22122101, - 0x20102110, 0x20102112, 0x20102211, 0x20112010, 0x20112012, 0x20112111, 0x20112210, 0x20112212, - 0x20122010, 0x20122011, 0x20122110, 0x20122112, 0x21102010, 0x21102012, 0x21102111, 0x21102210, - 0x21102212, 0x21112011, 0x21112110, 0x21112111, 0x21112112, 0x21112211, 0x21122012, 0x21122111, - 0x21122112, 0x21122212, 0x22102011, 0x22102110, 0x22112010, 0x22112012, 0x22112111, 0x22112212, - 0x22122011, 0x22122112, 0x20102121, 0x20112121, 0x20122121, 0x21102120, 0x21102122, 0x21102221, - 0x21112020, 0x21112121, 0x21112220, 0x21122021, 0x22102121, 0x22112021, 0x22112120, 0x22112121, - 0x22112122, 0x20200000, 0x20200002, 0x20200200, 0x20200202, 0x20210101, 0x20220000, 0x20220002, - 0x20220200, 0x20220202, 0x21200101, 0x21210001, 0x21210100, 0x21210102, 0x21210201, 0x22200000, - 0x22200002, 0x22200200, 0x22200202, 0x22210101, 0x22220000, 0x22220002, 0x22220200, 0x22220202, - 0x20200111, 0x20200211, 0x20210011, 0x20210110, 0x20210112, 0x20210211, 0x20210212, 0x21200112, - 0x21200211, 0x21210011, 0x21210111, 0x21210210, 0x21210212, 0x21220011, 0x21220110, 0x22200111, - 0x22210010, 0x22210012, 0x22210112, 0x22210211, 0x20200022, 0x20200220, 0x20200222, 0x20210020, - 0x20210221, 0x20220022, 0x20220220, 0x20220222, 0x21200121, 0x21210021, 0x21210122, 0x21210221, - 0x21220121, 0x22200020, 0x22200022, 0x22200220, 0x22200222, 0x22210121, 0x22220020, 0x22220022, - 0x22220220, 0x22220222, 0x20211201, 0x20221101, 0x21201001, 0x21201100, 0x21211000, 0x21211100, - 0x21211101, 0x21211200, 0x21211202, 0x21221001, 0x21221101, 0x21221102, 0x21221200, 0x21221201, - 0x22201101, 0x20201112, 0x20201211, 0x20211010, 0x20211012, 0x20211111, 0x20211210, 0x20221112, - 0x20221211, 0x21201012, 0x21201111, 0x21211011, 0x21211110, 0x21211111, 0x21211112, 0x21211211, - 0x21221111, 0x21221212, 0x22201011, 0x22201110, 0x22201111, 0x22201112, 0x22201211, 0x22211012, - 0x22211111, 0x22211210, 0x20201121, 0x20211021, 0x20211122, 0x20211222, 0x20221021, 0x20221121, - 0x21201120, 0x21201122, 0x21201222, 0x21211022, 0x21211121, 0x21211122, 0x21211220, 0x21221020, - 0x21221022, 0x22201122, 0x22211020, 0x22211121, 0x22211122, 0x22211221, 0x22221021, 0x22221120, - 0x22221122, 0x20202000, 0x20202002, 0x20202200, 0x20202202, 0x20222000, 0x20222002, 0x20222200, - 0x20222202, 0x21212001, 0x21212100, 0x21212102, 0x21212201, 0x22202000, 0x22202002, 0x22202200, - 0x22202202, 0x22212101, 0x22222000, 0x22222002, 0x22222200, 0x22222202, 0x20202111, 0x20212110, - 0x20212211, 0x20222011, 0x20222111, 0x21202011, 0x21212010, 0x21212111, 0x21212212, 0x21222011, - 0x21222112, 0x21222211, 0x22212010, 0x22212112, 0x20202020, 0x20202022, 0x20202220, 0x20202222, - 0x20222020, 0x20222022, 0x20222220, 0x20222222, 0x21212021, 0x21212120, 0x21212122, 0x22202020, - 0x22202022, 0x22202220, 0x22202222, 0x22212121, 0x22222020, 0x22222022, 0x22222220, 0x22222222, -GGML_TABLE_END() -#endif - -#endif // GGML_COMMON_IMPL -#endif // GGML_COMMON_IMPL diff --git a/third_party/llama.cpp b/third_party/llama.cpp deleted file mode 160000 index 3cf0325..0000000 --- a/third_party/llama.cpp +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 3cf03257f219afbe7334045ff7c6a06ac68c627d diff --git a/tools/_paths.py b/tools/_paths.py deleted file mode 100644 index 336719e..0000000 --- a/tools/_paths.py +++ /dev/null @@ -1,28 +0,0 @@ -"""tools/_paths.py - where the tools find llama.cpp's gguf-py (for the MTP packer and the fixtures). - -Order: $STRATA_GGUF_PY, then /third_party/llama.cpp/gguf-py (what setup.py clones), then the development -tree's ../../.ref/llama.cpp/gguf-py. -""" -from __future__ import annotations - -import os -import sys -from pathlib import Path - -ENGINE = Path(__file__).resolve().parents[1] - - -def gguf_py() -> str: - cands = [os.environ.get("STRATA_GGUF_PY"), ENGINE / "third_party" / "llama.cpp" / "gguf-py", - ENGINE.parents[min(1, len(ENGINE.parents) - 1)] / ".ref" / "llama.cpp" / "gguf-py"] # the dev tree; a shallow install (G:\Strata) has no grandparent - for c in cands: - if c and (Path(c) / "gguf").is_dir(): - return str(c) - sys.exit("llama.cpp's gguf-py was not found: run setup.py (it clones llama.cpp into third_party/), " - "or set STRATA_GGUF_PY") - - -def add_gguf_py() -> None: - p = gguf_py() - if p not in sys.path: - sys.path.insert(0, p) diff --git a/tools/draft_vocab.py b/tools/draft_vocab.py deleted file mode 100644 index b3cc9fc..0000000 --- a/tools/draft_vocab.py +++ /dev/null @@ -1,146 +0,0 @@ -"""The draft head's token subset (rt/draft_vocab.bin): the vocabulary rows the MTP draft layer may propose. - -The engine reads rt/draft_vocab.bin (int32 token ids) when the draft layer binds and computes the draft logits over -those rows only: a smaller head is faster and takes less VRAM, but a token outside the subset can never be drafted. -The shipped subset was built from English and code and had 27 of the vocabulary's 55,328 Han tokens, so an answer in -Chinese drafted almost nothing (#137). This adds whole scripts to a subset: - - python tools/draft_vocab.py --gguf -00001-of-0000N.gguf --base data/draft_vocab.bin --add cjk \ - --out data/draft_vocab.bin - ---add takes han, kana, hangul, cjk_punct, cjk (those four) or cyrillic. The base ids keep their order; the added ones follow in -id order. --stats prints what a subset holds. - -A language written in a script the base already holds (French, Spanish, German... in Latin letters) needs specific -words and word pieces, not a whole script. --corpus adds the tokens of a text corpus in that language: the most -frequent ones that together cover --coverage (default 0.99) of the corpus's token occurrences (#597): - - python tools/draft_vocab.py --gguf -00001-of-0000N.gguf --base data/draft_vocab_en.bin \ - --corpus fr1.txt fr2.txt ... --coverage 0.99 --out data/draft_vocab_fr.bin - -It prints the share of the corpus's occurrences outside the base and outside the new subset. --add and --corpus -can be combined. -""" -from __future__ import annotations - -import argparse -import sys -from array import array -from collections import Counter -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -import strata_tokenizer as ST # noqa: E402 - -SCRIPTS = { - "han": [(0x3400, 0x4DBF), (0x4E00, 0x9FFF), (0xF900, 0xFAFF), (0x20000, 0x2FA1F)], - "kana": [(0x3040, 0x30FF), (0x31F0, 0x31FF), (0xFF66, 0xFF9F)], - "hangul": [(0x1100, 0x11FF), (0x3130, 0x318F), (0xAC00, 0xD7AF)], - "cjk_punct": [(0x3000, 0x303F), (0xFF00, 0xFF65), (0xFFA0, 0xFFEF)], - # Ukrainian, Russian, Bulgarian, Serbian...: the shipped subset held 142 of the vocabulary's 18,580 Cyrillic tokens - "cyrillic": [(0x0400, 0x04FF), (0x0500, 0x052F), (0x1C80, 0x1C8F), (0x2DE0, 0x2DFF), (0xA640, 0xA69F)], -} -GROUPS = {"cjk": ["han", "kana", "hangul", "cjk_punct"]} - - -def scripts_of(text: str) -> set[str]: - found = set() - for ch in text: - c = ord(ch) - for name, ranges in SCRIPTS.items(): - if any(a <= c <= b for a, b in ranges): - found.add(name) - return found - - -def token_text(tok, i: int) -> str | None: - """A token's text, or None when its bytes are not whole UTF-8 characters (a piece of one) or it is special.""" - try: - return tok.token_bytes(i).decode("utf-8") - except (KeyError, UnicodeDecodeError, IndexError): - return None - - -def corpus_counts(tok, paths) -> Counter: - """Token occurrences over the corpus files (UTF-8 text, tokenized as plain text: no special tokens).""" - counts: Counter = Counter() - for path in paths: - counts.update(tok.encode(Path(path).read_text(encoding="utf-8"))) - return counts - - -def covering(counts: Counter, coverage: float) -> list[int]: - """The most frequent ids (ties: the lower id first) that together cover `coverage` of the occurrences.""" - total = sum(counts.values()) - picked, covered = [], 0 - for i, c in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])): - if covered >= coverage * total: - break - picked.append(i) - covered += c - return picked - - -def outside(counts: Counter, ids) -> float: - """The share of the occurrences whose token is not in `ids`.""" - total = sum(counts.values()) - have = set(ids) - return sum(c for i, c in counts.items() if i not in have) / total if total else 0.0 - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--gguf", required=True, help="the model's (first) GGUF file: its vocabulary") - ap.add_argument("--base", help="the subset to extend (int32 ids)") - ap.add_argument("--add", default="", help="comma list: han, kana, hangul, cjk_punct, cjk, cyrillic") - ap.add_argument("--corpus", nargs="+", default=[], help="UTF-8 text files in the language to add (#597)") - ap.add_argument("--coverage", type=float, default=0.99, - help="with --corpus: the share of its token occurrences the added tokens cover (default 0.99)") - ap.add_argument("--out", help="where to write the new subset") - ap.add_argument("--stats", action="store_true", help="print what the base (and the new) subset holds") - a = ap.parse_args() - - tok = ST.Tokenizer.from_gguf(a.gguf) - n = len(tok.tokens) - kinds = [scripts_of(t) if (t := token_text(tok, i)) is not None else set() for i in range(n)] - base = list(array("i", Path(a.base).read_bytes())) if a.base else [] - if any(i < 0 or i >= n for i in base): - sys.exit(f"{a.base} has ids outside the vocabulary ({n})") - - want = set() - for x in filter(None, (s.strip() for s in a.add.split(","))): - names = GROUPS.get(x, [x]) - if any(nm not in SCRIPTS for nm in names): - sys.exit(f"--add {x}: expected one of {', '.join([*SCRIPTS, *GROUPS])}") - want.update(names) - if not 0 < a.coverage <= 1: - sys.exit("--coverage: expected a share in (0, 1]") - counts = corpus_counts(tok, a.corpus) if a.corpus else Counter() - from_corpus = set(covering(counts, a.coverage)) if counts else set() - have = set(base) - added = [i for i in range(n) if i not in have and (kinds[i] & want or i in from_corpus)] - ids = base + added - - def stats(label, sel): - counts = {nm: sum(1 for i in sel if nm in kinds[i]) for nm in SCRIPTS} - full = {nm: sum(1 for k in kinds if nm in k) for nm in SCRIPTS} - print(f"{label}: {len(sel)} ids; " + ", ".join(f"{nm} {counts[nm]}/{full[nm]}" for nm in SCRIPTS)) - - if a.stats or not a.out: - if base: - stats("base", base) - if added: - stats("new", ids) - if counts: - print(f"corpus: {sum(counts.values())} token occurrences, {len(counts)} distinct; " - f"{len(from_corpus)} tokens cover {a.coverage:g}, {len(from_corpus - have)} of them not in the base") - print(f"corpus occurrences outside the base: {outside(counts, base):.2%}, outside the new subset: " - f"{outside(counts, ids):.2%}") - if a.out: - Path(a.out).write_bytes(array("i", ids).tobytes()) - print(f"wrote {a.out}: {len(ids)} ids ({len(added)} added)") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/gguf_reader.py b/tools/gguf_reader.py deleted file mode 100644 index 237d5fd..0000000 --- a/tools/gguf_reader.py +++ /dev/null @@ -1,142 +0,0 @@ -"""Minimal GGUF v3 header reader - no ggml, no gguf-py. - -Written because the `gguf` PyPI package cannot open this artifact: its `GGMLQuantizationType` -enum has no member for type 42 (`Q2_0`), which is newer than the library. That is itself a P0.S6 -finding - the format this engine is specialized for is ahead of the standard tooling. - -This is the reference implementation for `src/artifact/` (architecture §15: "GGUF v3 reader (mmap, -no ggml dependency)"). It parses the header only; tensor data is never read. -""" -from __future__ import annotations - -import dataclasses -import pathlib -import struct -from typing import Any - -GGUF_MAGIC = 0x46554747 # "GGUF" little-endian - -# ggml_type values. 42 = Q2_0, the GSQ-RCO routed-expert encoding, absent from gguf-py as of 0.19. -GGML_TYPES: dict[int, str] = { - 0: "F32", 1: "F16", 2: "Q4_0", 3: "Q4_1", 4: "Q4_2", 5: "Q4_3", 6: "Q5_0", 7: "Q5_1", - 8: "Q8_0", 9: "Q8_1", 10: "Q2_K", 11: "Q3_K", 12: "Q4_K", 13: "Q5_K", 14: "Q6_K", - 15: "Q8_K", 16: "IQ2_XXS", 17: "IQ2_XS", 18: "IQ3_XXS", 19: "IQ1_S", 20: "IQ4_NL", - 21: "IQ3_S", 22: "IQ2_S", 23: "IQ4_XS", 24: "I8", 25: "I16", 26: "I32", 27: "I64", - 28: "F64", 29: "IQ1_M", 30: "BF16", 31: "Q4_0_4_4", 32: "Q4_0_4_8", 33: "Q4_0_8_8", - 34: "TQ1_0", 35: "TQ2_0", 36: "IQ4_NL_4_4", 37: "IQ4_NL_4_8", 38: "IQ4_NL_8_8", - 39: "MXFP4", 40: "NVFP4", 41: "Q4_0_8_8", 42: "Q2_0", -} - -# GGUF metadata value type ids -GGUF_META = { - 0: ("u8", 1), 1: ("i8", 1), 2: ("u16", 2), 3: ("i16", 2), 4: ("u32", 4), 5: ("i32", 4), - 6: ("f32", 4), 7: ("bool", 1), 8: ("string", None), 9: ("array", None), - 10: ("u64", 8), 11: ("i64", 8), 12: ("f64", 8), -} - -# ggml block geometry for the encodings this model uses: (block elements, bytes per block) -# This is what makes a per-tensor byte count checkable, and it is the contract the kernels share. -BLOCK_GEOMETRY: dict[str, tuple[int, int]] = { - "F32": (1, 4), "F16": (1, 2), "BF16": (1, 2), "F64": (1, 8), - "Q4_0": (32, 18), "Q4_1": (32, 20), "Q5_0": (32, 22), "Q5_1": (32, 24), - "Q8_0": (32, 34), "Q8_1": (32, 36), - "Q2_K": (256, 84), "Q3_K": (256, 110), "Q4_K": (256, 144), "Q5_K": (256, 176), - "Q6_K": (256, 210), "Q8_K": (256, 292), - "IQ2_XXS": (256, 66), "IQ2_XS": (256, 74), "IQ3_XXS": (256, 98), "IQ1_S": (256, 50), - "IQ4_NL": (32, 18), "IQ3_S": (256, 110), "IQ2_S": (256, 82), "IQ4_XS": (256, 136), - "IQ1_M": (256, 56), "Q2_0": (64, 18), "MXFP4": (32, 17), "NVFP4": (64, 36), -} - - -@dataclasses.dataclass -class TensorInfo: - name: str - shape: list[int] - type_id: int - type_name: str - offset: int - - @property - def elements(self) -> int: - n = 1 - for d in self.shape: - n *= d - return n - - def expected_bytes(self) -> int | None: - geom = BLOCK_GEOMETRY.get(self.type_name) - if geom is None: - return None - block_elems, block_bytes = geom - if self.elements % block_elems: - return None - return self.elements // block_elems * block_bytes - - -class GGUFFile: - def __init__(self, path: pathlib.Path): - self.path = pathlib.Path(path) - self.metadata: dict[str, Any] = {} - self.tensors: list[TensorInfo] = [] - self.version = 0 - self.alignment = 32 - with self.path.open("rb") as fh: - self._parse(fh) - self.data_start = self._data_start - - # ------------------------------------------------------------------ internals - def _parse(self, fh) -> None: - magic = struct.unpack(" str: - (n,) = struct.unpack(" dict[str, int]: - out: dict[str, int] = {} - for t in self.tensors: - out[t.type_name] = out.get(t.type_name, 0) + 1 - return dict(sorted(out.items(), key=lambda kv: -kv[1])) - - def find(self, needle: str) -> list[TensorInfo]: - return [t for t in self.tensors if needle in t.name] diff --git a/tools/gguf_writer.py b/tools/gguf_writer.py deleted file mode 100644 index 8ad3cd6..0000000 --- a/tools/gguf_writer.py +++ /dev/null @@ -1,234 +0,0 @@ -"""A minimal GGUF v3 WRITER, including `Q2_0`. - -Why this exists ---------------- -P1.S1 of the plan says the tiny synthetic model is "written as a real GGUF via `gguf-py`" using -"at least `Q2_0`". That does not work: `gguf-py` has no `GGMLQuantizationType` member for type 42, so -`GGMLQuantizationType(42)` raises `ValueError`. Verified in round 39 and again here. - -`src/artifact/` needs a writer regardless - P1.S2 requires a reader with no ggml dependency, and the -writer is its companion - so this is that writer in Python, where it can be validated immediately -against `tools/gguf_reader.py` and against llama.cpp. - -Scope: enough to build the P1.S1 tiny model. It is NOT a general-purpose quantizer; the only -quantizer implemented is `Q2_0`, and its contract is `docs/q2_0-contract.md`: - block = 64 elements, fp16 scale, 16 bytes of 2-bit codes, LSB-first, 4 codes per byte - d = amax, code = clamp(round(w/d) + 1, 0, 3), symbol = code - 1 -> {-1, 0, +1, +2} - -Self-checking: `python tools/gguf_writer.py` writes a synthetic v3 file, reads it back with -`gguf_reader.py`, and asserts the tensors and metadata survived byte-exactly. -""" -from __future__ import annotations - -import dataclasses -import pathlib -import struct -import sys - -import numpy as np - -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from gguf_reader import GGUF_MAGIC, GGUFFile # noqa: E402 - -# ggml_type ids we can write. Values match GGML_TYPES in gguf_reader.py. -TYPE_IDS = {"F32": 0, "F16": 1, "Q2_0": 42} -DEFAULT_ALIGNMENT = 32 - -_META_IDS = {"u8": 0, "i8": 1, "u16": 2, "i16": 3, "u32": 4, "i32": 5, "f32": 6, - "bool": 7, "string": 8, "array": 9, "u64": 10, "i64": 11, "f64": 12} - - -# ------------------------------------------------------------------ Q2_0, per docs/q2_0-contract.md -def quantize_q2_0(w: np.ndarray) -> bytes: - """(n,) float32 -> concatenated 18-byte blocks. n must be a multiple of 64.""" - w = np.asarray(w, dtype=np.float32).reshape(-1) - if w.size % 64: - raise ValueError(f"Q2_0 needs a multiple of 64 elements, got {w.size}") - blocks = w.reshape(-1, 64) - out = bytearray() - for b in blocks: - amax = float(np.max(np.abs(b))) - d = amax - # d = amax (NOT amax/2) - the grid is asymmetric, symbols land in {-1,0,+1,+2}. - code = np.zeros(64, dtype=np.uint8) if d == 0 else \ - np.clip(np.rint(b / d).astype(np.int32) + 1, 0, 3).astype(np.uint8) - packed = np.zeros(16, dtype=np.uint8) - # j -> byte j//4, bit (j%4)*2 ; four codes per byte, least significant first. - for j in range(64): - packed[j // 4] |= np.uint8(code[j] << ((j % 4) * 2)) - out += struct.pack(" np.ndarray: - """Inverse of the above, for the round-trip check. Mirrors `dequantize_row_q2_0`.""" - nblocks = len(raw) // 18 - out = np.empty(nblocks * 64, dtype=np.float32) - for i in range(nblocks): - d = struct.unpack_from("> ((j % 4) * 2)) & 0x03 - out[i * 64 + j] = (c - 1) * d - return out - - -# ------------------------------------------------------------------ writer -@dataclasses.dataclass -class _Tensor: - name: str - shape: list[int] # GGUF order: dim 0 varies fastest - type_name: str - data: bytes - - -class GGUFWriter: - def __init__(self, alignment: int = DEFAULT_ALIGNMENT): - self.alignment = alignment - self.metadata: dict[str, tuple[str, object]] = {} - self.tensors: list[_Tensor] = [] - - # ---- metadata - def add(self, key: str, value, type_name: str | None = None) -> None: - if type_name is None: - type_name = {bool: "bool", int: "i64", float: "f64", str: "string"}.get(type(value)) - if type_name is None: - if isinstance(value, list) and value: - elem = {bool: "bool", int: "i32", float: "f32", str: "string"}.get(type(value[0])) - if elem is None: - raise TypeError(f"unsupported array element {type(value[0])} for {key}") - type_name = "array:" + elem - else: - raise TypeError(f"cannot infer a GGUF type for {key}") - self.metadata[key] = (type_name, value) - - # ---- tensors - def add_f32(self, name: str, arr: np.ndarray) -> None: - a = np.ascontiguousarray(arr, dtype=" None: - """`arr` is (rows, in_features) row-major with every row `shape[0]` long; `shape` is the FULL - GGUF shape. The shape must be passed explicitly, not inferred as [in, rows]: a fused expert - tensor is [in, out, experts], and inferring 2-D produced `[64, 4096]` where llama.cpp expects - `[64, 256, 16]`. Q2_0 blocks run along dim 0 only, so the extra axes are just a layout. - """ - a = np.asarray(arr, dtype=np.float32) - in_features = shape[0] - if a.ndim != 2 or a.shape[1] != in_features: - raise ValueError(f"{name}: expected (rows, {in_features}), got {a.shape}") - if a.shape[0] * in_features != int(np.prod(shape)): - raise ValueError(f"{name}: {a.shape} does not cover shape {shape}") - per_row = quantize_q2_0(a.reshape(-1)) # row-major: row 0 first - self.tensors.append(_Tensor(name, list(shape), "Q2_0", per_row)) - - # ---- serialisation - def _kv_bytes(self, key: str, type_name: str, value) -> bytes: - out = bytearray() - out += struct.pack(" bytes: - if type_name == "string": - b = v.encode("utf-8") - return struct.pack(" pathlib.Path: - path = pathlib.Path(path) - body = bytearray() - body += struct.pack(" int: - rng = np.random.default_rng(7) - w = GGUFWriter() - w.add("general.architecture", "qwen4exp") - w.add("qwen4exp.block_count", 8, "u32") - w.add("qwen4exp.test.array", [1, 2, 3, 4], "array:i32") - w.add("general.name", "strata tiny") - - A = rng.standard_normal((16, 64)).astype(np.float32) - B = rng.standard_normal((4, 8)).astype(np.float32) - w.add_q2_0("blk.0.ffn_gate_exps.weight", A, 64) - w.add_f32("blk.0.ssm_a", B) - - p = pathlib.Path(__file__).resolve().parent.parent / "bench" / "tiny-selftest.gguf" - w.write(p) - print(f"wrote {p.name} ({p.stat().st_size} B)") - - g = GGUFFile(p) - ok = True - print(f" version {g.version} tensors {len(g.tensors)} metadata {len(g.metadata)}") - if g.metadata.get("general.architecture") != "qwen4exp": print(" FAIL arch"); ok = False - if g.metadata.get("qwen4exp.block_count") != 8: print(" FAIL u32"); ok = False - if g.metadata.get("qwen4exp.test.array") != [1, 2, 3, 4]: print(" FAIL array"); ok = False - - by = {t.name: t for t in g.tensors} - t = by.get("blk.0.ffn_gate_exps.weight") - if t is None or t.type_name != "Q2_0" or t.shape != [64, 16]: - print(f" FAIL tensor dir: {t}"); ok = False - else: - with p.open("rb") as fh: - fh.seek(g.data_start + t.offset) - raw = fh.read(16 * 18) - back = dequantize_q2_0(raw) - err = np.abs(back - A.reshape(-1)).max() - rel = float(np.abs(back - A.reshape(-1)).mean() / np.abs(A).mean()) - print(f" Q2_0 round trip: max abs {err:.4f} mean rel {rel*100:.2f}% " - f"(quantization error, not a write bug)") - # The real check: re-quantizing the DEQUANTIZED values must be a fixed point. - again = dequantize_q2_0(quantize_q2_0(back)) - if not np.array_equal(again, back): - print(" FAIL Q2_0 is not a fixed point under requantization"); ok = False - else: - print(" Q2_0 fixed point: PASS (requantizing the dequantized values is exact)") - print("SELF-CHECK " + ("PASS" if ok else "FAIL")) - return 0 if ok else 1 - - -if __name__ == "__main__": - raise SystemExit(_selfcheck()) diff --git a/tools/iq_fixture.py b/tools/iq_fixture.py deleted file mode 100644 index 8cfcf92..0000000 --- a/tools/iq_fixture.py +++ /dev/null @@ -1,137 +0,0 @@ -"""tools/iq_fixture.py - deterministic i-quant fixtures for src/kernels/iq_parity.cpp (TODO 24). - -For each of the ten types iq_parity tests, writes `/.bin` (int32 header: the KERNEL type id, -rows, cols - then the raw GGUF block bytes) and `/.f32` (rows*cols float32 reference values, -dequantized by the same library the comparison treats as ground truth): - - python tools/iq_fixture.py --out build/iq_fixture - python tools/iq_fixture.py --out build/iq_fixture --seed 7 --rows 32 --cols 256 - -Generation is deterministic: an explicit seed and fixed dimensions, and every random choice comes from -numpy's RandomState under that seed. The blocks are synthetic on purpose: the i-quant formats have no -published quantizer in gguf-py (it dequantizes only), so each block combines sane half-precision scales -(written at the layout's scale offsets, see SCALE_OFFSETS below) with seeded index/sub-scale bytes - the -dequantized reference covers real codebook values either way, which is what the parity compares. - -Dependencies: python3 and numpy, plus the repository's VENDORED gguf-py (third_party/llama.cpp/gguf-py - -no pip install; it is put on sys.path relative to this file). Q2_0 is this repository's own format -(GGML type 42, which gguf-py does not carry): its codec comes from tools/gguf_writer.py. - -The kernel ids in the .bin headers are the repo's i-quant dispatch table (iq_kernels.cu is_iq / -iq_row_bytes) and match the vendored gguf-py's enum ids one for one - the layout table below is the -same GGML_QUANT_SIZES both sides compile in. -""" -from __future__ import annotations - -import argparse -import struct -import sys -from pathlib import Path - -import numpy as np - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "third_party" / "llama.cpp" / "gguf-py")) -sys.path.insert(0, str(ROOT / "tools")) - -try: - import gguf - from gguf.quants import dequantize as gguf_dequantize - from gguf_writer import dequantize_q2_0, quantize_q2_0 -except ImportError as e: # a missing numpy or vendored gguf-py must be explicit, not a traceback - sys.stderr.write(f"iq_fixture: missing dependency: {e}\n" - "numpy and the repository's vendored gguf-py (third_party/llama.cpp/gguf-py) are " - "required. The vendored copy comes with setup's llama.cpp download (the pinned " - "LLAMA_CPP_COMMIT zip); on a fresh checkout run setup once, or fetch that zip and " - "unpack its gguf-py there.\n") - sys.exit(3) - -QT = gguf.GGMLQuantizationType -# name -> (block values, block bytes, the fp16 scale offsets inside a block). The layouts mirror -# gguf-py's dequantize_blocks implementations: every one of these formats keeps its half-precision -# scale(s) at fixed offsets (IQ*_X*: offset 0; Q3_K: after the 32-byte hmask, 64-byte qs and the -# 12 scale bytes) - the rest of the block is indices and sub-scales, which are seeded random bytes. -LAYOUT = { # (block values, block bytes) == the vendored gguf-py's GGML_QUANT_SIZES == the kernels' sizes - "IQ2_XXS": (256, 66), - "IQ2_XS": (256, 74), - "IQ2_S": (256, 82), - "IQ3_XXS": (256, 98), - "IQ3_S": (256, 110), - "IQ1_M": (256, 56), - "IQ4_NL": (32, 18), - "IQ4_XS": (256, 136), - "Q3_K": (256, 110), -} -HALF_ONE = struct.pack(" None: - """Overwrite the fp16 scale bits of every block with a sane value, in place. The index and - sub-scale bytes stay seeded-random (their values are bounded by construction). Layouts mirror - gguf-py's dequantize_blocks: IQ*_X* and IQ4_* keep the fp16 scale at block offset 0; Q3_K keeps - it after the 32-byte hmask, 64-byte qs and 12 scale bytes; IQ1_M is "the only one which stores - the f16 scale in multiple parts" - the fp16 bits are the HIGH NIBBLES of the four uint16s at - bytes 48..56, so a 1.0 scale is nibbles 3, C, 0, 0 on bytes 49, 51, 54, 55.""" - if name == "Q3_K": - raw[:, 108:110] = np.frombuffer(HALF_ONE, dtype=np.uint8) - return - if name == "IQ1_M": - raw[:, 48:56] &= np.uint8(0x0F) # clear the four scale nibbles - for byte, nib in ((49, 0x30), (51, 0xC0), (54, 0x00), (55, 0x00)): - raw[:, byte] |= np.uint8(nib) - return - raw[:, 0:2] = np.frombuffer(HALF_ONE, dtype=np.uint8) -# name -> (the KERNEL type id written into the .bin header, identical to the gguf-py enum id) -KERNEL_IDS = {"IQ2_XXS": 16, "IQ2_XS": 17, "IQ2_S": 22, "IQ3_XXS": 18, "IQ3_S": 21, - "IQ1_M": 29, "IQ4_NL": 20, "IQ4_XS": 23, "Q2_0": 42, "Q3_K": 11} - - -def build(name: str, rows: int, cols: int, seed: int): - """The .bin body (header + raw blocks) and the .f32 reference for one type.""" - kernel_type = KERNEL_IDS[name] - n = rows * cols - rng = np.random.RandomState((seed, hash(name) & 0xFFFF) if False else (seed, KERNEL_IDS[name])) - if name == "Q2_0": # the repository's own codec, gguf-py has no type 42 - w = rng.standard_normal(n).astype(np.float32) - raw = np.frombuffer(quantize_q2_0(w), dtype=np.uint8) - ref = dequantize_q2_0(raw.tobytes()).astype(np.float32) - flat = raw - else: - block_values, block_bytes = LAYOUT[name] - blocks = n // block_values - raw = rng.randint(0, 256, (blocks, block_bytes), dtype=np.uint8) - repair_scales(name, raw) # sane fp16 scales; indices stay seeded-random - flat = raw.reshape(-1) - ref = np.asarray(gguf_dequantize(flat, getattr(QT, name)), dtype=np.float32) - if not np.isfinite(ref).all() or float(np.abs(ref).max()) > 1e4: - raise RuntimeError(f"{name}: the dequantized reference is not finite/tame - the layout table " - f"(block bytes, scale offsets) does not match gguf-py's dequantizer") - header = struct.pack("<3i", kernel_type, rows, cols) - return header + flat.tobytes(), ref - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], - formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--out", default="logs/iq_fixture", help="the fixture directory (created; may live in the " - "build directory - the source tree is not written)") - ap.add_argument("--seed", type=int, default=7, help="the fixture RNG seed (deterministic generation)") - ap.add_argument("--rows", type=int, default=32, help="weight rows (rows*cols stays a multiple of 256)") - ap.add_argument("--cols", type=int, default=256, help="the reduction dimension, a multiple of 256") - args = ap.parse_args() - if args.cols % 256 or args.rows * args.cols % 256: - ap.error("--cols must be a multiple of 256 and rows*cols a multiple of 256") - out = Path(args.out) - out.mkdir(parents=True, exist_ok=True) - for name in KERNEL_IDS: - blob, ref = build(name, args.rows, args.cols, args.seed) - (out / f"{name}.bin").write_bytes(blob) - (out / f"{name}.f32").write_bytes(np.ascontiguousarray(ref, dtype="2} {args.rows} x {args.cols} " - f"{len(blob) - 12} block bytes, {ref.size} reference floats") - print(f"iq_fixture: {len(KERNEL_IDS)} fixtures in {out} (seed {args.seed})") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/iq_pack.py b/tools/iq_pack.py deleted file mode 100644 index 9dbd939..0000000 --- a/tools/iq_pack.py +++ /dev/null @@ -1,763 +0,0 @@ -"""tools/iq_pack.py - plan v0.3 P6: a native pack for any of the model files (Q2_0, IQ2_XS, IQ3_XXS). - - python tools/iq_pack.py --gguf -00001-of-00002.gguf --out pack/iq3_xxs (standalone) - python tools/iq_pack.py --gguf -00001-of-00002.gguf --base pack/full --out ... (share dense.bin) - -The i-quant experts cannot be re-expressed in the Q2_0 pack form, so this pack keeps every quantized tensor in -its GGUF form: - - experts.bin optional (--experts-bin): per layer, 512 blobs of [gate rows | up rows | down rows], the - raw GGUF slices. Blob size is per layer (the files mix IQ1_M ... IQ3_S gate/up and Q2_0 / - IQ4_NL down). experts.bin.src.json says which source it was cut from (the shards' names and - sizes, the hash of native_experts.txt); an experts.bin is reused only when that matches. - native_experts.txt one line per layer: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard]; - written last, so a pack without it is not finished - index.txt the table the engine loads. Quantized dense tensors, token_embd and output are served - natively from the GGUF by the engine (--native): their rows carry shape only. - dense.bin standalone: the BF16/F16/F32 tensors in the form the engine reads them (index kinds 4/5/2; - 3 = F32 narrowed to F16 by the loader) - as the GGUF stores them, or converted (FORM below). - conversions.json every tensor that was converted: shard, source/destination type, method, whether it was - exact, the largest absolute error, the source bytes' sha256 (schema 1). - With --base: the base (Q2_0) pack's dense.bin, hard-linked - the float tensors are - byte-identical in all three model files (checked) - plus extra.bin for tensors that are - float here but quantized in the base pack (blk.1.ple_key). - tokenizer/ exported from the GGUF (tools/strata_tokenizer.py), with the model's chat template. - -Split files: every shard of the model is read (-0000N-of-0000M.gguf beside --gguf; a missing shard is an -error), so the layers may be split anyhow (Swift 1.5's GGUFs put layers 13-47 in shard 2 and the PLE table in -shard 1). A layer whose experts are not in shard 1 names its shard in native_experts.txt (v3). A shard boundary -may even fall inside a layer (Unsloth's UD-Q4_K_XL: layer 11's down in shard 2, its gate and up in shard 3): that -layer's shard column is per role, `gate,up,down` (an empty field = the --gguf shard), and only then is the file -v4, so an older engine refuses it instead of misreading it. Every other pack stays v3, byte for byte. Router -tensors stored as F32 whose values are exactly BF16 (Swift 1.5) are written as BF16, the form the engine's router -takes (so are the other F32 tensors the engine reads as BF16, when exact); anything else is refused. - -For ordinary quants, --compat-bf16 dequantizes the small projections that the engine reads as BF16, using -round-to-nearest-even. This introduces BF16 rounding; it does not reconstruct the original full-precision -weights. Experts, native attention projections, token embeddings, a Q2_0/Q8_0 PLE key and the disk-backed PLE -table stay unchanged. - -Qwen3.6-35B-A3B (`general.architecture` qwen35moe; docs/qwen36-port/step4-pack.md) is a second FORM table, not a -rewrite of Flash-Next's: the routers, `ssm_alpha`, `ssm_beta` and the 1-D shared-expert gate are F32 in the shipped -files with every value exactly BF16, so they are written as BF16 under the exact rule above (no --compat-bf16); the -norms, `ssm_a`, `ssm_dt.bias` and `ssm_conv1d` are F32 and copied; every projection (`attn_qkv`, `attn_gate`, -`ssm_out`, `attn_q/k/v/output`, `ffn_*_shexp`, `output`, `token_embd`) is served natively from the GGUF and must -be of a type the engine's native path has a kernel for (NATIVE_PROJECTION_TYPES below) - any other is refused by -name. The draft block of a -MTP file (`blk.40` and up, `nextn_predict_layers`) belongs to the drafter's pack and is -left out of index.txt, dense.bin and native_experts.txt alike. `expert-profile.bin` (the expert cache's ranking, -tools/make_profile.py) is copied in from --expert-profile when its header matches the trunk's layers x experts. -""" -from __future__ import annotations - -import argparse -import hashlib -import json -import os -import pathlib -import re -import shutil -import subprocess -import sys - -import numpy as np - -HERE = pathlib.Path(__file__).resolve().parent -sys.path.insert(0, str(HERE)) -import gguf_reader as G # noqa: E402 - -FLOAT = {"BF16", "F32", "F16"} -ROUTERS = ("ffn_gate_inp.weight", "ffn_gate_inp_shexp.weight") -NOT_IN_PACK = {"per_layer_token_embd.weight"} # the 28.8 GB PLE table: read from its GGUF by the engine - -# The float form the engine reads each pack tensor in (name without `blk.N.`; from eddoursul/Strata's FORM table). -# The residual, router, GDN, QSA and PLE kernels read these small projections as BF16, the norms as F32 and the PLE -# conv as F16. GSQ-RCO files already store them that way; other files do not (Unsloth's UD-Q4_K_XL: the routers, -# SSM gates and injections F32, the hyper-connection projections and the PLE value Q8_0, the PLE conv F32), so a -# tensor stored otherwise is converted, and every conversion is recorded in conversions.json: -# F32 -> BF16 whose values are exactly BF16 (low 16 bits zero) exact, by default -# F32 with other values, F16 or a quantized type -> BF16 rounds (nearest-even): only with --compat-bf16 -# F32 -> F16 (ple_conv1d) index kind 3, narrowed by the loader (#255), -# by default - the kernel reads nothing else -# F16 / BF16 -> F32 exact widening, by default -# Tensors not named here are written as stored (floats) or served from the GGUF (quantized), as before. -FORM = { - "ffn_gate_inp.weight": "BF16", "ffn_gate_inp_shexp.weight": "BF16", - "hc_attn_down.weight": "BF16", "hc_attn_up.weight": "BF16", "hc_attn_inject.weight": "BF16", - "hc_ffn_down.weight": "BF16", "hc_ffn_up.weight": "BF16", "hc_ffn_inject.weight": "BF16", - "output_hc_down.weight": "BF16", "output_hc_up.weight": "BF16", - "indexer.k_proj.weight": "BF16", "indexer.q_proj.weight": "BF16", - "ssm_alpha.weight": "BF16", "ssm_beta.weight": "BF16", - "ple_key.weight": "BF16", "ple_value.weight": "BF16", "ple_conv1d.weight": "F16", - "attn_q_norm.weight": "F32", "attn_k_norm.weight": "F32", "hc_attn_norm.weight": "F32", - "hc_ffn_norm.weight": "F32", "output_hc_norm.weight": "F32", "indexer.q_norm.weight": "F32", - "indexer.k_norm.weight": "F32", "ple_norm_conv.weight": "F32", "ple_norm_key.weight": "F32", - "ple_norm_query.weight": "F32", "ssm_a": "F32", "ssm_conv1d.weight": "F32", "ssm_dt.bias": "F32", - "ssm_norm.weight": "F32", -} -# qwen35moe (Qwen3.6-35B-A3B, docs/QWEN36-35B-A3B.md 3.5, 3.7; docs/qwen36-port/step4-pack.md): the plain residual -# block's norms in place of the hc_* set, no indexer, no PLE. The engine's forms (src/core/layout.cpp `check_one` -# and the kernels behind it): the router and the GDN gate projections BF16 (`moe_route`, `fused_gdn_ab`, the prefill -# `bf16_proj`), the shared expert's 1-D gate BF16 (`shared_expert`), every norm, `ssm_a`, `ssm_dt.bias` and -# `ssm_conv1d` F32 (read as `const float*`). The BF16 ones are F32 in both shipped files with every value exactly -# BF16 (step3-gdn.md's census), so the exact rule writes them without --compat-bf16. -FORM_QWEN35MOE = { - "ffn_gate_inp.weight": "BF16", "ffn_gate_inp_shexp.weight": "BF16", - "ssm_alpha.weight": "BF16", "ssm_beta.weight": "BF16", - "attn_norm.weight": "F32", "post_attention_norm.weight": "F32", "output_norm.weight": "F32", - "attn_q_norm.weight": "F32", "attn_k_norm.weight": "F32", "ssm_norm.weight": "F32", - "ssm_a": "F32", "ssm_dt.bias": "F32", "ssm_conv1d.weight": "F32", -} -FORMS = {"qwen4exp": FORM, "qwen35moe": FORM_QWEN35MOE} -# The qwen35moe tensors the engine serves natively from the GGUF (`NativeDense::load`'s eligible suffixes, the native -# head and the native embedding), and the ggml types each path has a kernel for: `native_mmvq_supported` -# (src/kernels/cuda/native_mmvq.cu) for the projections and the head, `embed_type_supported` (iq_kernels.cu: the -# `is_iq` set plus BF16) for the embedding. A projection of any other type is refused by name: the engine has no -# F32 / F16 GEMV and would refuse the pack at start-up ("this pack holds the tensor only in its GGUF form"). -NATIVE_PROJECTIONS_QWEN35MOE = ( - "attn_qkv.weight", "attn_gate.weight", "ssm_out.weight", # GDN layers - "attn_q.weight", "attn_k.weight", "attn_v.weight", "attn_output.weight", # attention layers - "ffn_gate_shexp.weight", "ffn_up_shexp.weight", "ffn_down_shexp.weight", # the shared expert, every layer -) -NATIVE_PROJECTION_TYPES = {"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"} -NATIVE_EMBED_TYPES = {"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", "BF16"} -# PLE key encodings left in the GGUF for the engine's native PLE key (Q2_0; Q8_0 in UD-Q4_K_XL). Other quantized -# keys take the BF16 path (--compat-bf16), as before. -NATIVE_PLE_KEY = {"Q2_0", "Q8_0"} -KIND = {"BF16": "4", "F16": "5", "F32": "2"} - - -def form_of(name: str, arch: str = "qwen4exp"): - return FORMS.get(arch, FORM).get(re.sub(r"^blk\.\d+\.", "", name)) - - -def needs_bf16(name: str, type_name: str, arch: str = "qwen4exp") -> bool: - """Whether the engine reads `name` as BF16 from the pack (not natively from the GGUF).""" - if name == "blk.1.ple_key.weight" and type_name in NATIVE_PLE_KEY: - return False - return form_of(name, arch) == "BF16" - - -def native_type_problem(name: str, type_name: str, arch: str): - """For a qwen35moe tensor the engine serves from the GGUF: None when its type has a native kernel, else the - refusal (the tensor, its type, the path and the types that path takes).""" - if arch != "qwen35moe": - return None - suffix = re.sub(r"^blk\.\d+\.", "", name) - if name == "token_embd.weight": - path, ok = "native embedding (iq_embed_rows)", NATIVE_EMBED_TYPES - elif name == "output.weight": - path, ok = "native head (native_mmvq)", NATIVE_PROJECTION_TYPES - elif name.startswith("blk.") and suffix in NATIVE_PROJECTIONS_QWEN35MOE: - path, ok = "native projection path (NativeDense, native_mmvq)", NATIVE_PROJECTION_TYPES - else: - return None - if type_name in ok: - return None - return "%s is %s, which the engine's %s has no kernel for; it serves %s" % ( - name, type_name, path, ", ".join(sorted(ok))) - - -def layer_of(name: str) -> int: - """The block index of a `blk.N.` tensor, -1 for any other.""" - m = re.match(r"^blk\.(\d+)\.", name) - return int(m.group(1)) if m else -1 - - -def dequantize(raw: np.ndarray, type_name: str) -> np.ndarray: - """The tensor's values as float32 (float types exactly, quantized ones through gguf-py's dequantizer).""" - if type_name == "F32": - return raw.view(np.float32) - if type_name == "F16": - return raw.view(np.float16).astype(np.float32) - if type_name == "BF16": - return (raw.view(np.uint16).astype(np.uint32) << 16).view(np.float32) - from _paths import add_gguf_py - add_gguf_py() - from gguf import GGMLQuantizationType as Q, quants - return quants.dequantize(raw, Q[type_name]).astype(np.float32).reshape(-1) - - -def bf16_bytes(raw: np.ndarray, type_name: str) -> bytes: - from _paths import add_gguf_py - add_gguf_py() - from gguf import GGMLQuantizationType as Q, quants - values = quants.dequantize(raw, Q[type_name]) - if not np.isfinite(values).all(): - raise ValueError("cannot convert non-finite weights to BF16") - # ggml's round-to-nearest-even conversion, including correct halfway rounding. - return quants.quantize(values, Q.BF16).tobytes() - - -def f16_values(values: np.ndarray, name: str) -> np.ndarray: - """values -> F16, nearest-even (numpy's conversion, which is the engine loader's f16_from_f32); refuses a value - that is not finite or overflows F16.""" - if not np.isfinite(values).all(): - raise ValueError(f"{name}: cannot convert non-finite weights to F16") - with np.errstate(over="ignore"): - h = values.astype(np.float16) - if not np.isfinite(h).all(): - raise ValueError(f"{name}: a value is beyond F16's range, which the engine reads it as") - return h - - -class Model: - """All shards of one model: name -> (GGUFFile, TensorInfo, memmap, shard path).""" - - def __init__(self, first: pathlib.Path): - import re - m = re.search(r"-(\d{5})-of-(\d{5})\.gguf$", first.name) - paths = [first] - if m: - total = int(m.group(2)) - paths = [first.with_name(first.name[:m.start()] + "-%05d-of-%05d.gguf" % (i, total)) - for i in range(1, total + 1)] - missing = [str(p) for p in paths if not p.is_file()] - if missing: - raise FileNotFoundError("missing model shards (wait for the download): " + ", ".join(missing)) - self.paths = paths - self.files = [G.GGUFFile(p) for p in paths] - self.sizes = [p.stat().st_size for p in paths] - check_split(self.files) - self.where = {} - for p, g in zip(paths, self.files): - mm = np.memmap(p, dtype=np.uint8, mode="r") - for t in g.tensors: - size = t.expected_bytes() - if size is None or g.data_start + t.offset + size > mm.size: - raise ValueError(f"{p.name}: unsupported or truncated tensor {t.name}") - if t.name in self.where: - raise ValueError(f"{p.name}: duplicate tensor {t.name}") - self.where[t.name] = (g, t, mm, p) - - def bytes(self, name) -> np.ndarray: - g, t, mm, _ = self.where[name] - return tensor_bytes(mm, g, t) - - -def check_split(files) -> None: - """The split keys, as the engine checks them (strata::GgufModel): shard 1 carries the metadata, and every shard - declares split.count / split.no (and split.tensors.count) consistently - a shard of another model, or a shard - renamed into the family, is refused rather than mixed in.""" - n = len(files) - meta0 = files[0].metadata - if n == 1: - if int(meta0.get("split.count", 1)) > 1: - raise ValueError(f"{files[0].path.name} is shard 1 of {meta0['split.count']}, but its name has no " - "-00001-of-0000N.gguf to find the others by") - return - if "general.architecture" not in meta0: - raise ValueError(f"{files[0].path.name} has no general.architecture; the first shard of a split model " - "carries the metadata") - total = meta0.get("split.tensors.count") - for i, g in enumerate(files): - md = g.metadata - if md.get("split.count") != n or md.get("split.no") != i or \ - (total is not None and md.get("split.tensors.count") != total): - raise ValueError(f"{g.path.name} does not declare itself shard {i + 1} of {n} of this model " - "(split.count / split.no / split.tensors.count)") - if total is not None and sum(len(g.tensors) for g in files) != total: - raise ValueError(f"the {n} shards hold {sum(len(g.tensors) for g in files)} tensors, but " - f"split.tensors.count is {total}") - - -ROLES = ("gate", "up", "down") -N_EXPERT = 512 -ALIGN = 64 - - -def read_index(path: pathlib.Path): - rows, header = {}, [] - for line in path.read_text(encoding="utf-8").splitlines(): - if line.startswith("#"): - header.append(line) - continue - f = line.split() - rows[f[0]] = f - return header, rows - - -def tensor_bytes(mm, g, t) -> np.ndarray: - n = t.expected_bytes() - return mm[g.data_start + t.offset: g.data_start + t.offset + n] - - -def is_expert(name: str) -> bool: - return name.startswith("blk.") and name.endswith(("_exps.weight",)) - - -def convert(name: str, type_name: str, raw: np.ndarray, compat_bf16: bool, arch: str = "qwen4exp"): - """The pack form of one tensor the engine reads from dense.bin: (kind, stored bytes, destination bytes, - record or None), or an error string. `record` describes a conversion for conversions.json.""" - form = form_of(name, arch) - if form is None or form == type_name: - return KIND[type_name], raw.tobytes(), raw.nbytes, None - values = dequantize(raw, type_name) - rec = {"src_type": type_name, "dst_type": form} - if form == "BF16": - u = values.view(np.uint32) if type_name == "F32" else None - inexact = int(np.count_nonzero(u & 0xFFFF)) if u is not None else 0 - if u is not None and not inexact: - if not np.isfinite(values).all(): - return f"{name} is F32 with non-finite values; refused rather than converted" - data = (u >> 16).astype("bf16 round-to-nearest-even (--compat-bf16)" % type_name.lower()) - rec.update(exact=bool(np.array_equal(got, values)), - max_abs_err=float(np.max(np.abs(got.astype(np.float64) - values))) if values.size else 0.0) - return "4", data, len(data), rec - if form == "F16": - if type_name != "F32" and not compat_bf16: - return f"{name} is {type_name}, but the engine reads F16; use --compat-bf16 (rounds to nearest-even)" - h = f16_values(values, name) - err = float(np.max(np.abs(h.astype(np.float64) - values))) if values.size else 0.0 - rec.update(exact=bool(np.array_equal(h.astype(np.float32), values)), max_abs_err=err) - if type_name == "F32": - # The F32 bytes go into dense.bin as index kind 3 and the loader narrows them to F16 (nearest-even), the - # form the PLE conv kernel reads (#255, gopinath87607): 4 B/elem in, 2 B/elem out. - rec.update(method="f32->f16 by the loader (index kind 3, round-to-nearest-even)") - return "3", raw.tobytes(), raw.nbytes // 2, rec - rec.update(method="%s->f16 round-to-nearest-even (--compat-bf16)" % type_name.lower()) - data = h.astype(" str: - return str(model.files[0].metadata.get("general.architecture", "qwen4exp")) - - -def index_standalone(src, out, model: Model, compat_bf16: bool = False, n_trunk: int = -1) -> int: - """Every non-expert tensor of the model: the floats the engine reads from the pack into dense.bin in the form it - reads them (FORM; converted when stored otherwise, see above), quantized ones served natively from the GGUF. - `n_trunk` (a -MTP file's `block_count - nextn_predict_layers`): the draft blocks from `blk.` up are - left out, they are the drafter's pack's; -1 = every block.""" - arch = model_arch(model) - todo, problems, draft = [], [], 0 - for name, (g, t, mm, p) in model.where.items(): - if is_expert(t.name) or t.name in NOT_IN_PACK: - continue - if n_trunk >= 0 and layer_of(name) >= n_trunk: - draft += 1 - continue - if len(t.shape) > 2: - print("tensor %s has %d dimensions; the index holds two" % (t.name, len(t.shape))) - return 1 - # quantized: served from the GGUF unless the engine reads it from the pack (FORM), which takes - # --compat-bf16 to dequantize - except the native PLE key encodings - form = form_of(name, arch) - native = t.type_name not in FLOAT and (form is None or ( - name == "blk.1.ple_key.weight" and t.type_name in NATIVE_PLE_KEY)) - if t.type_name not in FLOAT and not native and not compat_bf16: - problems.append(f"{name} is {t.type_name}, but the engine requires {form}; use --compat-bf16") - # qwen35moe: a projection the engine must serve natively is refused unless its type has a kernel. A float - # projection is refused too: the engine has no F32 / F16 GEMV, and "written as stored" would only move the - # refusal to the engine's start-up - why = native_type_problem(name, t.type_name, arch) - if why is not None: - problems.append(why) - todo.append((name, g, t, mm, p, native)) - if draft: - print("%d tensors of the draft (nextn) block(s) blk.%d and up are left to the drafter's pack" % (draft, n_trunk)) - # refused before anything is written: the previous pack stays as it was - if problems: - for m in problems[:8]: - print(m) - if len(problems) > 8: - print("... and %d more" % (len(problems) - 8)) - return 1 - rows, at = [], 0 - served = 0 - converted, records = [], [] - with open(out / "dense.bin.tmp", "wb") as fo: - for name, g, t, mm, p, native in todo: - ne0 = int(t.shape[0]) - ne1 = int(t.shape[1]) if len(t.shape) > 1 else 0 - if native: - served += 1 - rows.append([t.name, "0", "0", "0", "0", "0", "0", str(ne0), str(ne1), "8", "0", "32"] + ["0"] * 7) - continue - raw = tensor_bytes(mm, g, t) - try: - got = convert(name, t.type_name, raw, compat_bf16, arch) - except ValueError as e: - got = str(e) - if isinstance(got, str): - print(got) - fo.close() - (out / "dense.bin.tmp").unlink(missing_ok=True) - return 1 - kind, data, dst_bytes, rec = got - if rec is not None: - rec = {"name": name, "shard": p.name, **rec, - "source_sha256": hashlib.sha256(raw.tobytes()).hexdigest()} - records.append(rec) - if "--compat-bf16" in rec["method"]: # the rounding the flag allowed - converted.append({"name": name, "source_type": t.type_name, "bytes": len(data)}) - rows.append([t.name, "0", kind, str(at), str(len(data)), "0", str(dst_bytes), str(ne0), str(ne1), - "0", "0", "1"] + ["0"] * 7) - fo.write(data) - pad = (-len(data)) % ALIGN - fo.write(b"\0" * pad) - at += len(data) + pad - write_index(out, rows, src, served, 0, publish=False) - conv = out / "conversions.json.tmp" - conv.write_text(json.dumps({ - "schema": 1, "tool": "tools/iq_pack.py", "compat_bf16": compat_bf16, - "source_shards": [{"name": q.name, "size": s} for q, s in zip(model.paths, model.sizes)], - "tensors": records, - }, indent=1) + "\n", encoding="utf-8") - # published together, and the completion marker (native_experts.txt, written last by main) goes first: a stop - # from here on leaves a pack that setup and the engine see as unfinished, never a new dense.bin under an old - # index or the reverse - (out / "native_experts.txt").unlink(missing_ok=True) - (out / "dense.bin.tmp").replace(out / "dense.bin") - (out / "index.txt.tmp").replace(out / "index.txt") - conv.replace(out / "conversions.json") - if records: - exact = sum(1 for r in records if r["exact"]) - print("conversions.json: %d tensors converted to the engine's form (%d exact, %d rounded; max |err| %.3g)" - % (len(records), exact, len(records) - exact, max(r["max_abs_err"] for r in records))) - for r in records: - if r["dst_type"] == "F16": - print("narrowed to F16 by the loader: %s (%s, index kind 3)" % (r["name"], r["method"])) - if compat_bf16: - (out / "compat-bf16.json").write_text(json.dumps({ - "source": str(src), "rounding": "nearest-even", "tensors": converted, - }, indent=2) + "\n", encoding="utf-8") - print("compat-bf16: %d tensors, %.2f GiB; expert and PLE table bytes unchanged" - % (len(converted), sum(t["bytes"] for t in converted) / 2**30)) - return 0 - - -def write_index(out, rows, src, served, n_extra, publish=True): - at = 0 - for r in rows: - r[5] = str(at) - at += (int(r[6]) + ALIGN - 1) // ALIGN * ALIGN - with open(out / "index.txt.tmp", "w", encoding="utf-8", newline="\n") as fo: - fo.write("# strata pack index v3 -- generated by tools/iq_pack.py (native experts) from %s\n" % src.name) - fo.write("# align %d pool %d tensors %d\n" % (ALIGN, at, len(rows))) - for r in rows: - fo.write(" ".join(r) + "\n") - if publish: - (out / "index.txt.tmp").replace(out / "index.txt") - print("index.txt: %d tensors, %d served natively, %d in extra.bin, arena %.2f GiB" - % (len(rows), served, n_extra, at / 2**30)) - - -def index_from_base(a, src, base, out, g, T, mm) -> int: - base_src = pathlib.Path(json.loads((base / "manifest.json").read_text(encoding="utf-8"))["source"]["shard1"]) - if not base_src.exists(): - print("cannot find the base pack's shard 1 from its manifest.json") - return 1 - bg = G.GGUFFile(base_src) - BT = {t.name: t for t in bg.tensors} - bmm = np.memmap(base_src, dtype=np.uint8, mode="r") - header, rows = read_index(base / "index.txt") - new_rows, extra = [], [] - served = 0 - for name, f in rows.items(): - t, bt = T.get(name), BT.get(name) - if t is None or bt is None: - print("tensor %s missing from one of the models" % name) - return 1 - if t.type_name in FLOAT and bt.type_name in FLOAT: - if t.type_name != bt.type_name or t.shape != bt.shape or \ - not np.array_equal(tensor_bytes(mm, g, t), tensor_bytes(bmm, bg, bt)): - print("float tensor %s differs from the base model; this pack cannot reuse its dense.bin" % name) - return 1 - new_rows.append(list(f)) - elif t.type_name in FLOAT: - if t.type_name != "BF16": - print("unexpected float type %s for %s" % (t.type_name, name)) - return 1 - nbytes = t.expected_bytes() - off = sum(len(b) + (-len(b)) % ALIGN for b in extra) - extra.append(tensor_bytes(mm, g, t).tobytes()) - # file 3 = extra.bin, raw BF16 (index kind 4) - new_rows.append([name, "3", "4", str(off), str(nbytes), "0", str(nbytes), f[7], f[8]] + ["0"] * 10) - else: - served += 1 - new_rows.append([name, f[1], "0", "0", "0", "0", "0", f[7], f[8], "8", "0", "32"] + ["0"] * 7) - write_index(out, new_rows, src, served, len(extra)) - with open(out / "extra.bin", "wb") as fo: - for b in extra: - fo.write(b) - fo.write(b"\0" * ((-len(b)) % ALIGN)) - dense = out / "dense.bin" - if not dense.exists(): - try: - os.link(base / "dense.bin", dense) - except OSError: - shutil.copyfile(base / "dense.bin", dense) - if (base / "tokenizer").exists() and not (out / "tokenizer").exists(): - shutil.copytree(base / "tokenizer", out / "tokenizer") - return 0 - - -def expert_layout(model: Model, src: pathlib.Path): - """The pack's expert table: (layout rows, native_experts.txt text, n_expert, total bytes), or an error string. - Each role is resolved by name in whichever shard holds it, and its offset is absolute in THAT shard: two - shards do not start their data section at the same byte, so one role's data_start must not be used for - another's (per-role data_start as in #255, gopinath87607).""" - T = {n: w[1] for n, w in model.where.items()} - exps = [n for n in T if n.startswith("blk.") and n.endswith("_exps.weight")] - if not exps: - return "the model has no expert tensors (blk.N.ffn_{gate,up,down}_exps.weight)" - fused = sorted(n for n in exps if n.endswith(".ffn_gate_up_exps.weight")) - if fused: - return ("%s: the experts are fused (llama.cpp's gate-then-up form); the engine reads separate " - "ffn_gate_exps / ffn_up_exps / ffn_down_exps tensors" % fused[0]) - n_layers = 1 + max(int(n.split(".")[1]) for n in exps) - # the MTP files (Qwen3.6 -MTP builds, blk.40) carry the draft block as the last block(s): its experts belong - # to the drafter's pack (step 4), not to the trunk's layout, or the engine would route layer 40 of a 40-layer model - meta = model.files[0].metadata - arch = meta.get("general.architecture", "") - nextn = int(meta.get("%s.nextn_predict_layers" % arch, 0) or 0) - if nextn: - n_layers -= nextn - print("%d draft (nextn) block(s) at blk.%d and up are left to the MTP pack; %d trunk layers" % (nextn, n_layers, n_layers)) - n_expert = int(T["blk.0.ffn_gate_inp.weight"].shape[1]) # router rows = experts kept (pruned models ship < 512) - if any(int(T["blk.%d.ffn_gate_inp.weight" % l].shape[1]) != n_expert for l in range(n_layers)): - return "the routers disagree on the expert count; a per-layer pruned model cannot be packed" - layout, lines, offset, n_split = [], [], 0, 0 - for l in range(n_layers): - names = ["blk.%d.ffn_%s_exps.weight" % (l, r) for r in ROLES] - if any(n not in T for n in names): - return "layer %d: missing %s" % (l, ", ".join(n for n in names if n not in T)) - ts = [T[n] for n in names] - if any(t.expected_bytes() is None or len(t.shape) != 3 or int(t.shape[2]) != n_expert for t in ts): - return "layer %d: an expert tensor is not [*, *, %d] of whole blocks" % (l, n_expert) - per = [t.expected_bytes() // n_expert for t in ts] - if per[0] != per[1] or ts[0].type_name != ts[1].type_name: - return "layer %d: gate and up differ in type" % l - blob = per[0] + per[1] + per[2] - layout.append((l, ts[0].type_id, ts[2].type_id, offset, blob, ts)) - ws = [model.where[n] for n in names] - files = ["" if w[3] == src else w[3].name for w in ws] - column = files[0] if len(set(files)) == 1 else ",".join(files) - n_split += len(set(files)) != 1 - line = "%d %d %d %d %d %d %d %d" % (l, ts[0].type_id, ts[2].type_id, offset, blob, - *[w[0].data_start + w[1].offset for w in ws]) - lines.append(line + ("" if not column else " " + column)) - offset += blob * n_expert - if n_split: - head = ("# strata native experts v4: layer gu_type d_type offset blob_bytes gate_off up_off down_off " - "[shard | gate,up,down] (n_expert %d, total %d; absolute offsets in %s, or in the named shard " - "beside it - per role where the column is gate,up,down)\n" % (n_expert, offset, src.name)) - print("%d layer(s) have their gate/up/down in different shards: native_experts.txt v4, per-role shard " - "column for %s" % (n_split, ", ".join(str(l) for l, *_ in layout if "," in lines[l]))) - else: - head = ("# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] " - "(n_expert %d, total %d; absolute offsets in %s, or in the named shard beside it)\n" - % (n_expert, offset, src.name)) - return layout, head + "".join(line + "\n" for line in lines), n_expert, offset - - -def experts_source(model: Model, text: str, total: int) -> dict: - """What experts.bin is cut from: the shards (names and sizes) and the hash of native_experts.txt (every - per-role file and offset, the formats and the blob sizes). A same-size experts.bin of another model or - another packing is not this one.""" - return {"schema": 1, - "shards": [{"name": p.name, "size": s} for p, s in zip(model.paths, model.sizes)], - "native_experts_sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(), - "bytes": total} - - -def read_json(path: pathlib.Path): - try: - return json.loads(path.read_text(encoding="utf-8")) - except (OSError, ValueError): - return None - - -def profile_problem(path: pathlib.Path, n_layers: int, n_expert: int): - """The expert-cache profile's header (tools/make_profile.py, read by `read_expert_profile`) against this model's - trunk: None when it fits, else why not. The engine would refuse it at start-up with the same numbers; checking - here keeps a pack from shipping a ranking for another model.""" - import struct - try: - head = path.read_bytes()[:24] - except OSError as e: - return "%s: %s" % (path, e) - if len(head) < 24 or head[:4] != b"STRP": - return "%s is not a Strata expert profile (no STRP header)" % path - _, nl, ne, slots, n = struct.unpack_from("<5I", head, 4) - if (nl, ne) != (n_layers, n_expert): - return "%s ranks %d x %d (layers x experts), this model's trunk is %d x %d" % (path, nl, ne, n_layers, n_expert) - if n > slots or n > nl * ne: - return "%s: %d ranked pairs in %d slots of %d" % (path, n, slots, nl * ne) - return None - - -def main() -> int: - ap = argparse.ArgumentParser() - ap.add_argument("--gguf", required=True, help="the model's shard 1") - ap.add_argument("--base", help="optional: a Q2_0 canonical pack whose dense.bin holds the shared float tensors") - ap.add_argument("--out", required=True) - ap.add_argument("--skip-experts", action="store_true", help="rewrite the index only") - ap.add_argument("--compat-bf16", action="store_true", - help="dequantize small non-native projections to BF16 for ordinary Qwen4Exp GGUFs " - "(rounds weights; leaves experts and the PLE table unchanged)") - ap.add_argument("--experts-bin", action="store_true", - help="also write experts.bin (the engine otherwise reads the experts from the GGUF itself)") - ap.add_argument("--layout-only", action="store_true", - help="write native_experts.txt alone (the per-layer expert formats, blob sizes and offsets) and " - "print the census: the pack-side check of a model file, nothing else is written") - ap.add_argument("--expert-profile", metavar="PROFILE.bin", - help="the expert cache's ranking (tools/make_profile.py) to ship as /expert-profile.bin; its " - "header must say this model's trunk layers x experts. Default: data/qwen36-expert-profile.bin " - "for a qwen35moe model when it exists and fits; none otherwise") - a = ap.parse_args() - if a.compat_bf16 and a.base: - ap.error("--compat-bf16 cannot reuse --base dense weights") - # HF snapshot files are symlinks to hash-named blobs. Keep the shard filename for discovery: .absolute(), not - # .resolve(), which would follow the link to the blob and lose the -0000N-of-0000M name. - src = pathlib.Path(a.gguf).absolute() - base = pathlib.Path(a.base).resolve() if a.base else None - out = pathlib.Path(a.out) - out.mkdir(parents=True, exist_ok=True) - - g = G.GGUFFile(src) - mm = np.memmap(src, dtype=np.uint8, mode="r") - model = Model(src) - if len(model.paths) > 1: - print("model shards: " + ", ".join(p.name for p in model.paths)) - # ---- the expert table first: a model that cannot be packed is refused before any file of the pack changes - got = expert_layout(model, src) - if isinstance(got, str): - print(got) - return 1 - layout, text, n_expert, offset = got - n_trunk = len(layout) - arch = model_arch(model) - # the expert cache's ranking: checked against the trunk before anything is written, copied in after the index - profile = pathlib.Path(a.expert_profile) if a.expert_profile else None - if profile is None and arch == "qwen35moe": - default = HERE.parent / "data" / "qwen36-expert-profile.bin" - if default.is_file() and profile_problem(default, n_trunk, n_expert) is None: - profile = default - if profile is not None: - why = profile_problem(profile, n_trunk, n_expert) - if why: - print(why) - return 1 - if a.layout_only: - (out / "native_experts.txt").write_text(text, encoding="utf-8") - kinds = {} - for l, gt, dt, off, blob, ts in layout: - kinds.setdefault((ts[0].type_name, ts[2].type_name, blob), []).append(l) - print("%s: %d layers x %d experts, %.0f MiB of experts, mean blob %.3f MiB, largest %.3f MiB" % ( - src.name, len(layout), n_expert, offset / 2 ** 20, offset / n_expert / len(layout) / 2 ** 20, - max(b for *_, b, _ in layout) / 2 ** 20)) - for (gu, dn, blob), ls in sorted(kinds.items(), key=lambda kv: kv[1][0]): - print(" gate/up %-8s down %-8s blob %9d B: %s" % (gu, dn, blob, - "layers %s" % ls if len(ls) <= 8 else "%d layers" % len(ls))) - print("wrote %s" % (out / "native_experts.txt")) - return 0 - path = out / "experts.bin" - sidecar = out / "experts.bin.src.json" - want = experts_source(model, text, offset) - reuse = path.exists() and path.stat().st_size == offset and read_json(sidecar) == want - - def layer_blobs(blob, ts): - chunk = np.concatenate([model.bytes(t.name).reshape(n_expert, -1) for t in ts], axis=1) - assert chunk.shape == (n_expert, blob) # (n_expert, blob): gate | up | down per expert - return chunk - - if reuse: - # the sidecar names the shards by name and size, which a re-quantized or fine-tuned checkpoint of the same - # geometry packed into the same folder can share: compare the first and last blobs of the first, middle and - # last layers with the GGUF too (six blobs, so an unchanged pack is still reused at once) - with open(path, "rb") as f: - for l, gt, dt, off, blob, ts in (layout[0], layout[len(layout) // 2], layout[-1]): - for e in (0, n_expert - 1): - f.seek(off + e * blob) - want_blob = b"".join(model.bytes(t.name).reshape(n_expert, -1)[e].tobytes() for t in ts) - if f.read(blob) != want_blob: - reuse = False - if not reuse: - print("%s matches %s but not this GGUF's expert blobs" % (path, sidecar.name)) - if path.exists() and not reuse and not a.experts_bin: - if sidecar.exists(): - print("%s was cut from another source than this model (%s): the engine would read it instead of " - "the GGUF. Delete it, or rerun with --experts-bin to rewrite it." % (path, sidecar.name)) - return 1 - print("warning: %s has no %s, so nothing says it belongs to this model; the engine reads it instead of " - "the GGUF (rerun with --experts-bin to rewrite it)" % (path, sidecar.name)) - if a.base: - if any(w[3] != src for w in model.where.values() if not w[1].name in NOT_IN_PACK): - print("--base needs a model whose tensors are all in shard 1") - return 1 - (out / "native_experts.txt").unlink(missing_ok=True) - rc = index_from_base(a, src, base, out, g, {t.name: t for t in g.tensors}, mm) - else: - rc = index_standalone(src, out, model, a.compat_bf16, n_trunk) - if rc: - return rc - if not (out / "tokenizer" / "vocab.json").exists() or not (out / "tokenizer" / "chat_template.jinja").exists(): - subprocess.run([sys.executable, str(HERE / "strata_tokenizer.py"), "--gguf", str(src), "--out", str(out)], - check=True) # writes /tokenizer/ - if profile is not None: - tmp_prof = out / "expert-profile.bin.tmp" - shutil.copyfile(profile, tmp_prof) - tmp_prof.replace(out / "expert-profile.bin") - print("expert-profile.bin: %s (%d x %d)" % (profile, n_trunk, n_expert)) - elif arch == "qwen35moe": - print("no expert profile shipped (--expert-profile): the engine's --expert-profile needs one of %d x %d" - % (n_trunk, n_expert)) - - # ---- the experts. native_experts.txt is written to a temporary name and renamed only when every layer is - # in: a stop part-way (a layer split across shards, #171) left a partial native_experts.txt that the next setup - # run took as a finished pack (#172). It is the pack's completion marker, so it is published last. - tmp = out / "native_experts.txt.tmp" - with open(tmp, "w", encoding="utf-8", newline="\n") as fo: - fo.write(text) - tmp.replace(out / "native_experts.txt") - if a.skip_experts or not a.experts_bin: - if path.exists() and not a.experts_bin: - print("note: %s/experts.bin exists; the engine reads it instead of the GGUF" % out) - return 0 - if reuse: - print("experts.bin was cut from this model's shards (%s); not rewritten" % sidecar.name) - return 0 - # written under a temporary name and renamed when complete, then the sidecar: an interrupted write leaves no - # experts.bin, and an experts.bin without its sidecar is never reused - sidecar.unlink(missing_ok=True) - part = out / "experts.bin.tmp" - with open(part, "wb") as fo: - for l, gt, dt, off, blob, ts in layout: - fo.write(layer_blobs(blob, ts).tobytes()) - if l % 8 == 0: - print(" layer %2d %-8s/%-7s blob %8d at %.2f GiB" % (l, ts[0].type_name, ts[2].type_name, blob, - off / 2**30), flush=True) - part.replace(path) - side_tmp = out / "experts.bin.src.json.tmp" - side_tmp.write_text(json.dumps(want, indent=2) + "\n", encoding="utf-8") - side_tmp.replace(sidecar) - print("experts.bin: %d layers, %.2f GiB" % (len(layout), offset / 2**30)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/make_profile.py b/tools/make_profile.py deleted file mode 100644 index 359cfe5..0000000 --- a/tools/make_profile.py +++ /dev/null @@ -1,176 +0,0 @@ -"""tools/make_profile.py - the expert-cache profile (`data/expert-profile.bin`): every (layer, expert) pair, ranked. - -`--expert-cache auto` fills the VRAM slots it can afford with the profile's pairs in order, so the ranking decides -which experts start resident (the adaptive tier then swaps in what a conversation routes most). A profile that -ranks fewer pairs than a card can hold caps the cache (issue #46: a 32 GB card stopped at 8,000 slots); this tool -writes one that ranks all 24,576. - -The order: the base profile's ranking (default: the shipped data/expert-profile.bin), then the pairs your routing -traces used, most frequent first, then every pair still missing, interleaved across the layers. The base is only -*appended to*, never reordered - and the shipped profile already ranks all 24,576 pairs, so with it a trace is a -no-op. `--reorder` ranks the traces first and lets the base fill the rest, which is how a workload's trace decides -the top; `--no-base` drops the base entirely. - - python tools/make_profile.py [TRACE ...] [--base data/expert-profile.bin | --no-base] [--reorder] [--out PATH] - [--n-expert 256] (a pruned model: GSQ-RCO Coder keeps 256 of 512) - [--n-layer 40] (Qwen3.6-35B-A3B: 40 trunk layers x 256 experts) - [--text-trace routes.txt ...] - -A routing trace comes from a one-shot engine run with `--dump-routing FILE` (a prompt typical of your use; the -routed experts of every layer and position are written). Point the model config's `--expert-profile` at the result. - -The layer count: `--n-layer` (default 48, Flash-Next's); with `--base`, the base profile's header decides and a -differing `--n-layer` is an error. `--text-trace` reads llama.cpp eval-callback route traces (one line per token -per layer, ` ... `, `#` lines skipped, `.gz` accepted): the Qwen3.6 E0 trace of -regina/analysis/qwen36-35b-single-gpu-ladder/routes/ is that format. -""" -import argparse -import gzip -import struct -from collections import defaultdict -from pathlib import Path - -ROOT = Path(__file__).resolve().parent.parent -N_LAYER, N_EXPERT = 48, 512 -MAGIC, VERSION = b"STRP", 1 - - -def profile_header(path): - """(version, n_layer, n_expert, slots, n_ranked) of a profile file.""" - blob = Path(path).read_bytes()[:24] - if blob[:4] != MAGIC or len(blob) < 24: - raise SystemExit(f"{path}: not a Strata profile") - return struct.unpack_from("<5I", blob, 4) - - -def read_profile(path, n_expert=N_EXPERT, n_layer=N_LAYER): - blob = Path(path).read_bytes() - if blob[:4] != MAGIC: - raise SystemExit(f"{path}: not a Strata profile") - ver, nl, ne, slots, n = struct.unpack_from("<5I", blob, 4) - if (nl, ne) != (n_layer, n_expert): - raise SystemExit(f"{path}: {nl}x{ne}, not {n_layer}x{n_expert}") - return [struct.unpack_from(" ... ` per token per layer; `#` headers skipped. - A line whose layer or expert is out of range, or that is not integers, is an error (a trace of another model - would otherwise rank a plausible subset of this one's pairs).""" - freq = defaultdict(int) - opener = gzip.open if str(path).endswith(".gz") else open - with opener(path, "rt", encoding="utf-8") as f: - for n, line in enumerate(f, 1): - if not line.strip() or line.startswith("#"): - continue - try: - ids = [int(x) for x in line.split()] - except ValueError: - raise SystemExit(f"{path}:{n}: not a route line: {line.rstrip()!r}") - layer, experts = ids[0], ids[1:] - if not experts or not 0 <= layer < n_layer or any(not 0 <= e < n_expert for e in experts): - raise SystemExit(f"{path}:{n}: layer {layer} / experts {experts} outside {n_layer} x {n_expert}") - for e in experts: - freq[(layer, e)] += 1 - return freq - - -def write_profile(path, ranked, n_expert=N_EXPERT, n_layer=N_LAYER): - table = [[-1] * n_expert for _ in range(n_layer)] - for slot, (layer, e) in enumerate(ranked): - table[layer][e] = slot - with open(path, "wb") as f: - f.write(MAGIC + struct.pack("<5I", VERSION, n_layer, n_expert, len(ranked), len(ranked))) - for layer, e in ranked: - f.write(struct.pack(" dtype, shape, byte range) -at the start of each shard, so HTTP range requests can read the headers and then only the MTP tensors. - - python tools/mtp_fetch.py inventory --out DIR # headers only (a few KB per shard) - python tools/mtp_fetch.py fetch --out DIR [--only SUBSTR] # the MTP tensors themselves, resumable - python tools/mtp_fetch.py verify --out DIR # the fetched tensors against SHA256 (exit 3: bad ones) - -`fetch` writes one raw file per tensor plus `mtp-manifest.json` (dtype, shape, source shard, byte range, -sha256). It never downloads anything but the ranges named in the headers. Nothing here runs a model. - -#327: a mirror or proxy that ignores the Range header answers 200 with the whole shard - its JSON header and -unrelated tensors - and a proxy may cut that to the requested length, so neither the size nor a hash of what was -downloaded catches it (the drafter then accepts nothing, silently). A range read therefore needs a 206 whose -Content-Range is the range asked for, and every tensor of the pinned revision is checked against SHA256 below. -""" -import argparse -import hashlib -import json -import os -import struct -import sys -import time -import urllib.error -import urllib.request - -# #214: a fixed commit of the checkpoint (its `sha` from https://huggingface.co/api/models/Qwen/Qwen3.8-Flash-Next -# on 2026-09-30), so every install reads the same tensors; STRATA_MTP_REVISION overrides it (e.g. main). When the -# repository no longer has it, the current files are read instead, with a message (resolve_repo). -PINNED_REVISION = "de4b8e4d43b917e7706784d8bb445c9af86a3540" -REVISION = os.environ.get("STRATA_MTP_REVISION") or PINNED_REVISION -# #495: HF_ENDPOINT (a mirror, e.g. https://hf-mirror.com) serves the same revision; the SHA256 checks below still apply -HF_ENDPOINT = (os.environ.get("HF_ENDPOINT") or "").strip().rstrip("/") or "https://huggingface.co" -REPO = HF_ENDPOINT + "/Qwen/Qwen3.8-Flash-Next/resolve/%s/" % REVISION -PINNED = HF_ENDPOINT + "/Qwen/Qwen3.8-Flash-Next/resolve/%s/" % PINNED_REVISION # SHA256's revision -DTYPE_BYTES = {"BF16": 2, "F16": 2, "F32": 4, "F8_E4M3": 1, "I64": 8, "I32": 4} -BAD = 3 # `verify`'s exit code: a tensor is missing or corrupt - -# #327: sha256 of every MTP tensor's bytes at PINNED_REVISION (two independent fetches agree, and 29 of them were read -# again from that revision; the two expert tensors' first and last 16 MiB), so a mirror that ignored the -# Range header (it sent the shard's start: its JSON header) is caught, and an install it corrupted is fetched again. -SHA256 = { - "mtp.fc_embedding.weight": - "241d6e87ded317a61b1aeb3ca4e28c53f1caba09ad5be66092e91fe5e3e14751", - "mtp.fc_hidden.weight": - "97c8e427ad0177e2c713ed24a397d815b523eda15ef453f1ae6463f6c70a8f96", - "mtp.hyper_connection_mixer.hc_norm.weight": - "ce948a398e15aeaa403c424cda34e6eed296ab2570d591bb5ff3da642b255d64", - "mtp.hyper_connection_mixer.input_mix_weight_down.weight": - "c633d2841fda463e82045e0b93fb8cb8d511ec0c9eda616020f01aca18d71947", - "mtp.hyper_connection_mixer.input_mix_weight_up.weight": - "6565285f0ba2923703252763cfc11d8a9bda40ab42e7548e12464b04dbdbec13", - "mtp.layers.0.attn_hyper_connection.block_inject_weight.weight": - "c8afff64e7f54412d02120097c4255033c55245e1c1eed84cc630d428ccb864c", - "mtp.layers.0.attn_hyper_connection.hc_norm.weight": - "1fb619aeaaf637ccd70f46f1f8f8116e6a46448cb43026b246de8ee8286ed809", - "mtp.layers.0.attn_hyper_connection.input_mix_weight_down.weight": - "e80ac8bf3e270e9d5a949ec7c913329dc8de017d69851334820fae7b8c86a7f5", - "mtp.layers.0.attn_hyper_connection.input_mix_weight_up.weight": - "f80f1fd44e1183e7764ea496b11ff89ead9dd758f861d4e79a770bf54956b1a5", - "mtp.layers.0.mlp.experts.down_proj": - "539c46234f73bac70450f731f40e715f77ac32faf77def0f3f800e58aaabbbc0", - "mtp.layers.0.mlp.experts.gate_up_proj": - "839e98f9642ebc884b178abd2090b6dc8b0bcd81ed92d7f7a08314c6a68f96d5", - "mtp.layers.0.mlp.gate.weight": - "f0d35fa41b360a08bc0c5b1e5766aa42df960291716ee189208b5d2599462c20", - "mtp.layers.0.mlp.shared_expert.down_proj.weight": - "d2ced8c81367cc494599d1a8cdc279c3dd6579b628ded05acd7495e99cee01d8", - "mtp.layers.0.mlp.shared_expert.gate_proj.weight": - "f4a81109165853b3b64f36d809f98094b599763364070f5fa079200e1c386d4c", - "mtp.layers.0.mlp.shared_expert.up_proj.weight": - "172586861eea53efbff10afc43ded5b6e49c83879e9efc01e089c652bbb0a156", - "mtp.layers.0.mlp.shared_expert_gate.weight": - "acdd306d9996d356e4667a16ff63af6fef086fc7f570f1bc00bbe882a2a93f6e", - "mtp.layers.0.mlp_hyper_connection.block_inject_weight.weight": - "c5782dd92b479a1f8ef43d683fe9c917fd9e8fba81f23c1aae8817bfe4b476a6", - "mtp.layers.0.mlp_hyper_connection.hc_norm.weight": - "21a504876b5e7b788301557c68dfb757999430eba36c66ec8ab96a63604dbfd1", - "mtp.layers.0.mlp_hyper_connection.input_mix_weight_down.weight": - "b71240036dea954e034d5ae04e097bcd7ac51cb28a44e4c93d198af3447278a1", - "mtp.layers.0.mlp_hyper_connection.input_mix_weight_up.weight": - "40756866bf2a5e82c28e407f717b6fa07614d593f78e79c7ceb2cd4ffe6dda94", - "mtp.layers.0.self_attn.indexer.index_qk_proj.weight": - "2befafae6e944c1fc651fd73d4d527eb6f138a6c1679065b003128ee3150e859", - "mtp.layers.0.self_attn.indexer.k_layernorm.weight": - "2db621f6a08b4085756fc69d60a4a1bd1d7fbf5d406456d2477075842efaae54", - "mtp.layers.0.self_attn.indexer.q_layernorm.weight": - "afaf59f68e251939970ffdeacad0667dffc657a522bea62cdc44a52816fc49d6", - "mtp.layers.0.self_attn.k_norm.weight": - "8f924b0357cf936e14fc34518205d000e1423aa60626827df81b0804fae8cdfd", - "mtp.layers.0.self_attn.k_proj.weight": - "1a295dc2d6e633e808aeb19e00c97856a1817bbfcc83f5b610e2bfcacfcb8c38", - "mtp.layers.0.self_attn.o_proj.weight": - "9d2fcf0ac6ac19de87f638f710cfd1af6ad14141e75b7d3d5d29fbd06f374219", - "mtp.layers.0.self_attn.q_norm.weight": - "57957aa1e7c5a3ac628bff0ec5522ad55a39b8c0b8bd2d324ae640e3771617ef", - "mtp.layers.0.self_attn.q_proj.weight": - "5220aef3d288f40759f7356af9ef453e5ac0256a38749a9bb803a4e9db58150d", - "mtp.layers.0.self_attn.v_proj.weight": - "39cb12f5424e965fa71fb81db0ee230c701b7b1e0b72c36641fde7e0e41bff41", - "mtp.pre_fc_norm_embedding.weight": - "04c4a570850e06f2d8913da8220d54d4c7f87db6eb6d45480b938e8ba41d6a86", - "mtp.pre_fc_norm_hidden.weight": - "b933b44559879449b1baf2af8385c5c237347307e3fd452394870cb53e6eab6d", -} - - -def get(url, start=None, end=None, retries=4): - for attempt in range(retries): - try: - req = urllib.request.Request(url, headers={"User-Agent": "strata-mtp-fetch"}) - if start is not None: - req.add_header("Range", "bytes=%d-%d" % (start, end)) - with urllib.request.urlopen(req, timeout=120) as r: - if start is not None: - check_range(r.status, r.headers.get("Content-Range"), start, end) - data = r.read() - if start is not None and len(data) != end - start + 1: - raise IOError("short range read: %d of %d" % (len(data), end - start + 1)) - return data - except Exception as e: # network errors are retried, then surfaced - if attempt == retries - 1: - raise - time.sleep(2 ** attempt) - print("retry %s: %s" % (url, e), file=sys.stderr) - - -def check_range(status, content_range, start, end): - """#327: a range read is only what was asked for when the server says so: 206 and `bytes START-END/...`.""" - if status != 206: - raise IOError("range request not honoured: HTTP %s instead of 206 (a mirror or proxy that ignores the Range " - "header sends the whole file)" % status) - want = "bytes %d-%d/" % (start, end) - if not (content_range or "").strip().startswith(want): - raise IOError("range request answered with Content-Range %r, not %s..." % (content_range, want)) - - -def pinned(): - """The tensors' hashes are the pinned revision's: they apply when this run reads that revision.""" - return REPO == PINNED - - -def sha256_of(path): - h = hashlib.sha256() - with open(path, "rb") as f: - for block in iter(lambda: f.read(1 << 24), b""): - h.update(block) - return h.hexdigest() - - -def resolve_repo(): - """REPO, or the repository's current files when the pinned revision is gone from it (a 404 on its index).""" - global REPO - try: - req = urllib.request.Request(REPO + "model.safetensors.index.json", method="HEAD", - headers={"User-Agent": "strata-mtp-fetch"}) - urllib.request.urlopen(req, timeout=120).close() - except urllib.error.HTTPError as e: - if e.code == 404 and "/resolve/main/" not in REPO: - print("the checkpoint's pinned revision %s is gone: reading its current files (main)" % REVISION, - file=sys.stderr) - REPO = REPO.replace("/resolve/%s/" % REVISION, "/resolve/main/") - except OSError: - pass # no answer: get() retries and reports it - return REPO - - -def shard_header(shard): - url = REPO + shard - n = struct.unpack(" r["bytes"]: - os.remove(path) - have = 0 - with open(path, "ab") as f: - pos = r["start"] + have - while pos <= r["end"]: - end = min(pos + chunk - 1, r["end"]) - f.write(get(REPO + r["shard"], pos, end)) - pos = end + 1 - print("%s %.0f%%" % (r["name"], 100 * (pos - r["start"]) / r["bytes"]), file=sys.stderr) - if os.path.getsize(path) != r["bytes"]: - sys.exit("%s: size %d != %d" % (path, os.path.getsize(path), r["bytes"])) - digest = sha256_of(path) - if want is None or digest == want: - break - os.remove(path) # wrong bytes (#327): the whole tensor again, once - if attempt: - sys.exit("%s: sha256 %s is not the checkpoint's %s - the download source sends wrong data (a mirror " - "that ignores Range requests?)" % (r["name"], digest, want)) - print("%s: wrong bytes (sha256 %s...), fetching it again" % (r["name"], digest[:12]), file=sys.stderr) - manifest.append(dict(r, file=os.path.relpath(path, out), sha256=digest)) - with open(os.path.join(out, "mtp-manifest.json"), "w", encoding="utf-8") as f: - json.dump(manifest, f, indent=1) - - -def verify(out): - """#327: the fetched tensors against SHA256 -> the names that are missing or wrong. [] when they are right, or - when there is nothing to check (no tensors/, or STRATA_MTP_REVISION names another revision). A tensor's verdict - is kept in tensors/verified.json by size and mtime, so a later run hashes only what changed.""" - tdir = os.path.join(out, "tensors") - if not pinned() or not os.path.isdir(tdir): - return [] - stamp_path = os.path.join(tdir, "verified.json") - try: - with open(stamp_path, encoding="utf-8") as f: - stamps = json.load(f) - except (OSError, ValueError): - stamps = {} - bad, good = [], {} - for name, want in sorted(SHA256.items()): - path = os.path.join(tdir, name + ".bin") - if not os.path.exists(path): - bad.append(name) - continue - st = os.stat(path) - key = [st.st_size, st.st_mtime_ns, want] - if stamps.get(name) != key and sha256_of(path) != want: - bad.append(name) - continue - good[name] = key - try: - with open(stamp_path, "w", encoding="utf-8") as f: - json.dump(good, f, indent=1) - except OSError: - pass - return bad - - -def main(): - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("cmd", choices=["inventory", "fetch", "verify"]) - ap.add_argument("--out", required=True) - ap.add_argument("--only") - a = ap.parse_args() - if a.cmd == "verify": # offline: the hashes are the pinned revision's - bad = verify(a.out) - for name in bad: - print("MTP tensor missing or corrupt: %s" % name, file=sys.stderr) - sys.exit(BAD if bad else 0) - resolve_repo() - inventory(a.out) if a.cmd == "inventory" else fetch(a.out, a.only) - - -if __name__ == "__main__": - main() diff --git a/tools/mtp_pack.py b/tools/mtp_pack.py deleted file mode 100644 index 022d2ea..0000000 --- a/tools/mtp_pack.py +++ /dev/null @@ -1,193 +0,0 @@ -"""tools/mtp_pack.py - plan v0.3 P6 prep: the MTP draft block as a Strata GGUF, from the BF16 tensors. - -llama.cpp's qwen4exp converter drops the MTP head (`supports_mtp_export = False`), and the flyweight MTP GGUF is -no longer on this PC, so Strata packs its own from the 31 `mtp.*` tensors fetched by tools/mtp_fetch.py: - - python tools/mtp_pack.py --src Desktop/Strata/mtp-bf16 --experts q2_0 --out mtp-q2_0.gguf - python tools/mtp_pack.py --src ... --experts q4_0 --out mtp-q4_0.gguf (acceptance comparison arm) - -Layout: dense tensors (attention, indexer, hyper-connections, shared expert, router, fc/norms) stay BF16 (F32 for -1-D norms), ~0.18 GB. The routed experts keep the checkpoint's fused layout - `gate_up_proj` [512, 1280, 2560] and -`down_proj` [512, 2560, 640], quantized along the last (input) axis - in one of: - - q2_0 64-element blocks, grid {-1, 0, 1, 2} x d. The scale is chosen per block to MINIMIZE squared error over - that grid (the ggml reference sets d = max|w| and never uses the +2 level). Same format as the main - model's experts, so Strata's CPU VNNI kernel and GPU hit kernel serve it unchanged. ~0.71 GB. - q4_0 ggml reference rounding. ~1.42 GB. q8_0 ggml reference. ~2.67 GB. - -This is round-to-nearest, not GSQ: the plan picks the expert format by MEASURED draft acceptance (P0.3/P6), not -by this file's reconstruction error, which is reported per tensor only as a sanity check. No model runs here. -""" -from __future__ import annotations - -import argparse -import hashlib -import json -import sys -import time -from pathlib import Path - -import numpy as np - -HERE = Path(__file__).resolve().parent -sys.path.insert(0, str(Path(__file__).resolve().parent)) -from _paths import add_gguf_py # noqa: E402 -add_gguf_py() -import gguf # noqa: E402 (the pinned llama.cpp gguf-py, which knows Q2_0 = type 42) - -EXPERT_TENSORS = ("mtp.layers.0.mlp.experts.gate_up_proj", "mtp.layers.0.mlp.experts.down_proj") - - -class _Experts: - """Index an expert out of a BF16 memmap as float32 on demand.""" - def __init__(self, raw): - self.raw = raw - - def __getitem__(self, e): - return (np.asarray(self.raw[e]).astype(np.uint32) << 16).view(np.float32) - - -def load_bf16(path: Path, shape: list[int]) -> np.ndarray: - raw = np.fromfile(path, dtype=" np.ndarray: - """[..., n] float32 -> bytes of Q2_0 blocks (fp16 d, 16 bytes of 2-bit codes, code = q + 1, 4 per byte).""" - x = w.reshape(-1, 64).astype(np.float32) - amax = np.abs(x).max(axis=1, keepdims=True) - best_err = np.full((x.shape[0], 1), np.inf, dtype=np.float32) - best_d = np.zeros_like(amax) - # Candidate scales span amax/2 (the +2 level reaches the max) to amax (the ggml reference); 17 steps. - for f in np.linspace(0.5, 1.0, 17, dtype=np.float32): - d = amax * f - inv = np.where(d > 0, 1.0 / np.where(d > 0, d, 1.0), 0.0) - q = np.clip(np.rint(x * inv), -1, 2) - err = ((q * d - x) ** 2).sum(axis=1, keepdims=True) - better = err < best_err - best_err = np.where(better, err, best_err) - best_d = np.where(better, d, best_d) - d16 = best_d.astype(np.float16) - d = d16.astype(np.float32) # quantize against the STORED scale - inv = np.where(d > 0, 1.0 / np.where(d > 0, d, 1.0), 0.0) - codes = (np.clip(np.rint(x * inv), -1, 2) + 1).astype(np.uint8) # 0..3 - c = codes.reshape(-1, 16, 4) - packed = (c[:, :, 0] | (c[:, :, 1] << 2) | (c[:, :, 2] << 4) | (c[:, :, 3] << 6)).astype(np.uint8) - out = np.empty((x.shape[0], 18), dtype=np.uint8) - out[:, :2] = d16.view(np.uint8).reshape(-1, 2) - out[:, 2:] = packed - return out.reshape(-1) - - -def q4_0(w: np.ndarray) -> np.ndarray: - """ggml quantize_row_q4_0_ref: d = max / -8 (signed max), code = clamp(round(x/d + 8.5) truncated, 0, 15).""" - x = w.reshape(-1, 32).astype(np.float32) - idx = np.abs(x).argmax(axis=1) - mx = x[np.arange(x.shape[0]), idx][:, None] - d = mx / -8.0 - inv = np.where(d != 0, 1.0 / np.where(d != 0, d, 1.0), 0.0) - q = np.minimum(15, np.trunc(x * inv + 8.5)).astype(np.uint8) - packed = (q[:, :16] | (q[:, 16:] << 4)).astype(np.uint8) - out = np.empty((x.shape[0], 18), dtype=np.uint8) - out[:, :2] = d.astype(np.float16).view(np.uint8).reshape(-1, 2) - out[:, 2:] = packed - return out.reshape(-1) - - -def q8_0(w: np.ndarray) -> np.ndarray: - x = w.reshape(-1, 32).astype(np.float32) - d = np.abs(x).max(axis=1, keepdims=True) / 127.0 - inv = np.where(d > 0, 1.0 / np.where(d > 0, d, 1.0), 0.0) - q = np.rint(x * inv).astype(np.int8) - out = np.empty((x.shape[0], 34), dtype=np.uint8) - out[:, :2] = d.astype(np.float16).view(np.uint8).reshape(-1, 2) - out[:, 2:] = q.view(np.uint8) - return out.reshape(-1) - - -def dequant(kind: str, blob: np.ndarray, n: int) -> np.ndarray: - if kind == "q2_0": - b = blob.reshape(-1, 18) - d = b[:, :2].copy().view(np.float16).astype(np.float32) - qs = b[:, 2:] - codes = np.stack([(qs >> s) & 3 for s in (0, 2, 4, 6)], axis=2).reshape(-1, 64).astype(np.float32) - return ((codes - 1.0) * d).reshape(-1)[:n] - if kind == "q4_0": - b = blob.reshape(-1, 18) - d = b[:, :2].copy().view(np.float16).astype(np.float32) - qs = b[:, 2:] - q = np.concatenate([qs & 15, qs >> 4], axis=1).astype(np.float32) - return ((q - 8.0) * d).reshape(-1)[:n] - b = blob.reshape(-1, 34) - d = b[:, :2].copy().view(np.float16).astype(np.float32) - return (b[:, 2:].view(np.int8).astype(np.float32) * d).reshape(-1)[:n] - - -QUANT = {"q2_0": (q2_0, gguf.GGMLQuantizationType.Q2_0, 64, 18), - "q4_0": (q4_0, gguf.GGMLQuantizationType.Q4_0, 32, 18), - "q8_0": (q8_0, gguf.GGMLQuantizationType.Q8_0, 32, 34)} - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--src", required=True, help="directory written by tools/mtp_fetch.py fetch") - ap.add_argument("--experts", choices=sorted(QUANT), default="q2_0") - ap.add_argument("--out", required=True) - ap.add_argument("--check-experts", type=int, default=8, help="experts per tensor used for the error report") - a = ap.parse_args() - src = Path(a.src) - manifest = json.loads((src / "mtp-manifest.json").read_text()) - fn, qtype, block, block_bytes = QUANT[a.experts] - w = gguf.GGUFWriter(a.out, "qwen4exp-mtp") - w.add_string("strata.mtp.source", "Qwen/Qwen3.8-Flash-Next BF16 checkpoint, mtp.* tensors") - w.add_string("strata.mtp.source_sha256", hashlib.sha256( - json.dumps({t["name"]: t["sha256"] for t in manifest}, sort_keys=True).encode()).hexdigest()) - w.add_string("strata.mtp.expert_format", a.experts) - w.add_string("strata.mtp.expert_quantizer", "per-block MSE scale search" if a.experts == "q2_0" else "ggml reference") - report = [] - for t in sorted(manifest, key=lambda t: t["name"]): - name, shape = t["name"], t["shape"] - t0 = time.time() - if name in EXPERT_TENSORS: - # Streamed one expert at a time from a read-only view: the fused gate_up tensor alone is 6.7 GB as - # float32, so it is never materialized whole. - raw = np.memmap(src / t["file"], dtype="`, the nextn block of a -MTP GGUF) as the engine's -drafter pack (docs/QWEN36-35B-A3B.md 3.10; docs/qwen36-port/step4-drafter.md). - - python3 -I tools/mtp_qwen36_pack.py --gguf Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf --out [--draft-vocab data/draft_vocab.bin] - -The pack is separate from the trunk's (tools/iq_pack.py leaves `blk.40` out of it), so the pack cut from the Q4_K_XL-MTP -file's draft block serves the plain IQ3_XXS trunk too: the geometry it was cut for is recorded and the engine checks it -against the trunk it drafts for. Flash-Next's drafter keeps tools/mtp_pack.py / mtp_rt.py; this tool writes the same -file names with llama.cpp's tensor names, so `MtpDrafter::load` picks the path by the trunk's architecture. - -Writes - dense.txt one line per dense tensor: `name kind rows cols offset bytes`, the name without its `blk.N.` prefix - (`nextn.eh_proj.weight`, `attn_norm.weight`, `attn_q.weight`, `ffn_gate_inp.weight`, ...). kind is - `f32` (every norm, read as `const float*`), `bf16` (the router `ffn_gate_inp` and the 1-D shared-expert gate - `ffn_gate_inp_shexp`: BF16 in the shipped -MTP files, F32 values that are BF16-exact in a synthetic one), or - the ggml type of a projection as stored, lowercase (`q8_0` in both shipped files), served through the - engine's native MMVQ (the types tools/iq_pack.py's NATIVE_PROJECTION_TYPES lists). rows = ne1 (the - output width), cols = ne0 (the contiguous input width); 1-D tensors are `1 n`. - dense.bin the tensors' bytes as stored in the GGUF, each at a 256-aligned offset - experts.bin n_expert blobs of [gate rows | up rows | down rows], the GGUF's blocks as stored: the native GPU expert - kernels' blob (strata/kernels/iq_kernels.hpp `native_expert_layout`), all of them resident in VRAM - native_experts.txt the trunk pack's v3 line form for the one layer (`layer gu_type d_type offset blob_bytes gate_off - up_off down_off`; the three role offsets are inside a blob, the header says so) - mtp.json the geometry the block was cut for (n_embd, heads, head_dim, n_rot, experts, k, n_ff, the shared width), - the types per tensor, the source file, and which draft vocabulary was copied - draft_vocab.bin the draft head's token subset (tools/draft_vocab.py; the same 248,320-token vocabulary as Flash-Next, - so the shipped data/draft_vocab*.bin carry over), copied from --draft-vocab unless `none` - -Refused by name: a file without exactly one nextn block, fused expert tensors, a projection or head type outside -NATIVE_PROJECTION_TYPES, an expert type pair the native kernels lack (the IQ4_XS-MTP file's Q3_K gate/up with Q4_K down: -only the Q4_K_XL-MTP file's Q4_K / Q5_K block is served today), an F32 router that is not BF16-exact. -""" -from __future__ import annotations - -import argparse -import json -import pathlib -import re -import shutil -import sys - -import numpy as np - -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from _paths import add_gguf_py # noqa: E402 -add_gguf_py() -import gguf # noqa: E402 -from iq_pack import NATIVE_PROJECTION_TYPES # noqa: E402 - -ARCH = "qwen35moe" -# the native GPU expert kernels' type pairs (src/kernels/cuda/iq_kernels.cu, the three STRATA_*_FMTS lists; the gate/up -# and down lists of docs/qwen36-port/step3-experts.md section 2). The engine asks `native_expert_supported` again at -# load; this is the early refusal with the tensor named. -GU_TYPES = {16, 17, 18, 21, 22, 23, 29, 42, 12, 13, 14, 6, 8} -D_TYPES = {20, 23, 42, 7, 6, 8, 18, 13, 14} -D_TYPES_256 = {18, 13, 14, 23} # 256-value blocks: need n_ff % 256 == 0 as a down projection -# the dense tensors of the draft block, by role (names without the blk.N. prefix) -NORMS = ("attn_norm.weight", "post_attention_norm.weight", "attn_q_norm.weight", "attn_k_norm.weight", - "nextn.enorm.weight", "nextn.hnorm.weight", "nextn.shared_head_norm.weight") -ROUTERS = ("ffn_gate_inp.weight", "ffn_gate_inp_shexp.weight") -PROJECTIONS = ("nextn.eh_proj.weight", "attn_q.weight", "attn_k.weight", "attn_v.weight", "attn_output.weight", - "ffn_gate_shexp.weight", "ffn_up_shexp.weight", "ffn_down_shexp.weight") -EXPERTS = ("ffn_gate_exps.weight", "ffn_up_exps.weight", "ffn_down_exps.weight") -ALIGN = 256 - - -def meta_int(r: gguf.GGUFReader, key: str, default=None): - f = r.fields.get(key) - if f is None: - if default is None: - sys.exit("%s: missing" % key) - return default - return int(f.parts[f.data[0]][0]) - - -def raw_bytes(t) -> np.ndarray: - """A tensor's bytes in ggml memory order (ne0 contiguous), whatever gguf-py typed its view as.""" - a = np.ascontiguousarray(np.asarray(t.data)) - b = a.view(np.uint8).reshape(-1) - if b.size != int(t.n_bytes): - sys.exit("%s: %d bytes read, %d expected" % (t.name, b.size, t.n_bytes)) - return b - - -def bf16_exact_problem(name: str, f32: np.ndarray): - u = f32.view(np.uint32) - bad = int(np.count_nonzero(u & np.uint32(0xFFFF))) - if bad: - return ("%s is F32 with %d of %d values that are not BF16 (low 16 bits set), but the engine reads it as BF16" - % (name, bad, u.size)) - return None - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--gguf", required=True, help="a qwen35moe -MTP GGUF (nextn_predict_layers 1)") - ap.add_argument("--out", required=True) - ap.add_argument("--draft-vocab", default=None, - help="the draft head's token subset to copy in as draft_vocab.bin (default: data/draft_vocab.bin " - "beside this tool when it exists; `none` for the whole vocabulary)") - a = ap.parse_args() - src = pathlib.Path(a.gguf) - out = pathlib.Path(a.out) - r = gguf.GGUFReader(str(src)) - arch_f = r.fields.get("general.architecture") - arch = bytes(arch_f.parts[arch_f.data[0]]).decode("utf-8") if arch_f else "" - if arch != ARCH: - sys.exit("%s: general.architecture is %r, this tool packs %s" % (src.name, arch, ARCH)) - k = lambda s: "%s.%s" % (ARCH, s) - n_blocks = meta_int(r, k("block_count")) - nextn = meta_int(r, k("nextn_predict_layers"), 0) - if nextn != 1: - sys.exit("%s: nextn_predict_layers is %d; the drafter is one nextn block (the plain file has none: use the " - "-MTP build of the same model)" % (src.name, nextn)) - trunk = n_blocks - nextn - p = "blk.%d." % trunk - geo = dict(n_embd=meta_int(r, k("embedding_length")), n_head=meta_int(r, k("attention.head_count")), - n_head_kv=meta_int(r, k("attention.head_count_kv")), head_dim=meta_int(r, k("attention.key_length")), - n_rot=meta_int(r, k("rope.dimension_count")), n_expert=meta_int(r, k("expert_count")), - n_expert_used=meta_int(r, k("expert_used_count")), n_ff=meta_int(r, k("expert_feed_forward_length")), - n_ff_shexp=meta_int(r, k("expert_shared_feed_forward_length")), trunk_layers=trunk, draft_block=trunk) - T = {t.name[len(p):]: t for t in r.tensors if t.name.startswith(p)} - if not T: - sys.exit("%s: no blk.%d.* tensors" % (src.name, trunk)) - if "ffn_gate_up_exps.weight" in T or "attn_qkv.weight" in T: - sys.exit("%s: blk.%d carries fused tensors (%s); the drafter reads separate ffn_gate_exps / ffn_up_exps and " - "attn_q / attn_k / attn_v" % (src.name, trunk, - ", ".join(n for n in ("ffn_gate_up_exps.weight", "attn_qkv.weight") if n in T))) - missing = [n for n in NORMS + ROUTERS + PROJECTIONS + EXPERTS if n not in T] - if missing: - sys.exit("%s: blk.%d is missing %s" % (src.name, trunk, ", ".join(missing))) - stray = sorted(set(T) - set(NORMS + ROUTERS + PROJECTIONS + EXPERTS)) - if stray: - print("note: %d tensor(s) of blk.%d the drafter does not read, left out: %s" % (len(stray), trunk, ", ".join(stray))) - - # ---- the expert blob: [gate | up | down] per expert, types the native kernels take - ge, ue, de = (T[n] for n in EXPERTS) - gt, ut, dt = int(ge.tensor_type), int(ue.tensor_type), int(de.tensor_type) - E, FF, N = geo["n_expert"], geo["n_ff"], geo["n_embd"] - for t, shape in ((ge, (N, FF, E)), (ue, (N, FF, E)), (de, (FF, N, E))): - if tuple(int(x) for x in t.shape) != shape: - sys.exit("%s%s: shape %s, expected ne %s" % (p, t.name[len(p):], [int(x) for x in t.shape], list(shape))) - if gt != ut: - sys.exit("%s: gate (%s) and up (%s) differ in type" % (p, ge.tensor_type.name, ue.tensor_type.name)) - bad = [] - if gt not in GU_TYPES: - bad.append("%sffn_gate_exps / ffn_up_exps are %s" % (p, ge.tensor_type.name)) - if dt not in D_TYPES or (dt in D_TYPES_256 and FF % 256): - bad.append("%sffn_down_exps is %s" % (p, de.tensor_type.name)) - if bad: - sys.exit("%s: the native GPU expert kernels (iq_kernels.cu) have no kernel for this pair: %s" % (src.name, "; ".join(bad))) - gu_mat, d_mat = int(ge.n_bytes) // E, int(de.n_bytes) // E - if gu_mat * E != int(ge.n_bytes) or d_mat * E != int(de.n_bytes) or int(ue.n_bytes) != int(ge.n_bytes): - sys.exit("%s: expert tensor bytes are not whole experts" % p) - blob = 2 * gu_mat + d_mat - - # ---- the dense tensors - out.mkdir(parents=True, exist_ok=True) - lines, types, off = [], {}, 0 - with open(out / "dense.bin", "wb") as f: - for name in NORMS + ROUTERS + PROJECTIONS: - t = T[name] - tn = t.tensor_type.name - ne = [int(x) for x in t.shape] - if name in NORMS: - if tn != "F32" or len(ne) != 1: - sys.exit("%s%s is %s %s; the drafter reads its norms as F32 vectors" % (p, name, tn, ne)) - raw, kind, rows, cols = raw_bytes(t), "f32", 1, ne[0] - elif name in ROUTERS: - if tn == "BF16": - raw = raw_bytes(t) - elif tn == "F32": - f32 = np.ascontiguousarray(np.asarray(t.data), dtype=np.float32).reshape(-1) - why = bf16_exact_problem(p + name, f32) - if why: - sys.exit(why) - raw = (f32.view(np.uint32) >> 16).astype(np.uint16).view(np.uint8) # the high halves, exact - else: - sys.exit("%s%s is %s; the drafter reads it as BF16" % (p, name, tn)) - kind, rows, cols = "bf16", (ne[1] if len(ne) > 1 else 1), ne[0] - else: - if tn not in NATIVE_PROJECTION_TYPES: - sys.exit("%s%s is %s, which the engine's native MMVQ has no kernel for; it serves %s" - % (p, name, tn, ", ".join(sorted(NATIVE_PROJECTION_TYPES)))) - if len(ne) != 2: - sys.exit("%s%s: a projection is 2-D, this one is %s" % (p, name, ne)) - raw, kind, rows, cols = raw_bytes(t), tn.lower(), ne[1], ne[0] - pad = (-off) % ALIGN - f.write(b"\0" * pad) - off += pad - f.write(raw.tobytes()) - lines.append("%s %s %d %d %d %d" % (name, kind, rows, cols, off, raw.size)) - types[name] = tn - off += int(raw.size) - (out / "dense.txt").write_text("\n".join(lines) + "\n", encoding="utf-8") - # the eh_proj's shape is the one place the concatenation's width is checked before the engine runs it - eh = T["nextn.eh_proj.weight"] - if [int(x) for x in eh.shape] != [2 * N, N]: - sys.exit("%snextn.eh_proj.weight is ne %s, expected [%d, %d] (concat(enorm, hnorm) -> n_embd)" - % (p, [int(x) for x in eh.shape], 2 * N, N)) - - # ---- the experts, one blob each, in id order - g_raw, u_raw, d_raw = (raw_bytes(t).reshape(E, -1) for t in (ge, ue, de)) - with open(out / "experts.bin", "wb") as f: - for e in range(E): - f.write(g_raw[e].tobytes()) - f.write(u_raw[e].tobytes()) - f.write(d_raw[e].tobytes()) - (out / "native_experts.txt").write_text( - "# strata native experts v3 (the drafter's one block): layer gu_type d_type offset blob_bytes gate_off up_off " - "down_off (n_expert %d, total %d; `offset` in experts.bin, the three role offsets inside a blob; from %s blk.%d)\n" - "0 %d %d 0 %d 0 %d %d\n" % (E, blob * E, src.name, trunk, gt, dt, blob, gu_mat, 2 * gu_mat), encoding="utf-8") - - # ---- the draft vocabulary - dv = a.draft_vocab - if dv is None: - cand = pathlib.Path(__file__).resolve().parents[1] / "data" / "draft_vocab.bin" - dv = str(cand) if cand.is_file() else "none" - vocab = None - if dv != "none": - ids = np.fromfile(dv, dtype="= n_vocab: - sys.exit("%s: %d ids, not all inside the vocabulary (%d)" % (dv, ids.size, n_vocab)) - shutil.copyfile(dv, out / "draft_vocab.bin") - vocab = {"file": pathlib.Path(dv).name, "tokens": int(ids.size)} - else: - (out / "draft_vocab.bin").unlink(missing_ok=True) - - info = {"format": "strata mtp pack (qwen35moe) v1", "arch": ARCH, "source": src.name, - "source_bytes": src.stat().st_size, **geo, - "experts": {"gu_type": gt, "gu_type_name": ge.tensor_type.name, "d_type": dt, - "d_type_name": de.tensor_type.name, "blob_bytes": blob, "gu_matrix_bytes": gu_mat, - "down_matrix_bytes": d_mat, "bytes": blob * E}, - "dense": types, "dense_bytes": off, "draft_vocab": vocab} - (out / "mtp.json").write_text(json.dumps(info, indent=1) + "\n", encoding="utf-8") - print("wrote %s: dense.bin %d B (%d tensors), experts.bin %d B (%d x %d: gate/up %s, down %s), draft_vocab %s" - % (out, off, len(lines), blob * E, E, blob, ge.tensor_type.name, de.tensor_type.name, - vocab["tokens"] if vocab else "none (the whole head)")) - for line in lines: - print(" " + line) - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/mtp_rt.py b/tools/mtp_rt.py deleted file mode 100644 index 6276e4c..0000000 --- a/tools/mtp_rt.py +++ /dev/null @@ -1,111 +0,0 @@ -"""tools/mtp_rt.py - plan v0.3 P6: the MTP draft layer's runtime files, from the packed MTP GGUF. - - python tools/mtp_rt.py --gguf /mtp-bf16/mtp-q2_0.gguf --out /mtp-bf16/rt - -Writes - experts.bin 512 routed experts in the engine's blob layout (`include/strata/kernels/cpu/expert.hpp`): gate/up - rows interleaved (2r = gate r, 2r+1 = up r), then down rows; the Q2_0 codes in one plane and the fp16 - scales in another. A lossless relayout of the GGUF's Q2_0 blocks (same bytes, `cpu_expert_fixture.py`). - dense.bin every other tensor: the large projections quantized to Q8_0 (ggml's reference rounding) so the - engine's multi-column MMVQ can run them; the hyper-connection and router weights kept BF16; the - RMSNorm weights as F32 with the Gemma "+1" applied (vLLM GemmaRMSNorm scales by 1 + w). - dense.txt one line per tensor: name kind rows cols offset bytes (kind = q8_0 | bf16 | f32) -""" -from __future__ import annotations - -import argparse -import sys -from pathlib import Path - -import numpy as np - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -from _paths import add_gguf_py # noqa: E402 -add_gguf_py() -import gguf # noqa: E402 - -H, FF, NE = 2560, 640, 512 -BLOB = 3 * (H * FF * 18 // 64) -Q8 = {"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", "self_attn.indexer.index_qk_proj.weight", - "mlp.shared_expert.gate_proj.weight", "mlp.shared_expert.up_proj.weight", "mlp.shared_expert.down_proj.weight"} - - -def q8_0(x: np.ndarray) -> bytes: - """ggml quantize_row_q8_0_ref over rows of a 2-D float32 array: 32-value blocks, fp16 d = amax / 127.""" - b = x.reshape(-1, 32).astype(np.float32) - amax = np.abs(b).max(axis=1) - d = amax / 127.0 - inv = np.where(d > 0, 1.0 / np.where(d > 0, d, 1.0), 0.0).astype(np.float32) - v = b * inv[:, None] - q = (np.sign(v) * np.floor(np.abs(v) + 0.5)).astype(np.int8) - out = np.empty((b.shape[0], 34), dtype=np.uint8) - out[:, :2] = d.astype(np.float16).view(np.uint8).reshape(-1, 2) - out[:, 2:] = q.view(np.uint8) - return out.tobytes() - - -def blob_of(gu: np.ndarray, dn: np.ndarray) -> bytes: - """gu: (1280, 720) Q2_0 rows (gate rows 0..639, up rows 640..1279); dn: (2560, 180).""" - gub = gu.reshape(2 * FF, H // 64, 18) - inter = np.empty_like(gub) - inter[0::2] = gub[:FF] - inter[1::2] = gub[FF:] - dnb = dn.reshape(H, FF // 64, 18) - parts = [inter[:, :, 2:].tobytes(), dnb[:, :, 2:].tobytes(), inter[:, :, :2].tobytes(), dnb[:, :, :2].tobytes()] - out = b"".join(parts) - assert len(out) == BLOB, len(out) - return out - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--gguf", required=True) - ap.add_argument("--out", required=True) - a = ap.parse_args() - out = Path(a.out) - out.mkdir(parents=True, exist_ok=True) - r = gguf.GGUFReader(a.gguf) - tens = {t.name: t for t in r.tensors} - gu = np.asarray(tens["mtp.layers.0.mlp.experts.gate_up_proj"].data) - dn = np.asarray(tens["mtp.layers.0.mlp.experts.down_proj"].data) - assert gu.shape == (NE, 2 * FF, 720) and dn.shape == (NE, H, 180), (gu.shape, dn.shape) - with open(out / "experts.bin", "wb") as f: - for e in range(NE): - f.write(blob_of(gu[e], dn[e])) - lines = [] - off = 0 - with open(out / "dense.bin", "wb") as f: - for name, t in tens.items(): - if "experts." in name: - continue - short = name[len("mtp."):] - short = short[len("layers.0."):] if short.startswith("layers.0.") else short - data = np.asarray(t.data) - if int(t.tensor_type) == 0: # F32 norm weights: raw GemmaRMSNorm w -> 1 + w - arr = (data.astype(np.float32) + 1.0) - raw, kind, rows, cols = arr.tobytes(), "f32", 1, arr.size - else: # BF16 - u16 = data.view(np.uint16) if data.dtype != np.uint16 else data - u16 = u16.reshape(data.shape[0], -1) - rows, cols = u16.shape - if short in Q8: - f32 = (u16.astype(np.uint32) << 16).view(np.float32) - raw, kind = q8_0(f32), "q8_0" - else: - raw, kind = u16.tobytes(), "bf16" - pad = (-off) % 256 - f.write(b"\0" * pad) - off += pad - f.write(raw) - lines.append(f"{short} {kind} {rows} {cols} {off} {len(raw)}") - off += len(raw) - (out / "dense.txt").write_text("\n".join(lines) + "\n", encoding="utf-8") - print(f"experts.bin {NE * BLOB} B, dense.bin {off} B, {len(lines)} tensors -> {out}") - for l in lines: - print(" " + l) - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/pack_index.py b/tools/pack_index.py deleted file mode 100644 index 02678ac..0000000 --- a/tools/pack_index.py +++ /dev/null @@ -1,260 +0,0 @@ -"""tools/pack_index.py - emit a flat index of the pack's dense tensors for the engine's loader. - -WHY AN INDEX AND NOT A JSON PARSER. The manifest is JSON and the engine is C++. A JSON parser in the engine -would be a new, unaudited component whose failure mode is a wrong byte offset - which decodes to a plausible -weight and produces plausible logits. Python already parses the manifest correctly and is already the tool -that WROTE it, so this flattens what the loader needs into one line per tensor. - -WHY TEXT AND NOT BINARY. `pack/full/index.txt` is ~150 KB for 1,079 tensors. A fixed-size binary record -would save 60 KB and cost a struct-packing contract between two languages that must agree on padding, -endianness and field order - three ways to be wrong for no benefit at this size. Text is also readable when -a load produces the wrong number, which is the only time this file matters. - -THE ENGINE LAYOUT IS NOT THE PACK LAYOUT, and that is the point of `dst_*`. Two independent differences: - - 1. A tensor whose source type is BF16 or F16 is stored in the pack PROMOTED to 32 bits, because that is - lossless and it keeps the canonical decoder simple. A running engine does not have to hold it that way: - re-rounding to 16 bits costs nothing at all, because the value came FROM 16 bits. That is 1.374 GiB of - the 5.305 GiB dense file, and per `tools/pack_budget.py` it is the difference between the dense weights - fitting in VRAM beside the expert cache and not fitting at all. - - 2. **A SCALE PLANE MAY BE 2 BYTES IN THE PACK AND IS ALWAYS 4 IN THE ENGINE.** This is the one that hid - for a whole round. 90 of the 303 quantized tensors - every Q2_0 (all 58 expert tensors), Q4_0, Q5_0, - Q8_0 and IQ4_NL - carry fp16 scales, because that is what the SOURCE ggml block stores (a Q5_0 block is - `{fp16 d; ...}`). 213 tensors (IQ4_XS, Q3_K, Q4_K, Q5_K, Q6_K) carry f32 scales. The manifest has said - which is which all along, in `scales_fp16`. - - `src/core/layer.cpp` did not read that field. It assumed 4 bytes per scale, so it computed a scale plane - twice the real size, the three planes did not add up to the tensor, and the loader REFUSED - which is how - this was found, and the refusal is the only reason it was not a silent wrong answer. The first diagnosis - was "the manifest's `group_elems` must be wrong, the real group is 64". It is not: `group_elems` is 32 - and the scale plane is 2 bytes wide. **The unexamined input was the WIDTH, not the count.** An audit of - all 303 tensors against `scales_fp16`/`offsets_fp16` found zero inconsistencies, which is what settled it. - - The engine widens fp16 scales to f32 at load. That is EXACT - fp16 is a subset of f32 - and it costs - 11,407,360 B (10.88 MiB) of the 4.5 GiB pool, against teaching three kernel families a second scale - width. Note the asymmetry that makes this cheap and the BF16 re-rounding large: re-rounding loses - precision and saves GiB; widening loses nothing and costs MiB. - - `offsets_fp16` is also read, and it is FALSE for all 54 tensors that have an offset plane. It is - honoured anyway rather than assumed, because the next pack may not be. - -Columns: - - 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 - -`kind` is what the loader must DO, spelled out here rather than left for it to infer - the four cases are -distinguishable in the manifest but only by combining `source_type` with `values_fp16`, and getting that -combination wrong produces a plausible tensor: - - 0 VERBATIM copy straight through (BF16-free: F16 already 2 B/elem, F32, and the planes below) - 1 BF16_IN_F32 the pack holds the bf16 value promoted to f32; take the HIGH 16 BITS. Exact, not a - rounding: a bf16 value IS the top half of its f32 image. - 2 F32 copy 4 B/elem - 3 F16_IN_F32 the pack holds an f16 value promoted to f32; needs a real f32->f16 conversion with - round-to-nearest-even, NOT a truncation - -`ne0`/`ne1` are the manifest's own shape in its own order, with ne0 the CONTIGUOUS axis. `form` is the -canonical form letter from the manifest (P16/P32/S2/S4/S8); the SForm attributes are 0 for kinds 1-3. - -`codes_bytes`/`scales_bytes`/`offset_bytes` are the THREE ENGINE-FORM PLANE SIZES, in the order they sit in -the destination. They are emitted rather than left for the loader to re-derive, because re-deriving is where -the width bug lived: two places computing one layout is two places to disagree, and the loader cannot check a -layout it invented. The loader instead checks what it was TOLD: `scales_bytes/2` when `scales_fp16`, and the -three planes summing to both `src_bytes` (source widths) and `dst_bytes` (engine widths). Non-quantized -tensors carry `codes_bytes == dst_bytes` and two zeroes. -""" -from __future__ import annotations - -import argparse -import json -import os -import sys - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -FILE_ID = {"dense.bin": 0, "embd.bin": 1, "experts.bin": 2} -VERBATIM, BF16_IN_F32, F32_COPY, F16_IN_F32 = 0, 1, 2, 3 - -# WHICH ACTIVATION THIS WEIGHT WANTS, decided HERE because it is a property of `source_type` and the engine's -# `SForm` cannot recover it. The legacy formats (Q2_0, Q4_0, Q5_0, Q8_0, IQ4_NL) have `vec_dot_type` Q8_0; the -# K-quants and IQ4_XS have Q8_K. **NO COMBINATION OF THE S-FORM FIELDS TELLS THEM APART**: Q5_0 and Q5_K are -# both 8-bit with bias -16 (only `has_offset` differs), and IQ4_NL and IQ4_XS are both 4-bit with the IQ4NL -# codebook and no offset - they differ in NOTHING the S-form carries. That is why this column exists rather -# than the engine re-deriving the rule from `code_bits`. -ACT_Q8_0, ACT_Q8_K = 0, 1 -VDT = { - "Q2_0": ACT_Q8_0, "Q4_0": ACT_Q8_0, "Q5_0": ACT_Q8_0, "Q8_0": ACT_Q8_0, "IQ4_NL": ACT_Q8_0, - "Q3_K": ACT_Q8_K, "Q4_K": ACT_Q8_K, "Q5_K": ACT_Q8_K, "Q6_K": ACT_Q8_K, "IQ4_XS": ACT_Q8_K, -} - -# The plane key is `offsets`, NOT `mins`. The first version of this list said `mins` - which is what ggml calls -# the quantity conceptually, and the manifest does not - and a missing key in a loop like this is not an error, -# it is a SHORTER SPAN: 54 Q4_K/Q5_K tensors loaded with their offset plane never copied. Keys now come from -# the manifest, and the layout is verified against the recorded plane offsets rather than assumed. -PLANE_KEYS = ("codes", "scales", "offsets") - - -def main() -> int: - ap = argparse.ArgumentParser() - ap.add_argument("--pack", default="pack/full") - ap.add_argument("-o", "--out", default=None, help="default: /index.txt") - args = ap.parse_args() - out_path = args.out or os.path.join(args.pack, "index.txt") - - with open(os.path.join(args.pack, "manifest.json"), "r", encoding="utf-8") as fh: - man = json.load(fh) - align = int(man.get("align", 64)) - - def align_up(n: int) -> int: - return (n + align - 1) // align * align - - rows = [] - dst = 0 - n_reduced = 0 - saved = 0 - widened = 0 - n_widened = 0 - kinds: dict[int, int] = {} - for name, v in man["tensors"].items(): - f = v.get("file") - if f not in FILE_ID: - print("unknown file %r for %s" % (f, name), file=sys.stderr) - return 1 - shape = v.get("shape") or [0, 0] - ne0 = int(shape[0]) if len(shape) > 0 else 0 - ne1 = int(shape[1]) if len(shape) > 1 else 0 - elems = int(v.get("elements", 0)) - st = v.get("source_type") or "?" - - codes_bytes = scales_bytes = offset_bytes = 0 - scales_fp16 = 0 - widen_here = 0 - act_kind = ACT_Q8_0 - if "values" in v: - src_off = int(v["values"]["offset"]) - src_bytes = int(v["values"]["bytes"]) - else: - planes = [k for k in PLANE_KEYS if isinstance(v.get(k), dict)] - lo = min(int(v[k]["offset"]) for k in planes) - hi = max(int(v[k]["offset"]) + int(v[k].get("bytes", 0)) for k in planes) - src_off, src_bytes = lo, hi - lo - - # the planes must be CONTIGUOUS, in order, because the loader reads them as one span. If a future - # pack interleaves them this refuses; the alternative is reading the scale plane as offsets and - # decoding a plausible weight. - expect = src_off - for k in PLANE_KEYS: - if k not in planes: - continue - if int(v[k]["offset"]) != expect: - print("%s: plane %r starts at %d but %d was expected - planes are not contiguous" - % (name, k, int(v[k]["offset"]), expect), file=sys.stderr) - return 1 - expect += int(v[k].get("bytes", 0)) - if expect != src_off + src_bytes: - print("%s: plane span %d does not end at %d" % (name, expect, src_off + src_bytes), - file=sys.stderr) - return 1 - - if v.get("has_offset") and "offsets" not in planes: - print("%s says has_offset but has no `offsets` plane (found %s)" % (name, planes), - file=sys.stderr) - return 1 - - act_kind = VDT.get(st, ACT_Q8_0) # refuses below if the type is unknown - code_bits = int(v.get("code_bits") or 0) - group_elems = int(v.get("group_elems") or 0) - if code_bits == 0 or group_elems == 0: - print("%s: a quantized tensor with code_bits=%d group_elems=%d" % (name, code_bits, group_elems), - file=sys.stderr) - return 1 - if ne0 % group_elems: - print("%s: ne0 %d is not a multiple of group_elems %d" % (name, ne0, group_elems), - file=sys.stderr) - return 1 - n_groups = ne0 // group_elems - codes_bytes = elems * code_bits // 8 - scales_fp16 = 1 if v.get("scales_fp16") else 0 - offs_fp16 = 1 if v.get("offsets_fp16") else 0 - # engine-form plane sizes: ALWAYS 4 B per scale. fp16 in the pack is widened; the load is exact. - scales_bytes = ne1 * n_groups * 4 - offset_bytes = ne1 * n_groups * 4 if v.get("has_offset") else 0 - src_planes = (codes_bytes - + ne1 * n_groups * (2 if scales_fp16 else 4) - + (ne1 * n_groups * (2 if offs_fp16 else 4) if v.get("has_offset") else 0)) - if src_planes != int(v["codes"]["bytes"]) + int(v["scales"]["bytes"]) \ - + int(v.get("offsets", {}).get("bytes", 0)): - print("%s: derived planes %d disagree with the manifest's own plane bytes %d" - % (name, src_planes, int(v["codes"]["bytes"]) + int(v["scales"]["bytes"]) - + int(v.get("offsets", {}).get("bytes", 0))), file=sys.stderr) - return 1 - if src_planes != src_bytes: - print("%s: derived planes %d do not fill the span %d" % (name, src_planes, src_bytes), - file=sys.stderr) - return 1 - if scales_fp16: - widen_here = scales_bytes - ne1 * n_groups * 2 - widened += widen_here - n_widened += 1 - - # ---- the engine form, as an explicit KIND rather than a flag to interpret - vf = bool(v.get("values_fp16")) - if st == "BF16": - kind = BF16_IN_F32 - dst_bytes = elems * 2 - saved += src_bytes - dst_bytes - n_reduced += 1 - elif st == "F16" and not vf: - kind = F16_IN_F32 - dst_bytes = elems * 2 - saved += src_bytes - dst_bytes - n_reduced += 1 - elif st == "F16": - kind = VERBATIM # already 2 bytes on disk - dst_bytes = src_bytes - elif st == "F32": - kind = F32_COPY - dst_bytes = elems * 4 - else: - kind = VERBATIM - dst_bytes = codes_bytes + scales_bytes + offset_bytes - # THE ENGINE FORM OF A QUANTIZED TENSOR DIFFERS FROM THE PACK BY EXACTLY THE WIDENING, and saying - # so here is what makes the two plane sizes a CHECK rather than two independent guesses. - if dst_bytes != src_bytes + widen_here: - print("%s: engine form %d != pack %d + widening %d" % (name, dst_bytes, src_bytes, widen_here), - file=sys.stderr) - return 1 - - cb = v.get("codebook") - rows.append((name, FILE_ID[f], kind, src_off, src_bytes, dst, dst_bytes, ne0, ne1, - int(v.get("code_bits") or 0), int(v.get("code_bias") or 0), - int(v.get("group_elems") or 0), 1 if cb == "IQ4NL" else 0, - 1 if v.get("has_offset") else 0, - codes_bytes, scales_bytes, offset_bytes, scales_fp16, act_kind)) - dst = align_up(dst + dst_bytes) - kinds[kind] = kinds.get(kind, 0) + 1 - - with open(out_path, "w", encoding="utf-8", newline="\n") as fh: - fh.write("# strata pack index v3 -- generated by tools/pack_index.py; do not hand-edit\n") - fh.write("# align %d pool %d tensors %d\n" % (align, dst, len(rows))) - fh.write("# 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\n") - for r in rows: - fh.write("%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n" % r) - - names = {VERBATIM: "VERBATIM", BF16_IN_F32: "BF16_IN_F32", F32_COPY: "F32", F16_IN_F32: "F16_IN_F32"} - print("%s: %d tensors, engine pool %d B (%.3f GiB)" % (out_path, len(rows), dst, dst / 2**30)) - for k in sorted(kinds): - print(" kind %-12s %4d tensors" % (names[k], kinds[k])) - print(" %d tensors re-rounded to 16 bits, saving %d B (%.3f GiB)" - % (n_reduced, saved, saved / 2**30)) - print(" %d tensors widened fp16 scales -> f32, costing %d B (%.3f GiB)" - % (n_widened, widened, widened / 2**30)) - print(" compare with tools/pack_budget.py: the pack's dense+embd engine figure should match this pool") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/pack_layer.py b/tools/pack_layer.py deleted file mode 100644 index 1fdf114..0000000 --- a/tools/pack_layer.py +++ /dev/null @@ -1,123 +0,0 @@ -"""Strata P0.S9 - build the pack-layout expert arena from the real GGUF. - -The architecture (§3.2) defines one expert blob as 1,382,400 bytes: - - gate_up.codes 2 x 640 rows x 640 B rows interleaved g0,u0,g1,u1,... (share input x) - down.codes 2,560 rows x 160 B - gate_up.scales 2 x 640 x 40 x FP16 - down.scales 2,560 x 10 x FP16 - -and that totals exactly 819,200 + 409,600 + 102,400 + 51,200 = 1,382,400 B, matching the artifact's -Q2_0 expert size to the byte. The conversion is a pure relayout: Q2_0 codes and their FP16 block -scale are copied unchanged, so dequant(pack) == dequant(ggml) bit-exactly. - -Why build this at all rather than read the GGUF in place: the GGUF stores gate, up and down as three -separate tensors, so a fused gate/up pass would read two streams from three arrays. The pack -interleaves gate and up ROWS so one pass over the activation vector serves both, which is the whole -point of the blob layout. - -Expert index is the LAST axis of [in, out, experts] (P0.S6), and ne[0] varies fastest, so expert `e` -is one CONTIGUOUS 460,800-byte run inside each role tensor. Extraction is a strided copy. - -Run: python tools/pack_layer.py [n_layers] (default 1; 48 = the full 34 GB arena) -""" -from __future__ import annotations - -import json -import pathlib -import struct -import sys - -import numpy as np - -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from gguf_reader import GGUFFile # noqa: E402 - -REPO = pathlib.Path(__file__).resolve().parents[1] -STRATA = REPO.parents[min(1, len(REPO.parents) - 1)] # the dev layout's default shards (setup.py passes --gguf) -SHARD1 = STRATA / "Q2_0" / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf" - -H, FF, NE = 2560, 640, 512 -QK, BLOCK_BYTES = 64, 18 # Q2_0 -ROW_BYTES_GU = H * 2 // 8 # 640 B of codes for one 2,560-wide row -ROW_BYTES_D = FF * 2 // 8 # 160 B of codes for one 640-wide row -SCALES_GU = H // QK # 40 blocks per gate/up row -SCALES_D = FF // QK # 10 blocks per down row -ROLE_BYTES = H * FF * BLOCK_BYTES // QK # 460,800 B per role per expert -BLOB_BYTES = 3 * ROLE_BYTES # 1,382,400 - -assert BLOB_BYTES == 1_382_400, BLOB_BYTES -assert 2 * 640 * ROW_BYTES_GU + 2560 * ROW_BYTES_D + 2 * 640 * SCALES_GU * 2 \ - + 2560 * SCALES_D * 2 == BLOB_BYTES - - -def blob_offsets() -> dict[str, int]: - gu_codes = 0 - d_codes = gu_codes + 2 * FF * ROW_BYTES_GU - gu_scales = d_codes + H * ROW_BYTES_D - d_scales = gu_scales + 2 * FF * SCALES_GU * 2 - end = d_scales + H * SCALES_D * 2 - assert end == BLOB_BYTES, end - return {"gate_up_codes": gu_codes, "down_codes": d_codes, - "gate_up_scales": gu_scales, "down_scales": d_scales} - - -OFF = blob_offsets() - - -def build(n_layers: int, out_path: pathlib.Path) -> dict: - g = GGUFFile(SHARD1) - by_name = {t.name: t for t in g.tensors} - src = open(SHARD1, "rb") - manifest = {"blob_bytes": BLOB_BYTES, "offsets": OFF, "layers": [], "n_layers": n_layers} - total = n_layers * NE * BLOB_BYTES - out_path.parent.mkdir(parents=True, exist_ok=True) - - with out_path.open("wb") as out: - for layer in range(n_layers): - roles = {} - for role in ("gate", "up", "down"): - t = by_name[f"blk.{layer}.ffn_{role}_exps.weight"] - roles[role] = t - assert t.type_name == "Q2_0", t.type_name - # expert e is a contiguous run inside the role tensor - per_expert = t.elements // NE - assert per_expert * BLOCK_BYTES // QK == ROLE_BYTES, per_expert - layer_off = out.tell() - # vectorized over the layer's 512 experts (the same bytes the per-block loop wrote; tools/strata_pack.py - # verify checks them): each role is (512 experts, rows, blocks per row, 18 bytes) - def role_blocks(role, rows, per_row): - t = roles[role] - n = NE * ROLE_BYTES - src.seek(g.data_start + t.offset) - a = np.frombuffer(src.read(n), dtype=np.uint8) - assert a.size == n, (role, a.size) - return a.reshape(NE, rows, per_row, BLOCK_BYTES) - gate = role_blocks("gate", FF, SCALES_GU) - up = role_blocks("up", FF, SCALES_GU) - down = role_blocks("down", H, SCALES_D) - gu = np.stack([gate, up], axis=2).reshape(NE, 2 * FF, SCALES_GU, BLOCK_BYTES) # rows g0,u0,g1,u1,... - blobs = np.concatenate([ - gu[:, :, :, 2:].reshape(NE, -1), # gate/up codes - down[:, :, :, 2:].reshape(NE, -1), # down codes - gu[:, :, :, :2].reshape(NE, -1), # gate/up fp16 scales - down[:, :, :, :2].reshape(NE, -1), # down fp16 scales - ], axis=1) - assert blobs.shape == (NE, BLOB_BYTES), blobs.shape - out.write(blobs.tobytes()) - manifest["layers"].append({"layer": layer, "offset": layer_off, - "role_offsets": {r: by_name[f"blk.{layer}.ffn_{r}_exps.weight"].offset - for r in ("gate", "up", "down")}}) - print(f" layer {layer}: wrote {NE} blobs at {layer_off}") - src.close() - manifest["total_bytes"] = total - (out_path.with_suffix(".json")).write_text(json.dumps(manifest, indent=2), encoding="utf-8") - return manifest - - -if __name__ == "__main__": - n = int(sys.argv[1]) if len(sys.argv) > 1 else 1 - dest = REPO / "pack" / ("layer0.bin" if n == 1 else f"experts-{n}l.bin") - print(f"building {n} layer(s) -> {dest} ({(n*NE*BLOB_BYTES)/2**30:.2f} GiB)") - m = build(n, dest) - print(f"done: {m['total_bytes']/2**30:.2f} GiB, {n*NE} blobs") diff --git a/tools/qwen36_check_dequant.py b/tools/qwen36_check_dequant.py deleted file mode 100644 index e706156..0000000 --- a/tools/qwen36_check_dequant.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python3 -"""tools/qwen36_check_dequant.py - ref/load.py (gguf-py) dequantization against ggml's own to_float, on a real GGUF. - - python3 tools/qwen36_check_dequant.py MODEL.gguf /path/to/qwen36-dequant (built from tools/qwen36_dequant_ggml.cpp) - -Checks token_embd rows, one routed expert of each distinct quant type in the first and last blocks, and a dense -projection of each type. Prints the max |difference| per tensor; exit 1 if any exceeds 1e-6 * max|x|. -""" -import subprocess, sys, tempfile, pathlib -import numpy as np -REPO = pathlib.Path(__file__).resolve().parents[1] -sys.path[:0] = [str(REPO), str(REPO / "tools")] -from _paths import add_gguf_py -add_gguf_py() -from ref.load import Gguf - - -def main(): - path, tool = sys.argv[1], sys.argv[2] - g = Gguf(path) - cases, seen = [], set() - for t in g.g.tensors: - key = (t.type_name, len(t.shape)) - if t.name == "token_embd.weight": - cases.append((t.name, "rows", 12345)) - elif key not in seen and len(t.shape) >= 2 and t.type_name not in ("F32", "F16", "BF16"): - seen.add(key); cases.append((t.name, "e" if len(t.shape) == 3 else "all", 5)) - for t in g.g.tensors: # every quant type that occurs as a routed-expert tensor, wherever it first appears - if len(t.shape) == 3 and (t.type_name, 9) not in seen: - seen.add((t.type_name, 9)); cases.append((t.name, "e", 7)) - bad = 0 - for name, mode, idx in cases: - t = g.info(name) - if mode == "rows": - ref = g.rows(name, [idx, idx + 1, 247000]) - slabs = [(r * t.shape[0], t.shape[0]) for r in (idx, idx + 1, 247000)] - ref = ref.reshape(-1) - elif mode == "e": - per = t.shape[0] * t.shape[1] - ref = g.expert(name, idx).reshape(-1); slabs = [(idx * per, per)] - else: - ref = g.tensor(name).reshape(-1)[: 256 * 4096]; slabs = [(0, ref.size)] - outs = [] - for first, n in slabs: - with tempfile.NamedTemporaryFile() as f: - subprocess.run([tool, path, name, str(first), str(n), f.name], check=True, capture_output=True) - outs.append(np.fromfile(f.name, dtype=np.float32)) - got = np.concatenate(outs) - d, m = float(np.abs(got - ref).max()), float(np.abs(got).max()) - ok = d <= 1e-6 * max(m, 1e-9) - bad += not ok - print(f"{'ok ' if ok else 'FAIL'} {name:34s} {t.type_name:8s} {mode:4s} max|d| {d:.2e} max|x| {m:.3g}") - return 1 if bad else 0 - -sys.exit(main()) diff --git a/tools/qwen36_check_eval_callback.py b/tools/qwen36_check_eval_callback.py deleted file mode 100644 index bb067e8..0000000 --- a/tools/qwen36_check_eval_callback.py +++ /dev/null @@ -1,130 +0,0 @@ -#!/usr/bin/env python3 -"""tools/qwen36_check_eval_callback.py - check the printed output of the submodule's `llama-eval-callback` -against the numpy oracle's dumps. - - llama-eval-callback -m MODEL.gguf -p "hello" -ctk f32 -ctv f32 -fa off -c 64 -t 1 -ngl 0 > eval.txt 2>&1 - python3 ref/qwen36.py MODEL.gguf --text hello --dump ORA - python3 tools/qwen36_check_eval_callback.py ORA eval.txt [--tol 1e-4] - -`llama-eval-callback` prints, per graph node, the first and last 3 entries along every dimension (`%12.4f`, so each -printed value carries up to 5e-5 of rounding) and a float32 `sum` of the whole tensor. This reconstructs which -indices were printed from the shape (common/debug.cpp:75-117), looks them up in the oracle's array of the same -cb() name, and requires |printed - oracle| <= tol on every printed value and the sum to agree to tol of the -tensor's L1 mass. Repeated names get "#2", "#3" in execution order, as in the dumps. Nodes llama.cpp leaves -unnamed ("node_30", "x (view)") are ignored; "kq" and "kq_soft_max" are skipped because llama.cpp pads their -KV axis to its cache size. Exit status 1 on any mismatch or if fewer than --min-seams names were checked. -""" -import argparse -import math -import re -import sys -import pathlib - -import numpy as np - -HEAD = re.compile(r"^common_debug_cb_eval:\s+(.+?) = \((\w+)\)\s+\w+\(.*\) = \{(\d+), (\d+), (\d+), (\d+)\}\s*$") -NUM = re.compile(r"(? 6 else "") - return 1 if bad or checked < a.min_seams or (a.require_tail and not complete) else 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/qwen36_compare_dumps.py b/tools/qwen36_compare_dumps.py deleted file mode 100644 index 94439cf..0000000 --- a/tools/qwen36_compare_dumps.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python3 -"""tools/qwen36_compare_dumps.py - compare two directories of cb()-named .f32 dumps seam by seam. - - python3 tools/qwen36_compare_dumps.py ORACLE_DIR LLAMA_DIR [--tol 1e-4] [--quiet] - -Both directories hold .f32 + manifest.txt (" ,,,"), written by -ref/qwen36.py and tools/qwen36_dump_llama.cpp. For every stem in the ORACLE manifest that also appears in -the llama manifest: shapes must match (llama.cpp pads the KV axis of "kq"/"kq_soft_max" to its cache size; the -padded part is cropped, and for "kq_soft_max" required to be exactly zero), then max |a-b| is reported with the -largest magnitude seen, and the seam fails when max |a-b| > tol * max(1, max|b|). Integer seams (router -indices) must be identical. Stems present on only one side are listed. Exit status 1 on any failure. -""" -import argparse -import pathlib -import sys - -import numpy as np - - -def load(d): - d = pathlib.Path(d) - out = {} - for line in (d / "manifest.txt").read_text().splitlines(): - stem, kind, ne = line.split() - ne = tuple(int(x) for x in ne.split(",")) - a = np.fromfile(d / f"{stem}.f32", dtype=np.float32) - out[stem] = (kind, ne, a.reshape(tuple(reversed(ne)))) - return out - - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument("oracle") - ap.add_argument("llama") - ap.add_argument("--tol", type=float, default=1e-4) - ap.add_argument("--quiet", action="store_true", help="print only failures and the summary") - a = ap.parse_args() - o, l = load(a.oracle), load(a.llama) - bad, rows = 0, [] - for stem, (kind, ne, x) in o.items(): - if stem not in l: - continue - lk, lne, y = l[stem] - if lne != ne: - crop = stem.split("-")[0] in ("kq", "kq_soft_max") and lne[1:] == ne[1:] and lne[0] >= ne[0] - if not crop: - rows.append((stem, "SHAPE", f"oracle ne {ne} vs llama ne {lne}")) - bad += 1 - continue - pad = y[..., ne[0]:] - y = y[..., :ne[0]] - if stem.startswith("kq_soft_max") and np.any(pad != 0): - rows.append((stem, "PAD", "padded KV columns are not zero")) - bad += 1 - continue - if kind == "i32": - ok = np.array_equal(x, y) - rows.append((stem, "ok" if ok else "FAIL", "identical" if ok else f"{int((x != y).sum())} indices differ")) - bad += 0 if ok else 1 - continue - finite = np.isfinite(y) - err = np.abs(np.where(finite, x - y, 0.0)).max() if x.size else 0.0 - mag = np.abs(np.where(finite, y, 0.0)).max() if x.size else 0.0 - if not np.array_equal(np.isfinite(x), finite) or not np.array_equal(np.isneginf(x), np.isneginf(y)): - rows.append((stem, "FAIL", "non-finite pattern differs")) - bad += 1 - continue - ok = err <= a.tol * max(1.0, mag) - rows.append((stem, "ok" if ok else "FAIL", f"max|d| {err:.3e} max|x| {mag:.4g}")) - bad += 0 if ok else 1 - for r in rows: - if not a.quiet or r[1] != "ok": - print(f"{r[1]:5s} {r[0]:36s} {r[2]}") - only_o = sorted(set(o) - set(l)) - # "conv_state_update-N" is a view of the cache that llama.cpp evaluates BEFORE the copy that updates it, so it - # holds the old state; the new state is "conv_state_last-N", which is compared. - only_l = sorted(x for x in set(l) - set(o) if not x.startswith("conv_state_update-")) - print(f"\ncompared {len(rows)} seams, {bad} failed (tol {a.tol:g} x max(1, max|x|))") - print(f"oracle only ({len(only_o)}): {only_o}") - print(f"llama only ({len(only_l)}): {only_l}") - return 1 if bad else 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/qwen36_compare_logits.py b/tools/qwen36_compare_logits.py deleted file mode 100644 index 77067d5..0000000 --- a/tools/qwen36_compare_logits.py +++ /dev/null @@ -1,155 +0,0 @@ -#!/usr/bin/env python3 -"""tools/qwen36_compare_logits.py - the engine's per-position logits against a reference's, teacher-forced. - - python3 -I tools/qwen36_compare_logits.py ENGINE.f32 REFERENCE.f32 --n-vocab N [--engine-header] [--rows R] - [--routes-engine F --routes-ref F] [--json OUT] - -ENGINE.f32 is `strata --dump-logits` (two int32, n_vocab and rows, then the rows; --engine-header is the default) -or raw rows; REFERENCE.f32 is raw rows of n_vocab F32 (tools/qwen36_teacher_llama.cpp's logits.f32, or the oracle's -result_output_all). Row j of both is the distribution at the same position. Reports, per position and summarised: - - top-1 agreement the argmax of the two rows equal - KL(ref || engine) in nats, from the softmax of each row (mean, max, the position of the max) - drift Maya's quantized-mode gate: KL must not rise monotonically with the position - the slope of - KL against the position (least squares) and the Spearman rank correlation are printed; the - gate (--max-spearman) is one-sided - only a RISING KL is drift (Spearman > the bound), a - chaotic spread is flat and a falling KL is not drift - routes with --routes-*: " e0 .. e7" lines from both sides, the share of probed - (row, layer) pairs whose top-k SETS are equal - -Exit 1 when a gate given on the command line fails (--min-top1, --max-mean-kl, --max-max-kl, --max-spearman). -""" -import argparse -import json -import sys - -import numpy as np - - -def load_engine(path, n_vocab, header): - a = np.fromfile(path, dtype=np.float32) - if header: - h = np.frombuffer(a[:2].tobytes(), dtype=np.int32) - if int(h[0]) != n_vocab: - raise SystemExit(f"{path}: header says n_vocab {int(h[0])}, expected {n_vocab}") - a = a[2:] - rows = int(h[1]) - if a.size != rows * n_vocab: - raise SystemExit(f"{path}: header promises {rows} rows, the file holds {a.size / n_vocab:.2f}") - return a.reshape(-1, n_vocab) - - -def softmax(x): - x = x.astype(np.float64) - x = x - x.max(axis=1, keepdims=True) - e = np.exp(x) - return e / e.sum(axis=1, keepdims=True) - - -def spearman(x, y): - rx = np.argsort(np.argsort(x)).astype(np.float64) - ry = np.argsort(np.argsort(y)).astype(np.float64) - if rx.std() == 0 or ry.std() == 0: - return 0.0 - return float(np.corrcoef(rx, ry)[0, 1]) - - -def read_routes(path): - out = {} - for line in open(path): - parts = line.split() - if len(parts) < 3: - continue - row, layer = int(parts[0]), int(parts[1]) - out[(row, layer)] = frozenset(int(p) for p in parts[2:]) - return out - - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument("engine") - ap.add_argument("reference") - ap.add_argument("--n-vocab", type=int, required=True) - ap.add_argument("--engine-header", action="store_true", default=True) - ap.add_argument("--no-engine-header", dest="engine_header", action="store_false") - ap.add_argument("--rows", type=int, default=0, help="compare this many rows (0 = all common rows)") - ap.add_argument("--routes-engine") - ap.add_argument("--routes-ref") - ap.add_argument("--json") - ap.add_argument("--min-top1", type=float) - ap.add_argument("--max-mean-kl", type=float) - ap.add_argument("--max-max-kl", type=float) - ap.add_argument("--max-spearman", type=float) - ap.add_argument("--quiet", action="store_true") - a = ap.parse_args() - e = load_engine(a.engine, a.n_vocab, a.engine_header) - r = np.fromfile(a.reference, dtype=np.float32).reshape(-1, a.n_vocab) - n = min(e.shape[0], r.shape[0]) - if a.rows: - n = min(n, a.rows) - if n == 0: - raise SystemExit("no rows to compare") - e, r = e[:n], r[:n] - pe, pr = softmax(e), softmax(r) - kl = np.sum(pr * (np.log(pr + 1e-30) - np.log(pe + 1e-30)), axis=1) - top1 = (e.argmax(axis=1) == r.argmax(axis=1)) - top5 = np.array([len(set(np.argsort(-e[i])[:5]) & set(np.argsort(-r[i])[:5])) for i in range(n)]) - pos = np.arange(n, dtype=np.float64) - slope = float(np.polyfit(pos, kl, 1)[0]) if n > 1 else 0.0 - rho = spearman(pos, kl) if n > 1 else 0.0 - res = {"rows": int(n), "top1": int(top1.sum()), "top1_rate": float(top1.mean()), "kl_mean": float(kl.mean()), - "kl_max": float(kl.max()), "kl_argmax": int(kl.argmax()), "kl_median": float(np.median(kl)), - "kl_first_half": float(kl[: n // 2].mean()), "kl_second_half": float(kl[n // 2:].mean()), - "kl_slope_per_position": slope, "kl_spearman": rho, "top5_overlap_mean": float(top5.mean()), - "rows_top1_differ": [int(i) for i in np.nonzero(~top1)[0]]} - if a.routes_engine and a.routes_ref: - re_, rr = read_routes(a.routes_engine), read_routes(a.routes_ref) - common = sorted(set(re_) & set(rr)) - equal = sum(1 for k in common if re_[k] == rr[k]) - by_layer = {} - for k in common: - by_layer.setdefault(k[1], [0, 0]) - by_layer[k[1]][1] += 1 - by_layer[k[1]][0] += re_[k] == rr[k] - res["routes_pairs"] = len(common) - res["routes_equal"] = equal - res["routes_by_layer"] = {str(l): f"{v[0]}/{v[1]}" for l, v in sorted(by_layer.items())} - slot_eq = [] - for k in common: - slot_eq.append(len(re_[k] & rr[k]) / max(1, len(rr[k]))) - res["routes_slot_overlap_mean"] = float(np.mean(slot_eq)) if slot_eq else 0.0 - if not a.quiet: - print(f"{n} positions: top-1 agreement {res['top1']}/{n} ({res['top1_rate']:.4f}), top-5 overlap " - f"{res['top5_overlap_mean']:.2f}/5") - print(f"KL(ref||engine): mean {res['kl_mean']:.5f} median {res['kl_median']:.5f} max {res['kl_max']:.5f} " - f"at position {res['kl_argmax']}; first half {res['kl_first_half']:.5f}, second half {res['kl_second_half']:.5f}") - print(f"drift: KL slope {slope:+.2e} per position, Spearman(position, KL) {rho:+.3f}") - if res["rows_top1_differ"]: - print("top-1 differs at positions: " + ", ".join(map(str, res["rows_top1_differ"][:40])) + - (" ..." if len(res["rows_top1_differ"]) > 40 else "")) - if "routes_pairs" in res: - print(f"routes: {res['routes_equal']}/{res['routes_pairs']} probed (row, layer) top-k sets equal " - f"(per layer {res['routes_by_layer']}); mean slot overlap {res['routes_slot_overlap_mean']:.3f}") - print("per position (pos top1 kl):") - print(" ".join(f"{i}:{'=' if top1[i] else 'x'}{kl[i]:.3f}" for i in range(n))) - if a.json: - with open(a.json, "w") as f: - json.dump(res, f, indent=1) - bad = [] - if a.min_top1 is not None and res["top1_rate"] < a.min_top1: - bad.append(f"top-1 {res['top1_rate']:.4f} < {a.min_top1}") - if a.max_mean_kl is not None and res["kl_mean"] > a.max_mean_kl: - bad.append(f"mean KL {res['kl_mean']:.5f} > {a.max_mean_kl}") - if a.max_max_kl is not None and res["kl_max"] > a.max_max_kl: - bad.append(f"max KL {res['kl_max']:.5f} > {a.max_max_kl}") - if a.max_spearman is not None and rho > a.max_spearman: - bad.append(f"Spearman(position, KL) {rho:.3f} > {a.max_spearman}: KL rises with position (a leaking state); " - f"a negative correlation is not drift") - if bad: - print("GATE FAILED: " + "; ".join(bad)) - return 1 - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/qwen36_crosscheck.sh b/tools/qwen36_crosscheck.sh deleted file mode 100755 index d9acb2a..0000000 --- a/tools/qwen36_crosscheck.sh +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env bash -# tools/qwen36_crosscheck.sh - run the Qwen3.6 numpy oracle against the pinned llama.cpp graph on synthetic GGUFs. -# -# tools/qwen36_crosscheck.sh WORKDIR [REAL.gguf-with-nextn-for---like-real] -# -# Builds (CPU only, outside the repo, in WORKDIR/llbuild) the submodule's libllama and llama-eval-callback, builds -# tools/qwen36_dump_llama.cpp against it, writes the synthetic fixtures, and for each case compares -# (a) every cb()-named tensor, in full : ref/qwen36.py vs qwen36-dump (tools/qwen36_compare_dumps.py) -# (b) the printed stats of llama-eval-callback vs the oracle (tools/qwen36_check_eval_callback.py) -# Exit status 1 if any seam fails its tolerance (1e-4 of max(1, max|x|)). STRATA_GGUF_PY is honoured. -set -euo pipefail -REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -W="$(mkdir -p "${1:?usage: $0 WORKDIR [REAL.gguf]}" && cd "$1" && pwd)" -REAL="${2:-}" -LL="${LLAMA_CPP_DIR:-$REPO/third_party/llama.cpp}" -B="$W/llbuild" -PY="${PYTHON:-python3}" - -if [ ! -x "$B/bin/llama-eval-callback" ]; then - cmake -S "$LL" -B "$B" -DCMAKE_BUILD_TYPE=Release -DGGML_METAL=OFF -DGGML_BLAS=OFF -DLLAMA_CURL=OFF \ - -DLLAMA_BUILD_TESTS=OFF -DLLAMA_BUILD_SERVER=OFF > "$W/cmake.log" 2>&1 - cmake --build "$B" --target llama-eval-callback -j"$(sysctl -n hw.ncpu 2>/dev/null || nproc)" > "$W/build.log" 2>&1 -fi -c++ -std=c++17 -O1 "$REPO/tools/qwen36_dump_llama.cpp" -o "$B/qwen36-dump" \ - -I"$LL/include" -I"$LL/ggml/include" -L"$B/bin" -lllama -lggml -lggml-base -Wl,-rpath,"$B/bin" - -SYN="$REPO/tools/qwen36_synth_gguf.py" -mkdir -p "$W/fx" && cd "$W/fx" -$PY "$SYN" base.gguf > /dev/null -$PY "$SYN" seed7.gguf --seed 7 > /dev/null -$PY "$SYN" fused_gate_up.gguf --fused-gate-up --seed 3 > /dev/null -$PY "$SYN" fused_qkv.gguf --fused-qkv --no-nextn --seed 4 > /dev/null -$PY "$SYN" gqa.gguf --heads 4,2 --seed 11 > /dev/null # n_head_kv > 1: the h // (n_head/n_head_kv) mapping is exercised -$PY "$SYN" stray_scale.gguf --expert-weights-scale 2.5 --seed 5 > /dev/null -[ -n "$REAL" ] && $PY "$SYN" like_real.gguf --like-real "$REAL" | head -4 - -T11=104,101,108,108,111,32,119,111,114,108,100 # "hello world" -T40=104,101,108,108,111,32,119,111,114,108,100,33,10,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,48 -fail=0 -# compare DIR_A DIR_B: print failures and the summary lines, set fail=1 on a failed seam -compare() { - local out - out=$($PY "$REPO/tools/qwen36_compare_dumps.py" "$1" "$2" --quiet) || fail=1 - echo "$out" | grep -E "^(FAIL|SHAPE|PAD)|^compared|^llama only" | sed 's/^/ /' -} -# case: NAME MODEL TOKENS CHUNK(0 = one batch) WITH_MTP(0/1) -run_case() { - local name=$1 model=$2 toks=$3 chunk=$4 mtp=$5 - rm -rf "d_$name" "o_$name" "d_${name}_mtp" "o_${name}_mtp" - local extra=() oextra=() - [ "$mtp" = 1 ] && extra=(mtp) && oextra=(--mtp) - [ "$chunk" != 0 ] && oextra+=(--split "$chunk") - "$B/qwen36-dump" "$model" "d_$name" "$toks" "$chunk" ${extra[@]+"${extra[@]}"} > "dump_$name.log" 2>&1 - $PY "$REPO/ref/qwen36.py" "$model" --tokens "$toks" --dump "o_$name" ${oextra[@]+"${oextra[@]}"} > /dev/null - echo "== $name ($model, $(echo "$toks" | tr ',' '\n' | wc -l | tr -d ' ') tokens, chunk $chunk, mtp $mtp)" - compare "o_$name" "d_$name" - if [ "$mtp" = 1 ]; then - echo " nextn block (graph_mtp):" - compare "o_${name}_mtp" "d_${name}_mtp" - fi -} -run_case base_11 base.gguf $T11 0 1 -run_case base_40 base.gguf $T40 0 0 -run_case base_ar base.gguf $T40 1 0 # 40 tokens one at a time: the autoregressive GDN op, carried state and KV -run_case base_c7 base.gguf $T40 7 0 # chunks of 7, the last call (5 tokens) continues from 35 -run_case seed7 seed7.gguf $T11 0 1 -run_case fused_gu fused_gate_up.gguf $T11 0 1 -run_case fused_qkv fused_qkv.gguf $T11 0 0 -run_case gqa4_2 gqa.gguf $T40 0 1 -run_case stray_scl stray_scale.gguf $T11 0 1 -[ -n "$REAL" ] && run_case like_real like_real.gguf $T40 0 1 - -# (b) llama-eval-callback's own printout vs the oracle, for the 11-token prompt "hello world" -# llama-eval-callback's async logger drops its queue at exit, so the tail of the printout is sometimes cut off; retry until complete -for try in 1 2 3 4 5 6 7 8; do - "$B/bin/llama-eval-callback" -m base.gguf -p "hello world" -ctk f32 -ctv f32 -fa off -c 64 -t 1 -ngl 0 > eval_callback.txt 2>&1 - $PY "$REPO/tools/qwen36_check_eval_callback.py" o_base_11 eval_callback.txt --quiet --require-tail > /dev/null 2>&1 && break -done -grep -m1 "number of input tokens" eval_callback.txt -echo "== llama-eval-callback printed stats vs o_base_11" -$PY "$REPO/tools/qwen36_check_eval_callback.py" o_base_11 eval_callback.txt --quiet --require-tail || fail=1 -exit $fail diff --git a/tools/qwen36_dequant_ggml.cpp b/tools/qwen36_dequant_ggml.cpp deleted file mode 100644 index 1e56873..0000000 --- a/tools/qwen36_dequant_ggml.cpp +++ /dev/null @@ -1,30 +0,0 @@ -// tools/qwen36_dequant_ggml.cpp - dequantize a slab of one GGUF tensor with ggml's own to_float, to check ref/load.py (gguf-py). -// qwen36-dequant MODEL.gguf TENSOR FIRST_ELEMENT COUNT OUT.f32 (FIRST_ELEMENT and COUNT multiples of the block size) -// Build: c++ -std=c++17 -O1 tools/qwen36_dequant_ggml.cpp -o $B/qwen36-dequant -I$LL/ggml/include -L$B/bin -lggml -lggml-base -Wl,-rpath,$B/bin -#include "ggml.h" -#include "gguf.h" -#include -#include -#include -int main(int argc, char ** argv) { - if (argc < 6) { fprintf(stderr, "usage\n"); return 1; } - gguf_init_params ip = { true, nullptr }; - gguf_context * g = gguf_init_from_file(argv[1], ip); - if (!g) return 1; - int64_t id = gguf_find_tensor(g, argv[2]); - if (id < 0) { fprintf(stderr, "no tensor\n"); return 1; } - ggml_type t = gguf_get_tensor_type(g, id); - const ggml_type_traits * tr = ggml_get_type_traits(t); - int64_t first = atoll(argv[3]), n = atoll(argv[4]); - if (first % tr->blck_size || n % tr->blck_size) { fprintf(stderr, "not block aligned\n"); return 1; } - size_t off = gguf_get_data_offset(g) + gguf_get_tensor_offset(g, id) + (size_t)(first / tr->blck_size) * tr->type_size; - size_t nb = (size_t)(n / tr->blck_size) * tr->type_size; - std::vector raw(nb); - FILE * f = fopen(argv[1], "rb"); fseeko(f, off, SEEK_SET); - if (fread(raw.data(), 1, nb, f) != nb) return 1; - fclose(f); - std::vector out(n); - if (tr->to_float) tr->to_float(raw.data(), out.data(), n); else return 2; - f = fopen(argv[5], "wb"); fwrite(out.data(), 4, n, f); fclose(f); - printf("%s %s %s\n", argv[2], ggml_type_name(t), "ok"); -} diff --git a/tools/qwen36_dump_llama.cpp b/tools/qwen36_dump_llama.cpp deleted file mode 100644 index 713a57d..0000000 --- a/tools/qwen36_dump_llama.cpp +++ /dev/null @@ -1,171 +0,0 @@ -// tools/qwen36_dump_llama.cpp - run llama.cpp's own graph on a GGUF and dump every named tensor, in full. -// -// `llama-eval-callback` prints only 3 elements per edge and a float32 sum at 4 decimals. This does the same -// thing (a cb_eval callback on every node of the pinned submodule's graph) but writes each tensor named by -// llama.cpp's cb() - "attn_norm-0", "ffn_moe_topk-3", "result_output" - to /.f32 in full, in ggml -// memory order (ne0 fastest), I32 tensors converted to float. A repeated name (llama.cpp names "Kcur" twice -// in the attention graph) gets "#2", "#3" for the later occurrences. /manifest.txt lists -// " ,,," in the order the nodes ran. Same format as ref/qwen36.py. -// -// Build against the submodule (CPU only), outside the repo: -// 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 -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 -// Run: $B/qwen36-dump MODEL.gguf OUTDIR 104,101,108,108,111 [CHUNK [mtp]] -// CHUNK > 0 decodes the tokens CHUNK at a time (1 = the autoregressive path) and dumps only the last decode call, -// so the recurrent state and KV cache carried from the earlier calls are what is being checked. -// "mtp" loads the nextn block and, after the trunk pass, runs llama.cpp's MTP graph on (tokens[1:], trunk hidden -// states[:-1]) at positions 1.. - the pairing common/speculative.cpp builds (token k with the hidden of k-1) - -// and dumps it to OUTDIR_mtp. Needs CHUNK = 0. -// -// KV cache is F32 and flash attention is off, so on an F32 file the only difference to the numpy oracle is float -// summation order. Threads: 1, or $QWEN36_THREADS. - -#include "llama.h" -#include "ggml.h" -#include "ggml-backend.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -struct sink { - std::string dir; - std::map seen; - FILE * manifest = nullptr; - std::vector buf; - bool active = true; // only the last decode call is dumped when chunking - std::vector h_nextn; // the trunk's post-output-norm hidden states, for the MTP pass -}; - -static bool keep(const char * n) { - if (!n[0]) return false; - if (strncmp(n, "node_", 5) == 0 || strncmp(n, "leaf_", 5) == 0) return false; - if (strstr(n, " (") != nullptr) return false; // "x (view)", "x (reshaped)", "x (copy of y)" - if (strncmp(n, "cache_", 6) == 0) return false; - return true; -} - -static bool cb_eval(struct ggml_tensor * t, bool ask, void * ud) { - if (ask) return true; - auto * s = (sink *) ud; - if (!s->active) return true; - if (!keep(t->name) || ggml_is_quantized(t->type) || ggml_nelements(t) == 0) return true; - if (t->type != GGML_TYPE_F32 && t->type != GGML_TYPE_I32 && t->type != GGML_TYPE_F16) return true; - - std::string stem = t->name; - int n = ++s->seen[stem]; - if (n > 1) stem += "#" + std::to_string(n); - - const size_t nb = ggml_nbytes(t); - const bool host = ggml_backend_buffer_is_host(t->buffer); - const uint8_t * data = (const uint8_t *) t->data; - if (!host) { s->buf.resize(nb); ggml_backend_tensor_get(t, s->buf.data(), 0, nb); data = s->buf.data(); } - - std::vector out((size_t) ggml_nelements(t)); - size_t k = 0; - for (int64_t i3 = 0; i3 < t->ne[3]; i3++) - for (int64_t i2 = 0; i2 < t->ne[2]; i2++) - for (int64_t i1 = 0; i1 < t->ne[1]; i1++) - for (int64_t i0 = 0; i0 < t->ne[0]; i0++) { - const uint8_t * p = data + i3 * t->nb[3] + i2 * t->nb[2] + i1 * t->nb[1] + i0 * t->nb[0]; - float v; - if (t->type == GGML_TYPE_F32) v = *(const float *) p; - else if (t->type == GGML_TYPE_I32) v = (float) *(const int32_t *) p; - else v = ggml_fp16_to_fp32(*(const ggml_fp16_t *) p); - out[k++] = v; - } - if (stem == "h_nextn") s->h_nextn = out; - std::string path = s->dir + "/" + stem + ".f32"; - FILE * f = fopen(path.c_str(), "wb"); - if (!f) { fprintf(stderr, "cannot write %s\n", path.c_str()); exit(2); } - fwrite(out.data(), sizeof(float), out.size(), f); - fclose(f); - fprintf(s->manifest, "%s %s %lld,%lld,%lld,%lld\n", stem.c_str(), ggml_type_name(t->type), - (long long) t->ne[0], (long long) t->ne[1], (long long) t->ne[2], (long long) t->ne[3]); - return true; -} - -static sink * open_sink(const std::string & dir) { - auto * s = new sink; - s->dir = dir; - mkdir(dir.c_str(), 0755); - s->manifest = fopen((dir + "/manifest.txt").c_str(), "w"); - return s; -} - -int main(int argc, char ** argv) { - if (argc < 4) { fprintf(stderr, "usage: %s MODEL.gguf OUTDIR tok,tok,... [CHUNK [mtp]]\n", argv[0]); return 1; } - std::vector toks; - for (char * p = strtok(argv[3], ","); p; p = strtok(nullptr, ",")) toks.push_back((llama_token) atoi(p)); - const int chunk = argc > 4 ? atoi(argv[4]) : 0; - const bool want_mtp = argc > 5 && strcmp(argv[5], "mtp") == 0; - if (want_mtp && chunk != 0) { fprintf(stderr, "mtp needs CHUNK = 0\n"); return 1; } - - sink * s = open_sink(argv[2]); - - llama_backend_init(); - llama_model_params mp = llama_model_default_params(); - mp.n_gpu_layers = 0; - mp.load_mtp = want_mtp; - llama_model * model = llama_model_load_from_file(argv[1], mp); - if (!model) { fprintf(stderr, "model load failed\n"); return 1; } - - llama_context_params cp = llama_context_default_params(); - cp.n_ctx = 256; - cp.n_batch = cp.n_ubatch = 256; - const char * th = getenv("QWEN36_THREADS"); - cp.n_threads = cp.n_threads_batch = th ? atoi(th) : 1; - cp.type_k = GGML_TYPE_F32; - cp.type_v = GGML_TYPE_F32; - cp.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_DISABLED; - cp.cb_eval = cb_eval; - cp.cb_eval_user_data = s; - llama_context * ctx = llama_init_from_model(model, cp); - if (!ctx) { fprintf(stderr, "context init failed\n"); return 1; } - - const int n = (int) toks.size(); - const int step = chunk > 0 ? chunk : n; - for (int i = 0; i < n; i += step) { - const int m = std::min(step, n - i); - s->active = (i + m >= n); - if (llama_decode(ctx, llama_batch_get_one(toks.data() + i, m))) { fprintf(stderr, "decode failed\n"); return 1; } - } - fclose(s->manifest); - - if (want_mtp) { - const int n_embd = llama_model_n_embd(model); - sink * s2 = open_sink(std::string(argv[2]) + "_mtp"); - llama_context_params cp2 = cp; - cp2.ctx_type = LLAMA_CONTEXT_TYPE_MTP; - cp2.cb_eval_user_data = s2; - llama_context * mctx = llama_init_from_model(model, cp2); - if (!mctx) { fprintf(stderr, "mtp context init failed\n"); return 1; } - const int m = n - 1; - std::vector mt(toks.begin() + 1, toks.end()); - std::vector h(s->h_nextn.begin(), s->h_nextn.begin() + (size_t) m * n_embd); - std::vector pos(m); - std::vector nsid(m, 1); - std::vector sid0(1, 0); - std::vector sid(m, sid0.data()); - std::vector lg(m, 1); - for (int i = 0; i < m; i++) pos[i] = i + 1; - llama_batch b = {}; - b.n_tokens = m; b.token = mt.data(); b.embd = h.data(); b.pos = pos.data(); - b.n_seq_id = nsid.data(); b.seq_id = sid.data(); b.logits = lg.data(); - if (llama_decode(mctx, b)) { fprintf(stderr, "mtp decode failed\n"); return 1; } - fclose(s2->manifest); - llama_free(mctx); - } - llama_free(ctx); - llama_model_free(model); - llama_backend_free(); - return 0; -} diff --git a/tools/qwen36_router_bf16_flips.py b/tools/qwen36_router_bf16_flips.py deleted file mode 100644 index ef03d2c..0000000 --- a/tools/qwen36_router_bf16_flips.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/env python3 -"""tools/qwen36_router_bf16_flips.py - how often rounding Qwen3.6's F32 router weight to BF16 flips a top-8 choice. - -The shipped files store `blk.N.ffn_gate_inp.weight` in F32 and llama.cpp multiplies in F32; the engine's router -kernel reads a BF16 weight (`project_bf16` / `bf16_gemv_fp32_mmvf`, F32 activation x BF16 weight) and the pack -rounds the F32 tensor to BF16 under --compat-bf16 (docs/QWEN36-35B-A3B.md 3.4, docs/qwen36-port/upstream-tooling.md -section 4). A flipped selection is a different expert, not a rounding error, so the study asks for the flip rate to -be MEASURED on the real file, per layer, and not asserted: this script is that measurement, a number for the step-4 ---compat-bf16 decision. - - python3 -I ref/qwen36.py REAL.gguf --tokens T0,..,T7 --dump DIR --act-quant q8 # the router's inputs per layer - python3 -I tools/qwen36_router_bf16_flips.py REAL.gguf DIR [--k 8] - -For every layer it takes the oracle's `attn_post_norm-N` (the FFN input of the N-th layer, (T, n_embd)) and the file's -F32 router weight, forms the logits three ways - F32 x F32 (llama.cpp and the oracle; checked against the oracle's -own `ffn_moe_logits-N`), F32 x BF16(W) (the engine's native MMVF contract) and BF16(x) x BF16(W) (the legacy -`bf16_gemv` contract, both operands rounded) - and reports per layer: positions of the top-k that differ, experts -in one top-k set and not the other, tokens with any difference, and the smallest logit gap across the top-k boundary -(a flip needs the rounding error to exceed that gap), and the share of the layer's F32 router weight that is -already BF16-representable (low 16 bits zero). BF16 rounding is round-to-nearest-even, the engine's `bf16_from_f32`. - -Measured 2026-10-11 on both shipped files (UD-IQ3_XXS and UD-Q4_K_XL): every element of ffn_gate_inp, -ffn_gate_inp_shexp, ssm_alpha, ssm_beta and ssm_conv1d is BF16-exact (the checkpoint is BF16; the converter stored -them as F32), so F32 x BF16(W) is bitwise F32 x F32 and the flip rate of the engine's native contract is zero by -construction; the pack needs no --compat-bf16 for them. attn_norm is not BF16-exact (17%) and is read as F32. -""" -from __future__ import annotations - -import argparse -import pathlib -import sys - -import numpy as np - -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "ref")) -from load import Gguf # noqa: E402 - -F32 = np.float32 - - -def bf16_round(a: np.ndarray) -> np.ndarray: - """Round-to-nearest-even to BF16, returned as F32 (strata/kernels/bf16_bits.hpp bf16_from_f32).""" - u = np.ascontiguousarray(a, dtype=F32).view(np.uint32) - u = (u + ((u >> 16) & 1) + np.uint32(0x7FFF)) & np.uint32(0xFFFF0000) - return u.view(F32) - - -def topk_desc(logits: np.ndarray, k: int) -> np.ndarray: - """llama.cpp's selection: stable argsort of the softmax probabilities, descending, = of the logits.""" - return np.argsort(-logits, axis=1, kind="stable")[:, :k] - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - ap.add_argument("gguf") - ap.add_argument("dump", help="ref/qwen36.py --dump directory (needs attn_post_norm-N and ffn_moe_logits-N)") - ap.add_argument("--k", type=int, default=8) - a = ap.parse_args() - g = Gguf(a.gguf) - dump = pathlib.Path(a.dump) - n_layers = 0 - while (dump / f"ffn_moe_logits-{n_layers}.f32").exists(): - n_layers += 1 - if n_layers == 0: - sys.exit(f"{dump}: no ffn_moe_logits-N.f32 (run ref/qwen36.py --dump first)") - K = a.k - print(f"{a.gguf}: {n_layers} layers, top-{K}; router weight type " - f"{g.info('blk.0.ffn_gate_inp.weight').type_name}; dump {dump}") - print(f"{'layer':>5} {'oracle':>8} {'W bf16':>7} | {'F32 x BF16(W)':^30} | {'BF16(x) x BF16(W)':^30} | {'min gap':>9}") - print(f"{'':>5} {'max|d|':>8} {'-exact':>7} | {'slots':>6} {'set':>6} {'tokens':>7} {'rate':>7} | {'slots':>6} {'set':>6} {'tokens':>7} {'rate':>7} | {'(logits)':>9}") - tot = {"w": [0, 0, 0], "xw": [0, 0, 0], "slots": 0, "tokens": 0} - worst_oracle = 0.0 - for il in range(n_layers): - w = g.tensor(f"blk.{il}.ffn_gate_inp.weight").astype(F32) # (E, n_embd) - E, n_embd = w.shape - x = np.fromfile(dump / f"attn_post_norm-{il}.f32", dtype=F32).reshape(-1, n_embd) # (T, n_embd) - T = x.shape[0] - ref = np.fromfile(dump / f"ffn_moe_logits-{il}.f32", dtype=F32).reshape(T, E) - l32 = (x @ w.T).astype(F32) - worst_oracle = max(worst_oracle, float(np.abs(l32 - ref).max())) - wb = bf16_round(w) - exact = float((wb == w).mean()) # the share of the weight the rounding leaves untouched - l_w = (x @ wb.T).astype(F32) # the native MMVF contract: F32 activation, BF16 weight - l_xw = (bf16_round(x) @ wb.T).astype(F32) # the legacy bf16_gemv contract: both rounded - t32 = topk_desc(ref, K) # the oracle's own selection (identical to llama.cpp's) - gap = float((np.sort(ref, axis=1)[:, ::-1][:, K - 1] - np.sort(ref, axis=1)[:, ::-1][:, K]).min()) - row = [f"{il:>5} {np.abs(l32 - ref).max():>8.1e} {exact:>7.4f} |"] - for key, lg in (("w", l_w), ("xw", l_xw)): - tk = topk_desc(lg, K) - slots = int((tk != t32).sum()) - sets = sum(len(set(t32[t]) - set(tk[t])) for t in range(T)) - toks = int(sum(bool(set(t32[t]) != set(tk[t])) for t in range(T))) - tot[key][0] += slots; tot[key][1] += sets; tot[key][2] += toks - row.append(f" {slots:>6} {sets:>6} {toks:>7} {sets / (T * K):>7.3f} |") - tot["slots"] += T * K; tot["tokens"] += T - row.append(f" {gap:>9.2e}") - print("".join(row)) - n = tot["slots"] - print(f"\n{'total':>5} {worst_oracle:>8.1e} {'':>7} |", end="") - for key in ("w", "xw"): - s, st, tk = tot[key] - print(f" {s:>6} {st:>6} {tk:>7} {st / n:>7.4f} |", end="") - print(f"\n slots = positions of the top-{K} that differ (order included); set = experts chosen by F32 and not by the " - f"rounded weight (order ignored); tokens = tokens whose top-{K} SET differs; rate = set / ({tot['tokens']} tokens x {K}).") - print(" 'oracle max|d|' is this script's F32 logits against the oracle's ffn_moe_logits-N (a check of the inputs, not a result);") - print(" 'W bf16-exact' is the share of the layer's F32 router weight whose low 16 bits are zero (1.0000: BF16(W) == W, F32 x BF16(W) is F32 x F32).") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/qwen36_spread.py b/tools/qwen36_spread.py deleted file mode 100644 index be377c0..0000000 --- a/tools/qwen36_spread.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python3 -"""tools/qwen36_spread.py - per-seam-class spread between oracle dumps and a llama.cpp dump of the SAME real quantized file. - - python3 tools/qwen36_spread.py LLAMA_DIR LABEL=ORACLE_DIR [LABEL=ORACLE_DIR ...] - -For every seam of a class and every layer: rel_rms = ||oracle - llama|| / ||llama||. Prints, per class and label, -the median and the maximum over layers. Use it to set per-seam tolerances for the CUDA parity tests (docs/qwen36-port/oracle-crosscheck.md). -""" -import re, sys, pathlib -import numpy as np -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -import qwen36_compare_dumps as C - -CLASSES = [("norm (attn_norm)", r"attn_norm-\d+$"), ("qkv_mixed (GDN in-proj)", r"linear_attn_qkv_mixed-\d+$"), - ("gdn_out (linear_attn_out)", r"linear_attn_out-\d+$"), ("attn_out (attention o-proj)", r"attn_output-(3|7|11|15|19|23|27|31|35|39)$"), - ("moe_out (ffn_moe_out)", r"ffn_moe_out-\d+$"), ("ffn_out (routed+shared)", r"ffn_out-\d+$"), - ("l_out (layer output)", r"l_out-\d+$"), ("logits (result_output)", r"result_output$")] - -def main(): - l = C.load(sys.argv[1]) - runs = [a.split("=", 1) for a in sys.argv[2:]] - print("| class | " + " | ".join(f"{lab} median / max" for lab, _ in runs) + " |") - print("| --- | " + " | ".join("---" for _ in runs) + " |") - loaded = {lab: C.load(d) for lab, d in runs} - for cname, pat in CLASSES: - cells = [] - for lab, _ in runs: - o = loaded[lab] - v = [float(np.linalg.norm(o[s][2] - l[s][2]) / np.linalg.norm(l[s][2])) for s in o if re.match(pat, s) and s in l] - cells.append(f"{np.median(v):.1e} / {max(v):.1e}" if v else "-") - print(f"| {cname} | " + " | ".join(cells) + " |") - for lab, _ in runs: - o = loaded[lab] - n = sum(int(np.sum(o[f"ffn_moe_topk-{i}"][2] != l[f"ffn_moe_topk-{i}"][2])) for i in range(40) if f"ffn_moe_topk-{i}" in o) - tot = sum(o[f"ffn_moe_topk-{i}"][2].size for i in range(40) if f"ffn_moe_topk-{i}" in o) - print(f"") -main() diff --git a/tools/qwen36_synth_gguf.py b/tools/qwen36_synth_gguf.py deleted file mode 100644 index b44d958..0000000 --- a/tools/qwen36_synth_gguf.py +++ /dev/null @@ -1,373 +0,0 @@ -#!/usr/bin/env python3 -"""tools/qwen36_synth_gguf.py - a tiny synthetic `qwen35moe` GGUF (Qwen3.6-35B-A3B at toy scale). - -Real tensor names, real shape rules, F32 weights, deterministic seed, and every metadata key that -llama.cpp's loader reads for `qwen35moe` (src/models/qwen35moe.cpp:4-34 and src/llama-model.cpp:1231-1424 -in the pinned submodule). It exists so that `ref/qwen36.py` (the numpy oracle) and the submodule's own -`llama-eval-callback` can run the same forward pass on the same weights, and so the engine's parity tests -have a fixture that needs no 13 GB download. - - python3 tools/qwen36_synth_gguf.py OUT.gguf # default toy geometry, with the nextn layer - python3 tools/qwen36_synth_gguf.py OUT.gguf --like-real REAL.gguf # geometry ratios, rope, eps, interval from REAL - python3 tools/qwen36_synth_gguf.py OUT.gguf --no-nextn --fused-gate-up --fused-qkv - python3 tools/qwen36_synth_gguf.py OUT.gguf --gdn 2,4,128 --experts 256,8 --shexp-ff 512 --quant-shexp q8_0 --bf16-exact - # the engine's kernel fixture (step 3): state 128 (the CUDA GDN kernels are pinned to it), the real router - # shape, the shared expert at its real width in Q8_0, and the weights the engine reads as BF16 already - # BF16-representable, so the oracle and the kernels differ only by summation order - -Default geometry (all dims small enough to read, large enough that every reshape is non-degenerate): - - hidden 64, 4 layers (interval 4: layers 0,1,2 are Gated DeltaNet, layer 3 is full attention), - GDN 4 k-heads / 8 v-heads of dim 16, conv kernel 4, attention 2 heads / 1 KV head of dim 32, - partial rotary 8/32 = 0.25 with IMRoPE sections [2,1,1,0], 8 experts top-2, expert ff 32, shared ff 32, - vocab 128 (byte-level BPE with no merges, token id = ASCII code, so `-p "abc"` is tokens 97 98 99), - plus one nextn (MTP) block at index 4, so block_count is 5 and nextn_predict_layers is 1. - -Shape rules (GGUF dims are ne order, fastest first; numpy shapes below are the reverse): - - token_embd.weight / output.weight ne [n_embd, n_vocab] - blk.N.attn_norm / post_attention_norm ne [n_embd] - GDN: attn_qkv [n_embd, 2*key_dim+value_dim] attn_gate [n_embd, value_dim] ssm_conv1d [d_conv, conv_dim] - ssm_dt.bias [H_v] ssm_a [H_v] ssm_alpha/ssm_beta [n_embd, H_v] ssm_norm [S] ssm_out [value_dim, n_embd] - attn: attn_q [n_embd, 2*n_head*hd] attn_k/v [n_embd, n_kv*hd] attn_output [n_head*hd, n_embd] q_norm/k_norm [hd] - MoE: ffn_gate_inp [n_embd, E] ffn_{gate,up}_exps [n_embd, ff, E] ffn_down_exps [ff, n_embd, E] - ffn_gate_inp_shexp [n_embd] ffn_{gate,up}_shexp [n_embd, ff] ffn_down_shexp [ff, n_embd] - nextn (block n_layer): the attention-layer tensors above plus the MoE tensors plus - nextn.eh_proj [2*n_embd, n_embd] nextn.enorm / nextn.hnorm / nextn.shared_head_norm [n_embd] - -Requires numpy and gguf-py (STRATA_GGUF_PY, or third_party/llama.cpp/gguf-py). -""" -from __future__ import annotations - -import argparse -import dataclasses -import pathlib -import sys - -import numpy as np - -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from _paths import add_gguf_py # noqa: E402 - -add_gguf_py() -from gguf import GGUFWriter # noqa: E402 - -ARCH = "qwen35moe" - - -@dataclasses.dataclass -class Cfg: - n_embd: int = 64 - n_layer: int = 4 # trunk layers (excludes the nextn block) - interval: int = 4 # full attention on layers where (il + 1) % interval == 0 - n_vocab: int = 128 - n_expert: int = 8 - n_expert_used: int = 2 - n_ff_exp: int = 32 - n_ff_shexp: int = 32 - ssm_k_heads: int = 4 - ssm_v_heads: int = 8 - ssm_state: int = 16 - ssm_conv: int = 4 - n_head: int = 2 - n_head_kv: int = 1 - head_dim: int = 32 - n_rot: int = 8 # 0.25 * head_dim, as the real model - rope_sections: tuple = (2, 1, 1, 0) # sum == n_rot / 2 - rope_base: float = 10000.0 # the real model is 1e7; at 8 rotated dims that rotates only the first pair visibly, so the toy uses 1e4 (--like-real restores 1e7) - rms_eps: float = 1e-6 - n_ctx_train: int = 4096 - nextn: bool = True - fused_gate_up: bool = False - fused_qkv: bool = False # attention layers: one attn_qkv instead of attn_q/attn_k/attn_v - expert_weights_scale: float | None = None # a stray key: llama.cpp's qwen35moe loader does not read it - quant_shexp: str | None = None # ggml type name for ffn_{gate,up,down}_shexp (e.g. "q8_0"); F32 when None - bf16_exact: bool = False # round ssm_alpha/ssm_beta/ffn_gate_inp/ffn_gate_inp_shexp to BF16-representable F32 - seed: int = 0 - - @property - def key_dim(self): return self.ssm_k_heads * self.ssm_state - @property - def value_dim(self): return self.ssm_v_heads * self.ssm_state - @property - def conv_dim(self): return 2 * self.key_dim + self.value_dim - def is_attn(self, il): return (il + 1) % self.interval == 0 - - def check(self): - assert self.ssm_v_heads % self.ssm_k_heads == 0 - assert sum(self.rope_sections) * 2 <= self.n_rot <= self.head_dim and self.n_rot % 2 == 0 - assert self.n_head % self.n_head_kv == 0 and self.n_expert_used <= self.n_expert - assert self.n_layer >= self.interval, "need at least one full-attention layer" - - -def split_sections(sec: list, slots: int) -> list: - """Largest-remainder split of `slots` sector slots (n_rot / 2 of them) in the proportions of `sec`.""" - tot = sum(sec) - raw = [s * slots / tot for s in sec] - fl = [int(x) for x in raw] - for i in sorted(range(len(sec)), key=lambda i: raw[i] - fl[i], reverse=True)[: slots - sum(fl)]: - fl[i] += 1 - return fl - - -def real_config(path: str) -> tuple[Cfg, dict]: - """Derive a toy Cfg from a real qwen35moe GGUF: keep what is a rule (rope base, eps, interval, conv - kernel, the ratios), divide what is a size. Returns (cfg, report-of-real-values).""" - from gguf_reader import GGUFFile - gf = GGUFFile(path) - m = gf.metadata - assert m["general.architecture"] == ARCH, f"{path}: architecture {m['general.architecture']!r}" - g = lambda k, d=None: m.get(f"{ARCH}.{k}", d) - hd, n_rot = g("attention.key_length"), g("rope.dimension_count") - sec = list(g("rope.dimension_sections", [11, 11, 10, 0])) - small_hd = hd // 8 - small_rot = n_rot * small_hd // hd - fl = split_sections(sec, small_rot // 2) - n_head, n_kv = g("attention.head_count"), g("attention.head_count_kv") - cfg = Cfg( - n_embd=g("embedding_length") // 32, n_layer=4, interval=g("full_attention_interval", 4), - n_vocab=128, n_expert=g("expert_count") // 32, n_expert_used=max(1, g("expert_used_count") // 4), - n_ff_exp=g("expert_feed_forward_length") // 16, n_ff_shexp=g("expert_shared_feed_forward_length") // 16, - ssm_k_heads=g("ssm.group_count") // 4, ssm_v_heads=g("ssm.time_step_rank") // 4, - ssm_state=g("ssm.state_size") // 8, ssm_conv=g("ssm.conv_kernel"), - n_head=n_head // 2, n_head_kv=max(1, n_kv // 2), head_dim=small_hd, n_rot=small_rot, - rope_sections=tuple(fl), rope_base=g("rope.freq_base"), rms_eps=g("attention.layer_norm_rms_epsilon"), - nextn=any(t.name.startswith(f"blk.{g('block_count') - 1}.nextn.") for t in gf.tensors), - fused_gate_up=any(".ffn_gate_up_exps." in t.name for t in gf.tensors), - fused_qkv=any(t.name == f"blk.{g('full_attention_interval', 4) - 1}.attn_qkv.weight" for t in gf.tensors), - ) - cfg.check() - real = {"block_count": g("block_count"), "tensors": [t.name for t in gf.tensors]} - return cfg, real - - -def norm_name(name: str, n_layer_real: int | None = None) -> str: - """blk.17.ffn_gate_exps.weight -> blk.N.ffn_gate_exps.weight, for comparing name sets.""" - import re - return re.sub(r"^blk\.\d+\.", "blk.N.", name) - - -# ------------------------------------------------------------------------------------------------ weights -def build_tensors(c: Cfg) -> list[tuple[str, np.ndarray]]: - """(gguf name, numpy array in (out, in[, experts]) order) for every tensor, in the order llama.cpp's - loader declares them. Numpy shape is the reverse of the GGUF ne list.""" - rng = np.random.default_rng(c.seed) - f32 = np.float32 - - def lin(out, inn, gain=1.0): - return (rng.standard_normal((out, inn)) * gain / np.sqrt(inn)).astype(f32) - - def exps(e, out, inn, gain=1.0): - return (rng.standard_normal((e, out, inn)) * gain / np.sqrt(inn)).astype(f32) - - def normw(n): # llama.cpp multiplies by the stored weight directly (no +1) - return (1.0 + 0.2 * rng.standard_normal(n)).astype(f32) - - T: list[tuple[str, np.ndarray]] = [] - add = lambda n, a: T.append((n, np.ascontiguousarray(a, dtype=f32))) - d = c.n_embd - - def bf16(a): - """Round-to-nearest-even to BF16, returned as F32 (the engine's bf16_from_f32, strata/kernels/bf16_bits.hpp). - The pack rounds these F32 tensors to BF16 exactly when the low 16 bits are already zero (upstream-tooling.md - section 4), so a fixture written this way is one the engine reads bit-for-bit.""" - a = np.ascontiguousarray(a, dtype=f32) - if not c.bf16_exact: - return a - u = a.view(np.uint32) - u = (u + ((u >> 16) & 1) + np.uint32(0x7FFF)) & np.uint32(0xFFFF0000) - return u.view(f32) - - add("token_embd.weight", rng.standard_normal((c.n_vocab, d))) - add("output_norm.weight", normw(d)) - add("output.weight", lin(c.n_vocab, d, 2.0)) - - def moe(p): - add(f"{p}.ffn_gate_inp.weight", bf16(lin(c.n_expert, d, 3.0))) # spread logits so top-k is decisive - add(f"{p}.ffn_down_exps.weight", exps(c.n_expert, d, c.n_ff_exp)) - if c.fused_gate_up: # ne [n_embd, 2*ff, E]: gate rows then up rows - add(f"{p}.ffn_gate_up_exps.weight", exps(c.n_expert, 2 * c.n_ff_exp, d)) - else: - add(f"{p}.ffn_gate_exps.weight", exps(c.n_expert, c.n_ff_exp, d)) - add(f"{p}.ffn_up_exps.weight", exps(c.n_expert, c.n_ff_exp, d)) - add(f"{p}.ffn_gate_inp_shexp.weight", bf16(rng.standard_normal(d) / np.sqrt(d) * 2.0)) - add(f"{p}.ffn_gate_shexp.weight", lin(c.n_ff_shexp, d)) - add(f"{p}.ffn_up_shexp.weight", lin(c.n_ff_shexp, d)) - add(f"{p}.ffn_down_shexp.weight", lin(d, c.n_ff_shexp)) - - def attn(p): - qw, kw = c.head_dim * c.n_head * 2, c.head_dim * c.n_head_kv - if c.fused_qkv: - add(f"{p}.attn_qkv.weight", lin(qw + 2 * kw, d)) - else: - add(f"{p}.attn_q.weight", lin(qw, d)) - add(f"{p}.attn_k.weight", lin(kw, d)) - add(f"{p}.attn_v.weight", lin(kw, d)) - add(f"{p}.attn_output.weight", lin(d, c.head_dim * c.n_head)) - add(f"{p}.attn_q_norm.weight", normw(c.head_dim)) - add(f"{p}.attn_k_norm.weight", normw(c.head_dim)) - - for il in range(c.n_layer): - p = f"blk.{il}" - add(f"{p}.attn_norm.weight", normw(d)) - add(f"{p}.post_attention_norm.weight", normw(d)) - if c.is_attn(il): - attn(p) - else: - add(f"{p}.attn_qkv.weight", lin(c.conv_dim, d)) - add(f"{p}.attn_gate.weight", lin(c.value_dim, d)) - add(f"{p}.ssm_conv1d.weight", rng.standard_normal((c.conv_dim, c.ssm_conv)) * 0.6) - # real layer 0: ssm_a in [-72, -0.02] (already -exp(A_log), so negative), ssm_dt.bias in [-5.3, 15.6]; the toy - # spans both regimes (fast-forgetting and long-memory heads) over the 11-40 token sequences the tests use - add(f"{p}.ssm_dt.bias", rng.uniform(-5.0, 1.0, c.ssm_v_heads)) - add(f"{p}.ssm_a", -np.exp(rng.uniform(np.log(0.05), np.log(20.0), c.ssm_v_heads))) - add(f"{p}.ssm_beta.weight", bf16(lin(c.ssm_v_heads, d, 1.5))) - add(f"{p}.ssm_alpha.weight", bf16(lin(c.ssm_v_heads, d, 1.0))) - add(f"{p}.ssm_norm.weight", normw(c.ssm_state)) - add(f"{p}.ssm_out.weight", lin(d, c.value_dim)) - moe(p) - - if c.nextn: - p = f"blk.{c.n_layer}" - add(f"{p}.attn_norm.weight", normw(d)) - add(f"{p}.post_attention_norm.weight", normw(d)) - attn(p) - moe(p) - add(f"{p}.nextn.eh_proj.weight", lin(d, 2 * d)) - add(f"{p}.nextn.enorm.weight", normw(d)) - add(f"{p}.nextn.hnorm.weight", normw(d)) - add(f"{p}.nextn.shared_head_norm.weight", normw(d)) - return T - - -# ------------------------------------------------------------------------------------------------ vocab -def byte_unicode() -> list[str]: - """GPT-2 bytes_to_unicode for bytes 0..127 (printable ASCII maps to itself).""" - bs = list(range(ord("!"), ord("~") + 1)) + list(range(0xA1, 0xAD)) + list(range(0xAE, 0x100)) - cs = bs[:] - n = 0 - for b in range(256): - if b not in bs: - bs.append(b) - cs.append(256 + n) - n += 1 - m = dict(zip(bs, (chr(c) for c in cs))) - return [m[b] for b in range(128)] - - -def write(path: str, c: Cfg, comment: str = "") -> None: - c.check() - assert c.n_vocab == 128, "the toy vocabulary is the 128 ASCII byte tokens" - w = GGUFWriter(path, ARCH) - k = lambda s: f"{ARCH}.{s}" - w.add_name(f"qwen36-synth{comment}") - w.add_uint32(k("context_length"), c.n_ctx_train) - w.add_uint32(k("embedding_length"), c.n_embd) - w.add_uint32(k("block_count"), c.n_layer + (1 if c.nextn else 0)) - if c.nextn: - w.add_uint32(k("nextn_predict_layers"), 1) - w.add_uint32(k("attention.head_count"), c.n_head) - w.add_uint32(k("attention.head_count_kv"), c.n_head_kv) - w.add_uint32(k("attention.key_length"), c.head_dim) - w.add_uint32(k("attention.value_length"), c.head_dim) - w.add_float32(k("attention.layer_norm_rms_epsilon"), c.rms_eps) - w.add_uint32(k("rope.dimension_count"), c.n_rot) - w.add_array(k("rope.dimension_sections"), list(c.rope_sections) + [0] * (4 - len(c.rope_sections))) - w.add_float32(k("rope.freq_base"), c.rope_base) - w.add_uint32(k("expert_count"), c.n_expert) - w.add_uint32(k("expert_used_count"), c.n_expert_used) - w.add_uint32(k("expert_feed_forward_length"), c.n_ff_exp) - w.add_uint32(k("expert_shared_feed_forward_length"), c.n_ff_shexp) - w.add_uint32(k("ssm.conv_kernel"), c.ssm_conv) - w.add_uint32(k("ssm.state_size"), c.ssm_state) - w.add_uint32(k("ssm.group_count"), c.ssm_k_heads) - w.add_uint32(k("ssm.time_step_rank"), c.ssm_v_heads) - w.add_uint32(k("ssm.inner_size"), c.value_dim) - w.add_uint32(k("full_attention_interval"), c.interval) - if c.expert_weights_scale is not None: - w.add_float32(k("expert_weights_scale"), c.expert_weights_scale) - w.add_file_type(0) # LLAMA_FTYPE_ALL_F32 - - toks = byte_unicode() - w.add_tokenizer_model("gpt2") - w.add_tokenizer_pre("default") - w.add_token_list(toks) - w.add_token_types([1] * c.n_vocab) # NORMAL - w.add_token_merges(["Ā ā"]) # loader requires the key; this pair never occurs in ASCII text - w.add_bos_token_id(0) - w.add_eos_token_id(3) - w.add_add_bos_token(False) - - qt = None - if c.quant_shexp: - from gguf import GGMLQuantizationType, quants - qt = GGMLQuantizationType[c.quant_shexp.upper()] - for name, arr in build_tensors(c): - if qt is not None and any(name.endswith(f".{r}_shexp.weight") for r in ("ffn_gate", "ffn_up", "ffn_down")): - w.add_tensor(name, quants.quantize(arr, qt), raw_dtype=qt) # gguf-py's reference quantizer (bit-identical to ggml) - else: - w.add_tensor(name, arr) - w.write_header_to_file() - w.write_kv_data_to_file() - w.write_tensors_to_file() - w.close() - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - ap.add_argument("out") - ap.add_argument("--seed", type=int, default=0) - ap.add_argument("--like-real", metavar="REAL.gguf", help="take rope/eps/interval/ratios and the tensor-name set from a real qwen35moe GGUF") - ap.add_argument("--heads", metavar="N,KV", help="attention heads and KV heads (default 2,1; use 4,2 to make GQA non-degenerate)") - ap.add_argument("--head-dim", type=int, metavar="D", help="attention head_dim (default 32); n_rot becomes D/4, the IMRoPE sections the real " - "[11,11,10,0] in proportion, rope base 1e7: 256 is the engine's kernel width (step 3's attention parity)") - ap.add_argument("--no-nextn", action="store_true", help="omit the MTP block (the real UD-IQ3_XXS file has none)") - ap.add_argument("--fused-gate-up", action="store_true", help="ffn_gate_up_exps instead of ffn_gate_exps + ffn_up_exps") - ap.add_argument("--fused-qkv", action="store_true", help="attention layers carry attn_qkv instead of attn_q/k/v") - ap.add_argument("--expert-weights-scale", type=float, help="write a stray qwen35moe.expert_weights_scale key (llama.cpp ignores it)") - ap.add_argument("--gdn", metavar="K,V,S", help="GDN k-heads, v-heads, state size (default 4,8,16; the engine's kernels need S = 128)") - ap.add_argument("--experts", metavar="E,K", help="expert count and top-k (default 8,2; the real model is 256,8)") - ap.add_argument("--shexp-ff", type=int, metavar="N", help="shared expert width (default 32; the real model is 512)") - ap.add_argument("--quant-shexp", metavar="TYPE", help="write ffn_{gate,up,down}_shexp in this ggml type (e.g. q8_0) instead of F32") - ap.add_argument("--bf16-exact", action="store_true", - help="ssm_alpha, ssm_beta, ffn_gate_inp, ffn_gate_inp_shexp hold BF16-representable F32 values (what the engine reads them as)") - a = ap.parse_args() - real = None - if a.like_real: - c, real = real_config(a.like_real) - else: - c = Cfg() - c.seed = a.seed - if a.heads: - c.n_head, c.n_head_kv = (int(x) for x in a.heads.split(",")) - if a.head_dim: - c.head_dim, c.n_rot, c.rope_base = a.head_dim, a.head_dim // 4, 1e7 - c.rope_sections = tuple(split_sections([11, 11, 10, 0], c.n_rot // 2)) - if a.no_nextn: - c.nextn = False - c.fused_gate_up |= a.fused_gate_up - c.fused_qkv |= a.fused_qkv - c.expert_weights_scale = a.expert_weights_scale - if a.gdn: - c.ssm_k_heads, c.ssm_v_heads, c.ssm_state = (int(x) for x in a.gdn.split(",")) - if a.experts: - c.n_expert, c.n_expert_used = (int(x) for x in a.experts.split(",")) - if a.shexp_ff: - c.n_ff_shexp = a.shexp_ff - c.quant_shexp = a.quant_shexp - c.bf16_exact = a.bf16_exact - write(a.out, c, " like-real" if real else "") - names = {norm_name(n) for n, _ in build_tensors(c)} - print(f"wrote {a.out}: {len(build_tensors(c))} tensors, block_count {c.n_layer + int(c.nextn)}") - if real: - rn = {norm_name(n) for n in real["tensors"]} - # the real file's trunk blocks vs ours; nextn tensors only exist in blk. - extra, missing = sorted(names - rn), sorted(rn - names) - print(f"name-set check vs {a.like_real}: {len(names)} synthetic patterns, {len(rn)} real") - print(" only in synthetic:", extra or "none") - print(" only in real :", missing or "none") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/qwen36_teacher_llama.cpp b/tools/qwen36_teacher_llama.cpp deleted file mode 100644 index 027c1cd..0000000 --- a/tools/qwen36_teacher_llama.cpp +++ /dev/null @@ -1,199 +0,0 @@ -// tools/qwen36_teacher_llama.cpp - llama.cpp's own greedy continuation of a prompt, with the head's logits at every -// generated position and the routed experts at probed layers: the reference the Qwen3.6 runner is held to on the real -// files (docs/qwen36-port/step4-runner.md; the comparison is tools/qwen36_compare_logits.py). -// -// Build against a llama.cpp build of the pinned submodule (CUDA or CPU), e.g. on VM 221: -// c++ -std=c++17 -O1 tools/qwen36_teacher_llama.cpp -o qwen36-teacher -I$LL/include -I$LL/ggml/include \ -// $B/src/libllama.a $B/ggml/src/libggml.a $B/ggml/src/libggml-cpu.a $B/ggml/src/ggml-cuda/libggml-cuda.a \ -// $B/ggml/src/libggml-base.a -lcudart -lcublas -lcublasLt -lcuda -lgomp -lpthread -ldl -lm -// -// qwen36-teacher MODEL.gguf OUTDIR --prompt-file FILE [--n-gen 64] [--ngl 99] [--ctx 8192] [--probe 0,3,20,39] -// qwen36-teacher MODEL.gguf --detok FILE the ids in FILE (commas or whitespace) as text, to stdout -// --prompt-ids FILE the prompt as token ids (commas or whitespace) instead of --prompt-file's text -// --force-ids FILE teacher forcing: row j's logits are written, then FILE's j-th token is decoded instead of the -// argmax (continuation.txt still holds the argmax per row); --n-gen is capped at FILE's length -// -// Writes OUTDIR/prompt_ids.txt (the prompt's token ids, parse_special on: the ChatML tags of the regina prompts are -// tokens), OUTDIR/continuation.txt (the N greedy tokens), OUTDIR/logits.f32 (N rows of n_vocab F32: row j is the -// distribution the j-th generated token was picked from, i.e. the position n_prompt - 1 + j), OUTDIR/meta.txt -// ("n_vocab N n_prompt P n_gen G"), OUTDIR/routes.txt (" e0 .. e7" for the probed layers of every -// generated row; the prompt batch is not traced) and OUTDIR/text.txt (the continuation as text). Greedy means the -// argmax of the F32 logits; the KV cache is F16 as the engine's --kv fp16 is. -#include "llama.h" -#include "ggml.h" -#include "ggml-backend.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { -struct Routes { - std::set probe; - FILE* out = nullptr; - int row = -1; // the generated row being decoded (-1: the prompt batch, not traced) -}; -bool cb_routes(struct ggml_tensor* t, bool ask, void* ud) { - if (ask) return true; - auto* r = (Routes*) ud; - if (r->row < 0 || r->out == nullptr || std::strncmp(t->name, "ffn_moe_topk-", 13) != 0) return true; - const int layer = std::atoi(t->name + 13); - if (!r->probe.count(layer) || t->type != GGML_TYPE_I32) return true; - const int64_t k = t->ne[0], n = t->ne[1]; - std::vector ids((size_t) (k * n)); - ggml_backend_tensor_get(t, ids.data(), 0, ids.size() * sizeof(int32_t)); - for (int64_t i = 0; i < n; ++i) { - std::fprintf(r->out, "%d %d", r->row, layer); - for (int64_t j = 0; j < k; ++j) std::fprintf(r->out, " %d", ids[(size_t) (i * k + j)]); - std::fprintf(r->out, "\n"); - } - return true; -} -std::vector read_ids(const std::string& path) { - std::ifstream in(path); - std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); - for (char& c : text) if (c == ',') c = ' '; - std::istringstream is(text); - std::vector v; - for (long long x; is >> x;) v.push_back((llama_token) x); - return v; -} -std::string piece(const llama_vocab* vocab, llama_token t) { - char buf[512]; - const int n = llama_token_to_piece(vocab, t, buf, sizeof buf, 0, true); - return n > 0 ? std::string(buf, (size_t) n) : std::string(); -} -} // namespace - -int main(int argc, char** argv) { - if (argc < 3) { - std::fprintf(stderr, "usage: %s MODEL.gguf OUTDIR --prompt-file FILE [--n-gen N] [--ngl N] [--ctx N] [--probe L,L,..]\n" - " %s MODEL.gguf --detok FILE\n", argv[0], argv[0]); - return 1; - } - const std::string model_path = argv[1]; - std::string outdir, prompt_file, prompt_ids, force_ids, detok; - int n_gen = 64, ngl = 99, n_ctx = 8192; - std::set probe = {0, 3, 20, 39}; - for (int i = 2; 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(1); } return argv[++i]; }; - if (a == "--prompt-file") prompt_file = next(); - else if (a == "--prompt-ids") prompt_ids = next(); - else if (a == "--force-ids") force_ids = next(); - else if (a == "--n-gen") n_gen = std::atoi(next()); - else if (a == "--ngl") ngl = std::atoi(next()); - else if (a == "--ctx") n_ctx = std::atoi(next()); - else if (a == "--detok") detok = next(); - else if (a == "--probe") { - probe.clear(); - std::string s = next(); - for (char& c : s) if (c == ',') c = ' '; - std::istringstream is(s); - for (int l; is >> l;) probe.insert(l); - } else if (outdir.empty()) outdir = a; - else { std::fprintf(stderr, "unknown argument %s\n", a.c_str()); return 1; } - } - llama_backend_init(); - llama_model_params mp = llama_model_default_params(); - mp.n_gpu_layers = detok.empty() ? ngl : 0; - llama_model* model = llama_model_load_from_file(model_path.c_str(), mp); - if (!model) { std::fprintf(stderr, "model load failed\n"); return 1; } - const llama_vocab* vocab = llama_model_get_vocab(model); - if (!detok.empty()) { - for (llama_token t : read_ids(detok)) std::fputs(piece(vocab, t).c_str(), stdout); - std::fputc('\n', stdout); - llama_model_free(model); - llama_backend_free(); - return 0; - } - if (outdir.empty() || (prompt_file.empty() && prompt_ids.empty())) { std::fprintf(stderr, "OUTDIR and --prompt-file or --prompt-ids are required\n"); return 1; } - mkdir(outdir.c_str(), 0755); - std::vector toks; - int n = 0; - if (!prompt_ids.empty()) { - toks = read_ids(prompt_ids); - n = (int) toks.size(); - if (n <= 0) { std::fprintf(stderr, "no ids in %s\n", prompt_ids.c_str()); return 1; } - prompt_file = prompt_ids; - } else { - std::ifstream pf(prompt_file); - std::string prompt((std::istreambuf_iterator(pf)), std::istreambuf_iterator()); - while (!prompt.empty() && prompt.back() == '\n') prompt.pop_back(); // the files end in one newline the prompt does not - toks.resize(prompt.size() + 16); - n = llama_tokenize(vocab, prompt.c_str(), (int32_t) prompt.size(), toks.data(), (int32_t) toks.size(), false, true); - if (n < 0) { toks.resize((size_t) -n); n = llama_tokenize(vocab, prompt.c_str(), (int32_t) prompt.size(), toks.data(), (int32_t) toks.size(), false, true); } - if (n <= 0) { std::fprintf(stderr, "tokenize failed\n"); return 1; } - toks.resize((size_t) n); - } - std::vector forced; - if (!force_ids.empty()) { - forced = read_ids(force_ids); - if (forced.empty()) { std::fprintf(stderr, "no ids in %s\n", force_ids.c_str()); return 1; } - n_gen = std::min(n_gen, (int) forced.size()); - } - const int n_vocab = llama_vocab_n_tokens(vocab); - - Routes routes; - routes.probe = probe; - routes.out = std::fopen((outdir + "/routes.txt").c_str(), "w"); - llama_context_params cp = llama_context_default_params(); - cp.n_ctx = (uint32_t) n_ctx; - cp.n_batch = cp.n_ubatch = 2048; - cp.type_k = GGML_TYPE_F16; - cp.type_v = GGML_TYPE_F16; - cp.cb_eval = cb_routes; - cp.cb_eval_user_data = &routes; - llama_context* ctx = llama_init_from_model(model, cp); - if (!ctx) { std::fprintf(stderr, "context init failed\n"); return 1; } - - // the prompt, logits for its last position only - routes.row = -1; - for (int i = 0; i < n; i += 2048) { - const int m = std::min(2048, n - i); - if (llama_decode(ctx, llama_batch_get_one(toks.data() + i, m))) { std::fprintf(stderr, "prompt decode failed\n"); return 1; } - } - FILE* lf = std::fopen((outdir + "/logits.f32").c_str(), "wb"); - std::vector gen; - std::string text; - for (int j = 0; j < n_gen; ++j) { - const float* lg = llama_get_logits_ith(ctx, -1); - if (lg == nullptr) { std::fprintf(stderr, "no logits at row %d\n", j); return 1; } - std::fwrite(lg, sizeof(float), (size_t) n_vocab, lf); - const llama_token t = (llama_token) (std::max_element(lg, lg + n_vocab) - lg); - gen.push_back(t); - text += piece(vocab, t); - if (j + 1 == n_gen) break; - routes.row = j + 1; // the next decode's logits are row j + 1 - llama_token one = forced.empty() ? t : forced[(size_t) j]; - if (llama_decode(ctx, llama_batch_get_one(&one, 1))) { std::fprintf(stderr, "decode failed at row %d\n", j + 1); return 1; } - } - std::fclose(lf); - std::fclose(routes.out); - { - std::ofstream o(outdir + "/prompt_ids.txt"); - for (size_t i = 0; i < toks.size(); ++i) o << (i ? "," : "") << toks[i]; - o << "\n"; - std::ofstream c(outdir + "/continuation.txt"); - for (size_t i = 0; i < gen.size(); ++i) c << (i ? "," : "") << gen[i]; - c << "\n"; - std::ofstream m(outdir + "/meta.txt"); - m << "n_vocab " << n_vocab << " n_prompt " << n << " n_gen " << gen.size() << "\n"; - std::ofstream tx(outdir + "/text.txt"); - tx << text << "\n"; - } - std::printf("%s: %d prompt tokens, %zu greedy tokens, logits %zu x %d in %s\n", prompt_file.c_str(), n, gen.size(), - gen.size(), n_vocab, outdir.c_str()); - std::printf("---\n%s\n---\n", text.c_str()); - llama_free(ctx); - llama_model_free(model); - llama_backend_free(); - return 0; -} diff --git a/tools/strata_pack.py b/tools/strata_pack.py deleted file mode 100644 index 31fbe22..0000000 --- a/tools/strata_pack.py +++ /dev/null @@ -1,423 +0,0 @@ -"""Strata P1.S6/S7 - the pack builder and verifier. - -This is `strata-pack build` / `strata-pack verify` / `strata-pack info`. It is the Python implementation of -`docs/pack-format.md`; the C++ `tools/strata-pack` is a port of it, and if the two disagree the C++ is wrong. - -WHY PYTHON FIRST. The canonicalisation in `tools/canonical_xcheck.py` is measured bit-exact over every block -of every tensor (757,139,840 blocks across 1021 tensors, plus Q2_0), against gguf-py and, for Q2_0, backed by -`dequant_xcheck` against ggml itself. That makes the Python mapping table the specification of record. The -pack is Phase 2's prerequisite and can be produced from it today; the port then has a golden artifact to be -tested against instead of being the thing everything else waits on. - -THE ONE RULE. A pack is only valid if, for every tensor, `decode(pack) == dequant_ggml(source)` BIT FOR BIT. -`verify` is that test and it is not optional - it re-reads the written pack from disk and compares it against -the source shard. A pack that has not passed `verify` does not exist. - -SCALE PRECISION. A canonical scale is an FP32 product (`fl(d*sc)`), which is generally NOT representable in -FP16. The packer therefore stores scales as FP16 only when the round-trip is exact and as FP32 otherwise, and -records which per tensor. It never has to decide correctly: `verify` re-checks bit-exactness, so a wrong -choice is a failed build rather than a silently lossy pack. The expert arena is the exception and is FP16 by -construction - architecture §3.2 fixes the blob at exactly 1,382,400 bytes and pack_layer.py asserts it. -""" -from __future__ import annotations - -import argparse -import hashlib -import json -import pathlib -import struct -import sys - -import numpy as np - -HERE = pathlib.Path(__file__).resolve().parent -sys.path.insert(0, str(HERE)) -sys.path.insert(0, str(HERE.parent / "ref")) - -import gguf_reader as G # noqa: E402 -import pack_layer as PL # noqa: E402 -from canonical_xcheck import (MAPPINGS, KV_IQ4NL, open_shard, # noqa: E402 - data_section_offset, reference_values) - -FORMAT_VERSION = 1 -ALIGN = 64 # every plane starts on a 64-byte boundary (P1.S7) -_HERE = pathlib.Path(__file__).resolve() -STRATA = _HERE.parents[min(3, len(_HERE.parents) - 1)] # the development layout; build takes the shard from --gguf -SHARD2 = STRATA / "Q2_0" / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf" - -EXPERT_RE = ("ffn_gate_exps.weight", "ffn_up_exps.weight", "ffn_down_exps.weight") -EMBD_NAME = "token_embd.weight" - - -def is_expert(name: str) -> bool: - return name.startswith("blk.") and name.endswith(EXPERT_RE) - - -def code_bits(form: str) -> int: - return {"S2": 2, "S4": 4, "S8": 8}[form] - - -def pack_codes(codes: np.ndarray, bits: int) -> bytes: - """Pack one code per element into bytes, LSB-first, `8//bits` codes per byte. - - This is Q2_0's own convention (4 codes per byte, byte j/4, bits (j%4)*2), kept for every form so the - kernel has one unpacking loop rather than one per source type. - """ - flat = codes.reshape(-1).astype(np.uint8) - if bits == 8: - return flat.tobytes() - per = 8 // bits - if flat.size % per: - raise ValueError("code count %d is not a multiple of %d per byte" % (flat.size, per)) - g = flat.reshape(-1, per).astype(np.uint16) - out = np.zeros(g.shape[0], dtype=np.uint16) - for k in range(per): - out |= (g[:, k] & ((1 << bits) - 1)) << (k * bits) - return out.astype(np.uint8).tobytes() - - -def unpack_codes(buf: bytes, bits: int, n: int) -> np.ndarray: - if bits == 8: - return np.frombuffer(buf, dtype=np.uint8)[:n].copy() - per = 8 // bits - b = np.frombuffer(buf, dtype=np.uint8) - out = np.empty((b.size, per), dtype=np.uint8) - for k in range(per): - out[:, k] = (b >> (k * bits)) & ((1 << bits) - 1) - return out.reshape(-1)[:n].copy() - - -def choose_scale_dtype(scales: np.ndarray) -> tuple[np.ndarray, bool]: - """FP16 when the round-trip is exact, else FP32. Returns (bytes, is_fp16).""" - as16 = scales.astype(np.float16) - if np.array_equal(as16.astype(np.float32), scales): - return as16.tobytes(), True - return scales.astype(" the canonical planes, as (codes, scales, offsets_or_None, mapping).""" - m = MAPPINGS[tname] - parts = m.enc(raw) - if len(parts) == 3: - return parts[0], parts[1], parts[2], m - return parts[0], parts[1], None, m - - -def tensor_entry(name, meta, tname, raw, seg_offset): - """Encode one tensor and return (blob_bytes, manifest_entry).""" - m = MAPPINGS[tname] - - body = bytearray() - base = seg_offset - - def put(b: bytes) -> dict: - nonlocal body - pad = (-len(body)) % ALIGN - body += b"\0" * pad - off = base + len(body) - body += b - return {"offset": off, "bytes": len(b)} - - common = { - "name": name, "source_type": tname, "form": m.form, "codebook": m.codebook, - "code_bias": m.code_bias, "has_offset": m.has_offset, - "block_elems": m.block_elems, "block_bytes": m.block_bytes, "group_elems": m.group_elems, - "shape": list(meta.shape), "source_offset": meta.offset, - } - - # ---- P16/P32 are pass-through: one value plane, no codes, no scale, no offset - if m.form in ("P16", "P32"): - vals = np.ascontiguousarray(m.dec(m.enc(raw)), dtype=np.float32).reshape(-1) - if m.form == "P32": - vb, v16 = vals.astype(" np.ndarray: - """Decode a tensor from the pack, using ONLY what the manifest says. - - Deliberately manifest-driven: if the manifest does not carry enough to decode the tensor, this cannot - silently fall back on knowledge of the source type, and the omission becomes a failure here. - """ - if ent["form"] in ("P16", "P32"): - vb = head[ent["values"]["offset"]: ent["values"]["offset"] + ent["values"]["bytes"]] - return np.frombuffer(vb, dtype=" str: - h = hashlib.sha256() - with open(path, "rb") as f: - while True: - b = f.read(chunk) - if not b: - break - h.update(b) - return h.hexdigest() - - -def build(gguf: pathlib.Path, out_dir: pathlib.Path, n_layers: int | None, skip_hash: bool) -> int: - out_dir.mkdir(parents=True, exist_ok=True) - g = G.GGUFFile(gguf) - head, flen = open_shard(gguf) - data_off = data_section_offset(g, flen) - print("source %s: %d tensors, data at %d" % (gguf.name, len(g.tensors), data_off)) - - n_layers = 48 if n_layers is None else n_layers - man = { - "format": "strata-pack", "format_version": FORMAT_VERSION, - "source": {"shard1": str(gguf), "shard2": str(SHARD2)}, - "n_layers": n_layers, "align": ALIGN, - "codebooks": {"IQ4NL": [float(x) for x in KV_IQ4NL]}, - "tensors": {}, "experts": {}, "n_experts_per_layer": PL.NE, - } - - # ---- experts.bin: delegated to pack_layer so the blob layout has exactly ONE implementation - # pack_layer reads its own hardcoded SHARD1, so a different --gguf would silently take the expert arena - # from a different file than the dense tensors. Refuse rather than produce a mixed-source pack. - # the expert arena and the dense tensors come from the same file: point pack_layer at it - PL.SHARD1 = pathlib.Path(gguf).resolve() - shard2 = pathlib.Path(str(PL.SHARD1).replace("00001-of-00002", "00002-of-00002")) - man["source"]["shard2"] = str(shard2) - exp_path = out_dir / "experts.bin" - print("experts.bin: %d layers, %.2f GiB" % (n_layers, n_layers * PL.NE * PL.BLOB_BYTES / 2**30)) - em = PL.build(n_layers, exp_path) - man["experts"] = {"blob_bytes": em["blob_bytes"], "offsets": em["offsets"], - "layers": em["layers"], "total_bytes": em["total_bytes"], - "scales_fp16": True, "source_type": "Q2_0", "form": "S2"} - - # ---- dense.bin and embd.bin - dense = [] - embd = [] - for t in g.tensors: - if is_expert(t.name): - continue - (embd if t.name == EMBD_NAME else dense).append(t) - - for fname, group in (("dense.bin", dense), ("embd.bin", embd)): - path = out_dir / fname - seg_base = 0 - with open(path, "wb") as fh: - for t in group: - if t.type_name not in MAPPINGS: - print(" %s: NO MAPPING for %s - refusing to build" % (t.name, t.type_name)) - return 1 - raw = head[data_off + t.offset: data_off + t.offset + (t.expected_bytes() or 0)] - if len(raw) != (t.expected_bytes() or 0): - print(" %s: SHORT READ - refusing to build" % t.name) - return 1 - blob, ent = tensor_entry(t.name, t, t.type_name, raw, seg_base) - ent["file"] = fname - fh.write(blob) - seg_base += len(blob) - man["tensors"][t.name] = ent - print("%s: %d tensors, %.2f GiB" % (fname, len(group), path.stat().st_size / 2**30)) - - man["files"] = {"experts.bin": exp_path.stat().st_size, - "dense.bin": (out_dir / "dense.bin").stat().st_size, - "embd.bin": (out_dir / "embd.bin").stat().st_size} - if not skip_hash: - print("hashing shards (this is the slow part)...") - man["source"]["shard1_sha256"] = sha256(gguf) - man["source"]["shard2_sha256"] = sha256(shard2) if shard2.exists() else None - # shard 2 is NOT copied: the PLE table stays where it is and the manifest records how to find it - if shard2.exists(): - g2 = G.GGUFFile(shard2) - t2 = [t for t in g2.tensors if t.name == "per_layer_token_embd.weight"][0] - man["shard2_tensor"] = {"name": t2.name, "type": t2.type_name, "shape": list(t2.shape), - "offset": t2.offset, "elements": t2.elements, - "path": str(shard2)} - (out_dir / "manifest.json").write_text(json.dumps(man, indent=1), encoding="utf-8") - print("manifest.json: %d tensor entries" % len(man["tensors"])) - return 0 - - -def rebuild_role(blob: bytes, role: str) -> bytes: - """Rebuild one role's raw Q2_0 bytes from an expert blob - the exact inverse of pack_layer's layout. - - The arena stores codes and scales in SEPARATE PLANES and interleaves gate/up ROWS (g0,u0,g1,u1,...), so - a verifier that cannot invert that cannot check the arena. Written as the inverse on purpose: this is - the only independent statement about the blob layout in the tree, and if it and `pack_layer` were the - same code the arena would be unverified by construction. - """ - O, out = PL.OFF, bytearray() - n_blk = PL.H * PL.FF // PL.QK - for blk in range(n_blk): - if role == "down": - row, b_in = blk // PL.SCALES_D, blk % PL.SCALES_D - co = O["down_codes"] + row * PL.ROW_BYTES_D + b_in * 16 - so = O["down_scales"] + (row * PL.SCALES_D + b_in) * 2 - else: - row, b_in = blk // PL.SCALES_GU, blk % PL.SCALES_GU - slot = 2 * row + (0 if role == "gate" else 1) - co = O["gate_up_codes"] + slot * PL.ROW_BYTES_GU + b_in * 16 - so = O["gate_up_scales"] + (slot * PL.SCALES_GU + b_in) * 2 - out += blob[so:so + 2] # fp16 d first, as block_q2_0 has it - out += blob[co:co + 16] # then the 16 packed code bytes - return bytes(out) - - -def verify_experts(gguf: pathlib.Path, out_dir: pathlib.Path, man: dict, every: int) -> int: - """Verify the expert arena: 85% of the pack by bytes and the part Phase 2 reads 480x per token.""" - g = G.GGUFFile(gguf) - head, flen = open_shard(gguf) - data_off = data_section_offset(g, flen) - by_name = {t.name: t for t in g.tensors} - exp_mm, _ = open_shard(out_dir / "experts.bin") - blob = man["experts"]["blob_bytes"] - n_layers = man["n_layers"] - checked = bad = 0 - for layer in range(n_layers): - for e in range(0, PL.NE, every): - base = (layer * PL.NE + e) * blob - b = exp_mm[base:base + blob] - for role in ("gate", "up", "down"): - t = by_name["blk.%d.ffn_%s_exps.weight" % (layer, role)] - per_expert = t.elements // PL.NE - nbytes = per_expert * PL.BLOCK_BYTES // PL.QK - src = head[data_off + t.offset + e * nbytes: data_off + t.offset + (e + 1) * nbytes] - ref = reference_values("Q2_0", src) - got = MAPPINGS["Q2_0"].dec(canonicalise(t.name, "Q2_0", rebuild_role(b, role))[:2]) - checked += 1 - if not np.array_equal(ref, got): - print(" layer %d expert %d %-4s *** MISMATCH *** max|d| %.3e" - % (layer, e, role, np.abs(ref.astype(np.float64) - got.astype(np.float64)).max())) - bad += 1 - print("experts: %d layer/expert/role checks (%d layers, every %dth expert), %d bad" - % (checked, n_layers, every, bad)) - return bad - - -def verify(gguf: pathlib.Path, out_dir: pathlib.Path, limit: int | None, expert_every: int) -> int: - """P1.T3 over the pack: decode it from disk and compare with the source, bit for bit.""" - man = json.loads((out_dir / "manifest.json").read_text(encoding="utf-8")) - # A full verify also reads back the source hash build recorded (absent after --skip-hash, which is how setup - # builds): a pack compared against a different shard than it was built from is a mismatch, not a decode bug. - want = (man.get("source") or {}).get("shard1_sha256") - if want and limit is None: - got = sha256(gguf) - if got != want: - print("%s: sha256 %s, but the pack was built from %s" % (gguf.name, got, want)) - print("tools/strata_pack.py verify FAIL") - return 1 - g = G.GGUFFile(gguf) - head, flen = open_shard(gguf) - data_off = data_section_offset(g, flen) - by_name = {t.name: t for t in g.tensors} - files = {} - bad = 0 - n_t = n_el = 0 - for i, (name, ent) in enumerate(sorted(man["tensors"].items())): - if limit is not None and i >= limit: - break - if ent["file"] not in files: - files[ent["file"]] = open_shard(out_dir / ent["file"])[0] - t = by_name[name] - raw = head[data_off + t.offset: data_off + t.offset + (t.expected_bytes() or 0)] - ref = reference_values(t.type_name, raw) - got = decode_entry(files[ent["file"]], ent) - n_t += 1 - n_el += ref.size - if ref.shape != got.shape or not np.array_equal(ref, got): - d = np.abs(ref.astype(np.float64) - got.astype(np.float64)) if ref.shape == got.shape else None - print(" %-40s *** MISMATCH *** %s" % (name, ("max|d| %.3e" % d.max()) if d is not None else - "shape %s vs %s" % (ref.shape, got.shape))) - bad += 1 - elif i < 3 or i % 200 == 0: - print(" %-40s bit-exact (%d elements, %s)" % (name, ref.size, ent["form"])) - print() - print("verify: %d tensors, %d elements, %d bad" % (n_t, n_el, bad)) - if expert_every > 0: - bad += verify_experts(gguf, out_dir, man, expert_every) - print("tools/strata_pack.py verify " + ("PASS" if bad == 0 else "FAIL")) - return 0 if bad == 0 else 1 - - -def info(out_dir: pathlib.Path) -> int: - man = json.loads((out_dir / "manifest.json").read_text(encoding="utf-8")) - print("strata-pack v%d layers=%d" % (man["format_version"], man["n_layers"])) - for f, n in man.get("files", {}).items(): - print(" %-12s %12.3f GiB" % (f, n / 2**30)) - forms = {} - for e in man["tensors"].values(): - forms[e["form"]] = forms.get(e["form"], 0) + 1 - print(" dense/embd by form: %s" % ", ".join("%s=%d" % kv for kv in sorted(forms.items()))) - print(" experts: %d blobs x %d B, %s" % (man["experts"]["layers"].__len__() * man["n_experts_per_layer"], - man["experts"]["blob_bytes"], man["experts"]["source_type"])) - return 0 - - -def main() -> int: - ap = argparse.ArgumentParser() - sub = ap.add_subparsers(dest="cmd", required=True) - b = sub.add_parser("build") - b.add_argument("--gguf", required=True) - b.add_argument("--out", required=True) - b.add_argument("--layers", type=int, default=None, help="expert layers to emit (default 48)") - b.add_argument("--skip-hash", action="store_true") - v = sub.add_parser("verify") - v.add_argument("--gguf", required=True) - v.add_argument("--out", required=True) - v.add_argument("--limit", type=int, default=None) - v.add_argument("--expert-every", type=int, default=32, - help="verify every Nth expert per layer in the arena (0 disables; the arena is 85%% of " - "the pack and verifying NONE of it is how a pack passes while being wrong)") - n = sub.add_parser("info") - n.add_argument("--out", required=True) - args = ap.parse_args() - if args.cmd == "build": - return build(pathlib.Path(args.gguf), pathlib.Path(args.out), args.layers, args.skip_hash) - if args.cmd == "verify": - return verify(pathlib.Path(args.gguf), pathlib.Path(args.out), args.limit, args.expert_every) - return info(pathlib.Path(args.out)) - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/strata_tokenizer.py b/tools/strata_tokenizer.py deleted file mode 100644 index 08351f7..0000000 --- a/tools/strata_tokenizer.py +++ /dev/null @@ -1,339 +0,0 @@ -"""tools/strata_tokenizer.py - the tokenizer, as the reference implementation of record. - -WHY THIS EXISTS AND WHERE IT SITS. The GGUF carries the whole tokenizer in metadata: `tokenizer.ggml.model` -= `gpt2`, 248,320 `tokens`, 247,587 `merges`, `token_type`, `pre` = `qwen35`, and a Jinja `chat_template`. -None of that needs the 35 GB of weights, so it is extracted into the pack's `tokenizer/` directory -(docs/pack-format.md §6) and this module is what reads it back. A C++ port follows and is tested against -this one. - -THE DECISIVE PROPERTY IS THE ROUND TRIP. Byte-level BPE maps each BYTE to a printable unicode character so -that any UTF-8 input is representable with no UNK token. Every failure mode of that mapping - the wrong -offset for a byte, a merge applied in the wrong order, a pre-tokenizer split that drops a character - still -produces plausible token ids. `decode(encode(s)) == s` is the check that sees them, and it is exact because -the byte layer is lossless. It is asserted over a corpus chosen to hit the boundaries: multi-byte UTF-8, -emoji (4-byte), combining marks, whitespace runs, and C0 control bytes. -""" -from __future__ import annotations - -import json -import pathlib -import sys - -try: - import regex -except ImportError: # the pack export (`extract`) needs no pattern; `encode` says so if it is asked - regex = None - -# ------------------------------------------------------------------ byte <-> unicode (GPT-2 byte-level BPE) -def bytes_to_unicode() -> dict[int, str]: - """The GPT-2 byte encoder: 256 bytes -> 256 printable characters, reversibly. - - Bytes 33..126, 161..172 and 174..255 map to themselves; the remaining 68 (space, newline, the C0 - controls and the high range that would be invisible) are shifted into 256+n so that no byte is - unprintable. The shift is the whole trick and getting its ORDER wrong is invisible in the output ids. - """ - bs = (list(range(0x21, 0x7F)) + list(range(0xA1, 0xAD)) + list(range(0xAE, 0x100))) - cs = bs[:] - n = 0 - for b in range(256): - if b not in bs: - bs.append(b) - cs.append(256 + n) - n += 1 - return dict(zip(bs, (chr(c) for c in cs))) - - -BYTE_TO_UNICODE = bytes_to_unicode() -UNICODE_TO_BYTE = {v: k for k, v in BYTE_TO_UNICODE.items()} - -# The `qwen35` pre-tokenizer, transcribed from the ORACLE rather than from the family resemblance: -# `.ref/llama.cpp/src/llama-vocab.cpp` L396, `case LLAMA_VOCAB_PRE_TYPE_QWEN35`. The commented-out line -# above it is the `tokenizer.json` original, and llama.cpp's active version differs from it - it spells the -# contraction classes out instead of using `(?i:...)`, which is behaviourally the same. -# -# THE `\p{M}` IS THE WHOLE POINT OF THIS BEING TRANSCRIBED. The QWEN3 pattern two cases earlier (L389) is -# the same shape with `\p{L}` where this has `[\p{L}\p{M}]` and without `\p{M}` in the punctuation negation. -# Writing the QWEN3 pattern for `qwen35` looks right, round-trips perfectly, and is wrong: a combining mark -# is `\p{M}`, so without it the mark gets swallowed into the following punctuation run and a token like `_j` -# never forms. It cost 3 strings out of 1875 and only `tokenize_oracle_check` could see it. -QWEN35_PATTERN = ( - r"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])" - r"|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+" - r"|\p{N}" - r"| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*" - r"|\s*[\r\n]+" - r"|\s+(?!\S)" - r"|\s+" -) - - -class Tokenizer: - def __init__(self, tokens: list[str], merges: list[str], token_types: list[int] | None = None, - pre: str = "qwen35", special_ids: dict[str, int] | None = None): - self.tokens = tokens - self.pre = pre - self.token_types = token_types - self.special_ids = special_ids or {} - self.ids = {t: i for i, t in enumerate(tokens)} - if len(self.ids) != len(tokens): - raise ValueError("vocabulary has duplicate tokens: %d entries, %d unique" - % (len(tokens), len(self.ids))) - # Merge rules as (left, right) -> rank. A merge list that is not a total order over its pairs, or one - # naming a token that is not in the vocabulary, would make BPE silently produce different ids than the - # model was trained with, so both are checked here rather than discovered as a bad answer later. - self.ranks: dict[tuple[str, str], int] = {} - for i, m in enumerate(merges): - parts = m.split(" ") - if len(parts) != 2: - raise ValueError("merge %d is not a pair: %r" % (i, m)) - if parts[0] not in self.ids or parts[1] not in self.ids: - raise ValueError("merge %d names a token outside the vocabulary: %r" % (i, m)) - self.ranks[(parts[0], parts[1])] = i - # Without the `regex` module (the VMs' system python) the export still works: vocab, merges, token types - # and the template need no pattern. Encoding does, and `_encode_plain` refuses by name instead. - self._re = regex.compile(QWEN35_PATTERN) if regex is not None else None - - # The literals matched directly instead of being run through BPE. GGUF token types: 3 = CONTROL, - # 4 = USER_DEFINED. The two classes behave DIFFERENTLY and llama.cpp's own tokenizer settled which: - # - # * type 4 (USER_DEFINED: ``, ``, ``, ...) is matched ALWAYS, - # with or without parse_special. - # * type 3 (CONTROL: `<|im_start|>`, `<|im_end|>`, `<|endoftext|>`, ...) is matched ONLY when - # parse_special is set. - # - # Measured, not assumed: with parse_special=False the oracle still emitted `` as one - # token and mine emitted four, and the three disagreements were exactly the type-4 cases while every - # type-3 case agreed. Treating both classes alike costs 3 strings in 1229 and silently changes a chat - # prompt, because `<|im_end|>` decomposed into ordinary pieces is not the token the model expects. - self.special_tokens: dict[str, int] = {} - if token_types: - for i, ty in enumerate(token_types): - if ty in (3, 4): - self.special_tokens[tokens[i]] = i - always = [t for t, i in self.special_tokens.items() if token_types and token_types[i] == 4] - # Longest literal first, or `<|im_end|>` could match a shorter prefix of itself. `regex.escape` so a - # token containing regex metacharacters (several do: `<|`, `[`, `(`) is matched literally. - self._always_re = self._alt(always) - self._special_re = self._alt(list(self.special_tokens)) - - @staticmethod - def _alt(literals: list[str]): - if not literals or regex is None: - return None - return regex.compile("|".join(regex.escape(s) for s in sorted(literals, key=len, reverse=True))) - - # -------------------------------------------------------------- constructors - @classmethod - def from_gguf(cls, path) -> "Tokenizer": - sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) - from gguf_reader import GGUFFile - md = GGUFFile(pathlib.Path(path)).metadata - need = ["tokenizer.ggml.tokens", "tokenizer.ggml.merges"] - missing = [k for k in need if k not in md] - if missing: - raise ValueError("GGUF is missing %s; it does not carry a tokenizer" % ", ".join(missing)) - model = md.get("tokenizer.ggml.model") - if model != "gpt2": - raise ValueError("expected a byte-level BPE tokenizer (model 'gpt2'), got %r" % model) - special = {k: int(md[k]) for k in md - if k.startswith("tokenizer.ggml.") and k.endswith("_token_id")} - return cls(list(md["tokenizer.ggml.tokens"]), list(md["tokenizer.ggml.merges"]), - list(md.get("tokenizer.ggml.token_type") or []) or None, - md.get("tokenizer.ggml.pre", "qwen35"), special) - - # -------------------------------------------------------------- the algorithm - def _bpe(self, word: str) -> list[str]: - """Merge `word` (already byte-mapped) by LOWEST RANK first, repeatedly - not left to right. - - Applying merges in list order rather than rank order is the classic BPE bug: it produces a different - segmentation and a plausible token count. - - A word longer than HEAP_MIN symbols (a long CJK run, a minified blob: one pre-token piece of thousands of - bytes) goes to _bpe_heap, which applies the same merges in the same order without rescanning every pair - after each merge (#268: that rescan is O(n^2) and took seconds on an 8K-character CJK run). - """ - if len(word) > self.HEAP_MIN: - return self._bpe_heap(word) - parts = list(word) - while len(parts) > 1: - best, best_rank = None, None - for i in range(len(parts) - 1): - r = self.ranks.get((parts[i], parts[i + 1])) - if r is not None and (best_rank is None or r < best_rank): - best, best_rank = i, r - if best is None: - break - parts[best:best + 2] = [parts[best] + parts[best + 1]] - return parts - - HEAP_MIN = 64 # words up to this many symbols keep the scan above, unchanged - - def _bpe_heap(self, word: str) -> list[str]: - """_bpe's result in O(n log n): the symbols as a linked list, every adjacent pair with a rank in a heap - keyed (rank, position). Popping the lowest rank and then the lowest position is exactly the order the - scan picks (its strict `<` keeps the leftmost of equal ranks), and a symbol's position is where it starts - in the word, which only its left neighbour's merge can change - so a popped pair whose two symbols are - no longer the ones it was pushed with is stale and skipped.""" - import heapq - parts = list(word) - n = len(parts) - nxt = list(range(1, n)) + [-1] - prv = list(range(-1, n - 1)) - ranks = self.ranks - heap = [] - for i in range(n - 1): - r = ranks.get((parts[i], parts[i + 1])) - if r is not None: - heap.append((r, i, parts[i], parts[i + 1])) - heapq.heapify(heap) - while heap: - r, i, left, right = heapq.heappop(heap) - j = nxt[i] - if parts[i] != left or j < 0 or parts[j] != right: - continue # stale: one of its symbols has merged since - parts[i] = left + right - parts[j] = None # j is gone: i takes its place in the list - k = nxt[j] - nxt[i] = k - if k >= 0: - prv[k] = i - r2 = ranks.get((parts[i], parts[k])) - if r2 is not None: - heapq.heappush(heap, (r2, i, parts[i], parts[k])) - p = prv[i] - if p >= 0: - r2 = ranks.get((parts[p], parts[i])) - if r2 is not None: - heapq.heappush(heap, (r2, p, parts[p], parts[i])) - return [s for s in parts if s is not None] - - def _encode_plain(self, text: str) -> list[int]: - if self._re is None: - raise ImportError("tokenizing needs the `regex` module (pip install regex): the qwen35 pre-tokenizer " - "pattern uses \\p{L} / \\p{M} classes the standard `re` does not have") - out: list[int] = [] - for piece in self._re.findall(text): - mapped = "".join(BYTE_TO_UNICODE[b] for b in piece.encode("utf-8")) - for tok in self._bpe(mapped): - i = self.ids.get(tok) - if i is None: - raise KeyError("BPE produced a token outside the vocabulary: %r" % tok) - out.append(i) - return out - - def _encode_matching(self, text: str, pat, plain=()) -> list[int]: - """Encode `text`, emitting any literal `pat` matches as single tokens and BPE-ing the rest. - - The split happens on the RAW text, before the byte mapping, because a special token's string is a - literal to match rather than bytes to decompose. Everything between the matches is tokenized - normally - which is why a near-miss like `<|im_star` still costs ordinary tokens. A match that starts - inside one of the `plain` (start, end) spans is left to the text around it (#537). - """ - if pat is None: - return self._encode_plain(text) - out: list[int] = [] - pos = 0 - for m in pat.finditer(text): - if plain and any(a <= m.start() < b for a, b in plain): - continue - if m.start() > pos: - out.extend(self._encode_plain(text[pos:m.start()])) - out.append(self.special_tokens[m.group(0)]) - pos = m.end() - if pos < len(text): - out.extend(self._encode_plain(text[pos:])) - return out - - def encode(self, text: str, parse_special: bool = False, plain=()) -> list[int]: - """Tokenize `text`. - - `parse_special` controls only the type-3 CONTROL literals such as `<|im_end|>`; the type-4 - USER_DEFINED ones such as `` are matched either way. See the note in `__init__`. - `plain`: (start, end) spans of `text` that are ordinary text even where they spell a literal - a - `` quoted in a message (#537) - and are tokenized with the text around them. - """ - return self._encode_matching(text, self._special_re if parse_special else self._always_re, plain) - - def token_bytes(self, i: int) -> bytes: - """The raw bytes of one token (a multi-byte character can be split across tokens).""" - cache = self.__dict__.setdefault("_bytes_cache", {}) - b = cache.get(i) - if b is None: - if i < 0 or i >= len(self.tokens): - raise IndexError("token id %d is outside the vocabulary (%d)" % (i, len(self.tokens))) - raw = bytearray() - for ch in self.tokens[i]: - v = UNICODE_TO_BYTE.get(ch) - if v is None: - raise KeyError("token %d contains a character outside the byte alphabet: %r" % (i, ch)) - raw.append(v) - b = cache[i] = bytes(raw) - return b - - def decode(self, ids: list[int], errors: str = "replace") -> str: - return b"".join(self.token_bytes(i) for i in ids).decode("utf-8", errors=errors) - - -# ------------------------------------------------------------------ the pack's tokenizer/ directory -def extract(gguf_path, out_dir) -> dict: - """Write the tokenizer into `/tokenizer/` so the engine never opens the weight shards for it.""" - out = pathlib.Path(out_dir) / "tokenizer" - out.mkdir(parents=True, exist_ok=True) - tk = Tokenizer.from_gguf(gguf_path) - cfg = { - "model": "gpt2", - "pre": tk.pre, - "vocab_size": len(tk.tokens), - "n_merges": len(tk.ranks), - "special_ids": tk.special_ids, - "add_bos_token": False, - # The pattern is SHIPPED, not recomputed by the reader: it is transcribed from llama.cpp for the - # declared `pre` type, and a C++ port that re-derived it would be free to get `\p{M}` wrong again. - "pre_pattern": QWEN35_PATTERN, - "pre_pattern_source": ".ref/llama.cpp src/llama-vocab.cpp L396 (LLAMA_VOCAB_PRE_TYPE_QWEN35)", - } - (out / "vocab.json").write_text(json.dumps(tk.ids, ensure_ascii=False), encoding="utf-8") - (out / "merges.txt").write_text("\n".join("%s %s" % k for k, _ in - sorted(tk.ranks.items(), key=lambda kv: kv[1])), encoding="utf-8") - (out / "token_type.json").write_text(json.dumps(tk.token_types), encoding="utf-8") - (out / "tokenizer.json").write_text(json.dumps(cfg, ensure_ascii=False, indent=1), encoding="utf-8") - # the model's own chat template: fine-tunes change it (Swift 1.5 differs from Qwen3.8-Flash-Next's) - sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) - from gguf_reader import GGUFFile - tpl = GGUFFile(pathlib.Path(gguf_path)).metadata.get("tokenizer.chat_template") - if tpl: - (out / "chat_template.jinja").write_text(tpl, encoding="utf-8", newline="\n") - return cfg - - -def main() -> int: - import argparse - ap = argparse.ArgumentParser() - ap.add_argument("--gguf", required=True) - ap.add_argument("--out", required=True) - ap.add_argument("--check", action="store_true", help="round-trip a corpus and report") - args = ap.parse_args() - cfg = extract(args.gguf, args.out) - print("tokenizer/: vocab %d, merges %d, pre %s, specials %s" - % (cfg["vocab_size"], cfg["n_merges"], cfg["pre"], cfg["special_ids"])) - if args.check: - tk = Tokenizer.from_gguf(args.gguf) - corpus = ["", "Hello, world!", " leading and trailing ", "a\n\n\nb", - "def f(x):\n\treturn x # comment\n", "\u4f60\u597d\uff0c\u4e16\u754c", "\u0645\u0631\u062d\u0628\u0627", - "\U0001f600\U0001f680\U0001f1fa\U0001f1f8", "e\u0301\u0301 combining", "\x00\x01\x7f control", - "\u00a0non-breaking\u00a0space", "1234567890", "MixedCASE_and-dashes", "\r\n\r\n", "\u2028\u2029", - "x" * 5000] - bad = 0 - for s in corpus: - ids = tk.encode(s) - back = tk.decode(ids) - if back != s: - print(" *** ROUND TRIP FAILED *** %r -> %d ids -> %r" % (s[:40], len(ids), back[:40])) - bad += 1 - print("round trip: %d strings, %d failed" % (len(corpus), bad)) - return 0 if bad == 0 else 1 - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/test_draft_vocab.py b/tools/test_draft_vocab.py deleted file mode 100644 index 2375a22..0000000 --- a/tools/test_draft_vocab.py +++ /dev/null @@ -1,47 +0,0 @@ -"""Tests for tools/draft_vocab.py's corpus coverage mode (#597): the most frequent tokens of a corpus that together cover -a given share of its occurrences. No model, no GPU. - - python -m unittest tools.test_draft_vocab -""" -from __future__ import annotations - -import sys -import tempfile -import unittest -from collections import Counter -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -import draft_vocab as DV # noqa: E402 - - -class Coverage(unittest.TestCase): - def test_most_frequent_first_until_the_share_is_covered(self): - c = Counter({7: 50, 3: 30, 9: 15, 4: 5}) # 100 occurrences - self.assertEqual(DV.covering(c, 0.5), [7]) - self.assertEqual(DV.covering(c, 0.8), [7, 3]) - self.assertEqual(DV.covering(c, 0.81), [7, 3, 9]) - self.assertEqual(DV.covering(c, 1.0), [7, 3, 9, 4]) - - def test_ties_take_the_lower_id_first(self): - self.assertEqual(DV.covering(Counter({5: 10, 2: 10, 8: 10}), 0.5), [2, 5]) - - def test_share_outside_a_subset(self): - c = Counter({1: 60, 2: 30, 3: 10}) - self.assertAlmostEqual(DV.outside(c, [1]), 0.4) - self.assertAlmostEqual(DV.outside(c, [1, 2, 3]), 0.0) - self.assertEqual(DV.outside(Counter(), [1]), 0.0) - - def test_corpus_counts_reads_every_file(self): - class Tok: # one id per character - def encode(self, text): - return [ord(ch) for ch in text] - with tempfile.TemporaryDirectory() as d: - a, b = Path(d) / "a.txt", Path(d) / "b.txt" - a.write_text("été", encoding="utf-8") - b.write_text("eté", encoding="utf-8") - self.assertEqual(DV.corpus_counts(Tok(), [a, b]), Counter({ord("é"): 3, ord("t"): 2, ord("e"): 1})) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_iq_pack.py b/tools/test_iq_pack.py deleted file mode 100644 index 10213ab..0000000 --- a/tools/test_iq_pack.py +++ /dev/null @@ -1,840 +0,0 @@ -"""Focused pack compatibility tests; run .venv/bin/python -m unittest discover -s tools -p test_iq_pack.py.""" -import contextlib -import hashlib -import io -import json -from pathlib import Path -import sys -import tempfile -import unittest -from unittest.mock import patch - -import numpy as np - -sys.path.insert(0, str(Path(__file__).resolve().parent)) # runnable from the repo root too - -from _paths import add_gguf_py -add_gguf_py() -from gguf import GGUFWriter, GGMLQuantizationType as Q, quants -import iq_pack - - -def write_gguf(path, tensors, split=None, arch=True, kv=None, architecture="qwen4exp"): - """`split` = (no, count, tensors): llama.cpp's gguf-split keys (0-based split.no); `kv` = extra u32 keys; - `architecture` = the general.architecture string (qwen4exp, or qwen35moe for the Qwen3.6 fixtures).""" - writer = GGUFWriter(path, architecture) - if not arch: # a later shard of a split: no model metadata - writer.kv_data[0].pop("general.architecture", None) - for key, value in (kv or {}).items(): - writer.add_uint32(key, value) - if split is not None: - writer.add_uint16("split.no", split[0]) - writer.add_uint16("split.count", split[1]) - writer.add_int32("split.tensors.count", split[2]) - for name, values, kind in tensors: - writer.add_tensor(name, quants.quantize(values, kind), raw_dtype=kind) - writer.write_header_to_file() - writer.write_kv_data_to_file() - writer.write_tensors_to_file() - writer.close() - - -class CompatibilityTests(unittest.TestCase): - def test_bf16_halfway_rounds_to_even(self): - values = np.array([0x3F808000, 0x3F818000, 0xBF808000, 0xBF818000], dtype=np.uint32) - got = np.frombuffer(iq_pack.bf16_bytes(values.view(np.uint8), "F32"), dtype=np.uint16) - np.testing.assert_array_equal(got, [0x3F80, 0x3F82, 0xBF80, 0xBF82]) - - def test_nonfinite_conversion_refused(self): - with self.assertRaisesRegex(ValueError, "non-finite"): - iq_pack.bf16_bytes(np.array([np.nan], dtype=np.float32).view(np.uint8), "F32") - - def test_projection_conversion_and_native_bytes(self): - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: - root = Path(tmp) - source = root / "model.gguf" - values = np.linspace(-1, 1, 256, dtype=np.float32).reshape(2, 128) - router = np.full((2, 128), 0.10001, dtype=np.float32) - names = ["blk.0.hc_attn_down.weight", "output_hc_up.weight", - "blk.0.ssm_alpha.weight", "blk.3.indexer.q_proj.weight", "blk.1.ple_value.weight"] - write_gguf(source, [(n, values, Q.Q8_0) for n in names] + [ - ("blk.1.ple_key.weight", values, Q.Q8_0), - ("blk.0.ffn_gate_inp.weight", router, Q.F32), - ("blk.0.attn_qkv.weight", values, Q.Q8_0), - ("per_layer_token_embd.weight", values, Q.Q8_0), - ]) - before = source.read_bytes() - model = iq_pack.Model(source) - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(iq_pack.index_standalone(source, root, model, True), 0) - _, rows = iq_pack.read_index(root / "index.txt") - dense = (root / "dense.bin").read_bytes() - # A scalar oracle independent of the BF16 encoder: choose the nearest BF16 value, - # using the even representation at exact ties. - decoded = quants.dequantize(quants.quantize(values, Q.Q8_0), Q.Q8_0).ravel() - def rounded(x): - bits = int(np.float32(x).view(np.uint32)) - return (bits >> 16) + ((bits & 65535) > 32768 or - ((bits & 65535) == 32768 and (bits >> 16) & 1)) - expected = np.array([rounded(x) for x in decoded], dtype=np.uint16) - for name in names: - row = rows[name] - self.assertEqual(row[2], "4") - offset, size = int(row[3]), int(row[4]) - np.testing.assert_array_equal(np.frombuffer(dense[offset:offset + size], dtype=np.uint16), expected) - for name in ["blk.0.attn_qkv.weight", "blk.1.ple_key.weight"]: # a Q8_0 PLE key stays native - native = rows[name] - self.assertEqual(native[2], "0") - self.assertEqual(native[4], "0") - self.assertEqual(native[9], "8") - self.assertNotIn("per_layer_token_embd.weight", rows) - self.assertEqual(source.read_bytes(), before) - self.assertEqual(len(json.loads((root / "compat-bf16.json").read_text())["tensors"]), 6) - conv = json.loads((root / "conversions.json").read_text()) - self.assertEqual(sorted(r["name"] for r in conv["tensors"]), sorted(names + ["blk.0.ffn_gate_inp.weight"])) - - def test_default_still_refuses_inexact_f32_router(self): - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: - root = Path(tmp) - source = root / "model.gguf" - write_gguf(source, [("blk.0.ffn_gate_inp.weight", np.full((2, 32), 0.10001, np.float32), Q.F32)]) - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 1) - - def test_existing_bf16_pack_remains_byte_identical(self): - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: - root = Path(tmp) - source = root / "model.gguf" - values = np.linspace(-2, 2, 256, dtype=np.float32).reshape(2, 128) - write_gguf(source, [("blk.0.hc_attn_down.weight", values, Q.BF16)]) - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 0) - self.assertEqual((root / "dense.bin").read_bytes(), quants.quantize(values, Q.BF16).tobytes()) - - def test_quantized_control_weights_need_explicit_conversion(self): - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: - root = Path(tmp) - source = root / "model.gguf" - write_gguf(source, [("blk.0.hc_attn_down.weight", np.ones((2, 32), np.float32), Q.Q8_0)]) - (root / "dense.bin").write_bytes(b"previous pack") - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 1) - self.assertEqual((root / "dense.bin").read_bytes(), b"previous pack") - - def test_q2_ple_and_large_tensors_stay_native(self): - self.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "Q2_0")) - self.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "Q8_0")) - self.assertTrue(iq_pack.needs_bf16("blk.1.ple_key.weight", "IQ3_XXS")) - for name in ["blk.0.ffn_gate_exps.weight", "token_embd.weight", "output.weight", - "per_layer_token_embd.weight", "blk.0.attn_qkv.weight"]: - self.assertFalse(iq_pack.needs_bf16(name, "IQ3_XXS")) - - def test_experts_bin_is_kept_only_with_this_ggufs_blobs(self): - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: - root = Path(tmp) - out = root / "pack" - (out / "tokenizer").mkdir(parents=True) - for name in ["vocab.json", "chat_template.jinja"]: - (out / "tokenizer" / name).touch() - - def model(name, scale): - path = root / name - write_gguf(path, [("blk.%d.hc_attn_down.weight" % l, np.ones((2, 32), np.float32), Q.BF16) - for l in range(3)] + - [("blk.%d.ffn_gate_inp.weight" % l, np.ones((4, 32), np.float32), Q.BF16) - for l in range(3)] + - [("blk.%d.ffn_%s_exps.weight" % (l, r), - scale * np.arange(4 * 2 * 32, dtype=np.float32).reshape(4, 2, 32) / 256, Q.Q8_0) - for l in range(3) for r in ("gate", "up", "down")]) - return path - - def pack(path): - log = io.StringIO() - argv = ["iq_pack.py", "--gguf", str(path), "--out", str(out), "--experts-bin"] - with patch.object(sys, "argv", argv), contextlib.redirect_stdout(log): - self.assertEqual(iq_pack.main(), 0) - return log.getvalue() - - first = model("a.gguf", 1) - pack(first) - written = (out / "experts.bin").read_bytes() - self.assertIn("not rewritten", pack(first)) - self.assertEqual((out / "experts.bin").read_bytes(), written) - # the same geometry with other weights under the same file name: the size and the sidecar (shard names - # and sizes, native_experts.txt) match, the contents do not - second = model("a.gguf", -1) - self.assertIn("not this GGUF's expert blobs", pack(second)) - rewritten = (out / "experts.bin").read_bytes() - self.assertEqual(len(rewritten), len(written)) - self.assertNotEqual(rewritten, written) - self.assertIn("not rewritten", pack(second)) - - def test_layout_only_writes_the_table_and_the_census(self): - """--layout-only (the Qwen3.6 port's step 2): native_experts.txt alone, the census printed, nothing else.""" - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: - root = Path(tmp) - out = root / "pack" - path = root / "m.gguf" - write_gguf(path, [("blk.%d.ffn_gate_inp.weight" % l, np.ones((4, 32), np.float32), Q.F32) - for l in range(2)] + - [("blk.%d.ffn_%s_exps.weight" % (l, r), - np.arange(4 * 2 * 32, dtype=np.float32).reshape(4, 2, 32) / 256, Q.Q8_0) - for l in range(2) for r in ("gate", "up", "down")]) - log = io.StringIO() - with patch.object(sys, "argv", ["iq_pack.py", "--gguf", str(path), "--out", str(out), "--layout-only"]), \ - contextlib.redirect_stdout(log): - self.assertEqual(iq_pack.main(), 0) - self.assertEqual(sorted(p.name for p in out.iterdir()), ["native_experts.txt"]) - text = (out / "native_experts.txt").read_text() - rows = [line.split() for line in text.splitlines() if line and not line.startswith("#")] - self.assertEqual([r[0] for r in rows], ["0", "1"]) - blob = 3 * 2 * 32 * 34 // 32 # gate | up | down, Q8_0 rows of 32 values = 34 bytes - self.assertEqual([int(r[4]) for r in rows], [blob, blob]) - self.assertIn("(n_expert 4, total %d;" % (2 * 4 * blob), text.splitlines()[0]) - self.assertIn("2 layers x 4 experts", log.getvalue()) - self.assertIn("gate/up Q8_0 down Q8_0 blob %9d B: layers [0, 1]" % blob, log.getvalue()) - self.assertIn("wrote %s" % (out / "native_experts.txt"), log.getvalue()) - - def test_nextn_block_is_left_out_of_the_layout(self): - """nextn_predict_layers 1 (the -MTP files): the last block's experts belong to the drafter's pack.""" - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: - root = Path(tmp) - out = root / "pack" - path = root / "mtp.gguf" - write_gguf(path, [("blk.%d.ffn_gate_inp.weight" % l, np.ones((4, 32), np.float32), Q.F32) - for l in range(3)] + - [("blk.%d.ffn_%s_exps.weight" % (l, r), - np.arange(4 * 2 * 32, dtype=np.float32).reshape(4, 2, 32) / 256, Q.Q8_0) - for l in range(3) for r in ("gate", "up", "down")], - kv={"qwen4exp.nextn_predict_layers": 1}) - log = io.StringIO() - with patch.object(sys, "argv", ["iq_pack.py", "--gguf", str(path), "--out", str(out), "--layout-only"]), \ - contextlib.redirect_stdout(log): - self.assertEqual(iq_pack.main(), 0) - rows = [line.split() for line in (out / "native_experts.txt").read_text().splitlines() - if line and not line.startswith("#")] - self.assertEqual([r[0] for r in rows], ["0", "1"]) - self.assertIn("1 draft (nextn) block(s) at blk.2 and up are left to the MTP pack; 2 trunk layers", log.getvalue()) - self.assertIn("2 layers x 4 experts", log.getvalue()) - - def test_fused_gate_up_experts_are_refused_by_name(self): - """llama.cpp's fused ffn_gate_up_exps form: refused before anything is written.""" - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: - root = Path(tmp) - out = root / "pack" - path = root / "fused.gguf" - write_gguf(path, [("blk.0.ffn_gate_inp.weight", np.ones((4, 32), np.float32), Q.F32), - ("blk.0.ffn_gate_up_exps.weight", - np.arange(4 * 4 * 32, dtype=np.float32).reshape(4, 4, 32) / 256, Q.Q8_0), - ("blk.0.ffn_down_exps.weight", - np.arange(4 * 2 * 32, dtype=np.float32).reshape(4, 2, 32) / 256, Q.Q8_0)]) - log = io.StringIO() - with patch.object(sys, "argv", ["iq_pack.py", "--gguf", str(path), "--out", str(out), "--layout-only"]), \ - contextlib.redirect_stdout(log): - self.assertEqual(iq_pack.main(), 1) - self.assertIn("blk.0.ffn_gate_up_exps.weight: the experts are fused", log.getvalue()) - self.assertFalse((out / "native_experts.txt").exists()) - - def test_snapshot_symlinks_keep_split_discovery(self): - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: - root = Path(tmp) - snap = root / "snapshot" - snap.mkdir() - first = snap / "model-00001-of-00002.gguf" - second = snap / "model-00002-of-00002.gguf" - write_gguf(root / "blob1", [ - ("blk.0.hc_attn_down.weight", np.ones((2, 32), np.float32), Q.Q8_0), - ("blk.0.ffn_gate_inp.weight", np.ones((512, 32), np.float32), Q.BF16), - ], split=(0, 2, 5)) - write_gguf(root / "blob2", [(f"blk.0.ffn_{r}_exps.weight", np.ones((512, 2, 32), np.float32), Q.Q8_0) - for r in ("gate", "up", "down")], split=(1, 2, 5), arch=False) - try: - first.symlink_to(root / "blob1") - except OSError: # Windows without Developer Mode or admin rights - self.skipTest("symlinks are not available here") - with self.assertRaisesRegex(FileNotFoundError, "missing model shards"): - iq_pack.Model(first) - second.symlink_to(root / "blob2") - out = root / "pack" - (out / "tokenizer").mkdir(parents=True) - for name in ["vocab.json", "chat_template.jinja"]: - (out / "tokenizer" / name).touch() - with patch.object(sys, "argv", ["iq_pack.py", "--gguf", str(first), "--out", str(out), "--compat-bf16"]): - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(iq_pack.main(), 0) - expert_index = (out / "native_experts.txt").read_text() - self.assertIn(second.name, expert_index) - self.assertIn("n_expert 512,", expert_index) - (root / "blob2").write_bytes((root / "blob2").read_bytes()[:-64]) - with self.assertRaisesRegex(ValueError, "truncated tensor"): - iq_pack.Model(first) - - - -def bits(u32): - return np.array(u32, dtype=np.uint32).view(np.float32) - - -def pack_one(root, tensors, *flags): - """A one-file model of `tensors` packed into `root` (index only): (rc, printed, rows, dense, conversions).""" - source = root / "model.gguf" - write_gguf(source, tensors) - buf = io.StringIO() - with contextlib.redirect_stdout(buf): - rc = iq_pack.index_standalone(source, root, iq_pack.Model(source), *flags) - if rc: - return rc, buf.getvalue(), None, None, None - _, rows = iq_pack.read_index(root / "index.txt") - conv = json.loads((root / "conversions.json").read_text()) - return rc, buf.getvalue(), rows, (root / "dense.bin").read_bytes(), conv - - -def stored(rows, dense, name, dtype): - row = rows[name] - return np.frombuffer(dense[int(row[3]):int(row[3]) + int(row[4])], dtype=dtype) - - -class ConversionTests(unittest.TestCase): - """CS2: FORM decides the engine's form; exact F32->BF16 by default, rounding only with --compat-bf16, the PLE - conv F32 -> F16 by the loader (index kind 3), non-finite values refused, every conversion in conversions.json.""" - - def test_exact_f32_to_bf16_by_default(self): - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: - x = bits(np.arange(64, dtype=np.uint32).reshape(2, 32) << 16 | 0x3F000000) # BF16 values held as F32 - rc, log, rows, dense, conv = pack_one(Path(tmp), [("blk.0.hc_attn_inject.weight", x, Q.F32), - ("blk.0.ssm_beta.weight", x, Q.F32), - ("blk.0.ssm_norm.weight", x, Q.F32)]) - self.assertEqual(rc, 0, log) - for name in ["blk.0.hc_attn_inject.weight", "blk.0.ssm_beta.weight"]: - self.assertEqual(rows[name][2], "4") - np.testing.assert_array_equal(stored(rows, dense, name, "> 16).ravel()) - self.assertEqual(rows["blk.0.ssm_norm.weight"][2], "2") # F32 form: as stored - recs = {r["name"]: r for r in conv["tensors"]} - self.assertEqual(set(recs), {"blk.0.hc_attn_inject.weight", "blk.0.ssm_beta.weight"}) - r = recs["blk.0.ssm_beta.weight"] - self.assertEqual((r["src_type"], r["dst_type"], r["exact"], r["max_abs_err"], r["shard"]), - ("F32", "BF16", True, 0.0, "model.gguf")) - self.assertEqual(r["source_sha256"], hashlib.sha256(x.tobytes()).hexdigest()) - self.assertEqual(conv["schema"], 1) - self.assertEqual(conv["source_shards"], [{"name": "model.gguf", - "size": (Path(tmp) / "model.gguf").stat().st_size}]) - - def test_inexact_f32_rounds_only_with_compat(self): - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: - x = np.linspace(-1, 1, 64, dtype=np.float32).reshape(2, 32) + np.float32(1e-4) - rc, log, *_ = pack_one(Path(tmp), [("blk.0.hc_ffn_inject.weight", x, Q.F32)]) - self.assertEqual(rc, 1) - self.assertIn("not BF16", log) - rc, log, rows, dense, conv = pack_one(Path(tmp), [("blk.0.hc_ffn_inject.weight", x, Q.F32)], True) - self.assertEqual(rc, 0, log) - got = stored(rows, dense, "blk.0.hc_ffn_inject.weight", "